package blogs

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

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

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

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

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

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