package server

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"local/firestormy/config"
	"local/firestormy/config/ns"

	"github.com/google/uuid"
)

type upsertRequest struct {
	ID       string `json:"id"`
	Language string `json:"language"`
	Cron     string `json:"cron"`
	Script   string `json:"script"`
}

func newUpsertRequest(r io.Reader) (upsertRequest, error) {
	u := upsertRequest{}
	if err := json.NewDecoder(r).Decode(&u); err != nil {
		return u, err
	}
	err := u.validate()
	return u, err
}

func (u *upsertRequest) validate() error {
	if u.ID == "" {
		u.ID = uuid.New().String()
	} else if _, err := config.Store.Get(u.ID, ns.Jobs...); err != nil {
		return fmt.Errorf("ID provided but not accessible: %v", err)
	}
	if u.Language == "" {
		return errors.New("language required")
	}
	if u.Cron == "" {
		return errors.New("cron required")
	}
	if u.Script == "" {
		return errors.New("script required")
	}
	return nil
}
