package server

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

	"github.com/google/uuid"
)

type upsertRequest struct {
	Title    string `json:"title"`
	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.Title == "" {
		u.Title = u.ID
	}
	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
}

func (s *Server) upserts(w http.ResponseWriter, r *http.Request) {
	upsert, err := newUpsertRequest(r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	log.Println("received", upsert)
	http.Error(w, "not impl", http.StatusNotImplemented)
}
