package controller

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"

	"xengineering.eu/ceres/model"
)

func RecipeCreate(db *model.DB) http.Handler {
	return http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			buf, err := io.ReadAll(r.Body)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			recipe := model.Recipe{}
			err = json.Unmarshal(buf, &recipe)
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}

			recipe.LastChanged = fmt.Sprint(time.Now().Unix())
			recipe.Created = recipe.LastChanged

			var obj model.Object = &recipe
			err = db.Transaction(obj.Create)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			http.Redirect(w, r, "/recipe/"+recipe.Id, http.StatusSeeOther)
		},
	)
}

func RecipeUpdate(db *model.DB) http.Handler {
	return http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			buf, err := io.ReadAll(r.Body)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			recipe := model.Recipe{}
			err = json.Unmarshal(buf, &recipe)
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}

			if recipe.Id != r.PathValue("id") {
				http.Error(w, "IDs in URL and JSON do not match", http.StatusBadRequest)
				return
			}

			recipe.LastChanged = fmt.Sprint(time.Now().Unix())

			var obj model.Object = &recipe
			err = db.Transaction(obj.Update)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			http.Redirect(w, r, "/recipe/"+recipe.Id, http.StatusSeeOther)
		},
	)
}

func RecipeDelete(db *model.DB) http.Handler {
	return http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			recipe := model.Recipe{}
			recipe.Id = r.PathValue("id")

			var obj model.Object = &recipe
			err := db.Transaction(obj.Delete)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			http.Redirect(w, r, "/recipes", http.StatusSeeOther)
		},
	)
}