package controller

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

	"xengineering.eu/ceres/model"

	"github.com/gorilla/mux"
)

func RecipeCreate(w http.ResponseWriter, r *http.Request) {
	recipe := model.Recipe{}
	recipe.Title = "recipe without title"

	err := recipe.Create()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, "/recipe/" + recipe.Id + "?view=recipe-edit", 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
	}

	err = recipe.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`]

	err := recipe.Delete()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

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