package roles

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 role models.Role
	err := json.NewDecoder(r.Body).Decode(&role)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusBadRequest)
		return
	}
	role_uuid := r.PathValue("role_uuid")
	role.ID, err = uuid.Parse(role_uuid)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusBadRequest)
		return
	}

	_, err = core.DB.NewUpdate().
		Model(&role).
		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:    role,
	}.Respond(w, http.StatusOK)

}
