package events

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

	"fr.latosa-escrima/core"
	"fr.latosa-escrima/core/models"
	"github.com/google/uuid"
)

func HandleUpdate(w http.ResponseWriter, r *http.Request) {
	var event models.Event
	err := json.NewDecoder(r.Body).Decode(&event)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusBadRequest)
		return
	}

	event_uuid := r.PathValue("event_uuid")
	event.EventID, err = uuid.Parse(event_uuid)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusBadRequest)
		return
	}

	_, err = core.DB.NewUpdate().
		Model(&event).
		OmitZero().
		WherePK().
		Exec(context.Background())
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: "Event not found.",
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	core.JSONSuccess{
		Status:  core.Success,
		Message: "Event updated",
		Data:    event,
	}.Respond(w, http.StatusOK)
}
