package server

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"local/firestormy/config"
	"local/firestormy/config/ns"
	"local/firestormy/scheduler"
	"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"`
	Disabled bool   `json:"disabled"`
}

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 == "" {
	} 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 (u *upsertRequest) toJob() (*scheduler.Job, error) {
	j, err := scheduler.NewJob(scheduler.Bash, u.Cron, u.Script)
	if err != nil {
		return nil, err
	}
	j.Title = u.Title
	j.Name = u.ID
	j.Disabled = u.Disabled
	return j, err
}

func (s *Server) upsert(w http.ResponseWriter, r *http.Request) {
	upsert, err := newUpsertRequest(r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	job, err := upsert.toJob()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if job.Name == "" {
		job.Name = uuid.New().String()
		if job.Title == "" {
			job.Title = job.Name
		}
		if err := scheduler.Schedule.Add(job); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if err := scheduler.Schedule.Update(job); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	json.NewEncoder(w).Encode(map[string]interface{}{})
}
