package media

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

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

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

}
