package controller

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

	"xengineering.eu/ceres/model"

	"github.com/gorilla/mux"
)

func RecipeCreate(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 = model.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(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 != mux.Vars(r)[`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 = model.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(w http.ResponseWriter, r *http.Request) {
	recipe := model.Recipe{}
	recipe.Id = mux.Vars(r)[`id`]

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

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