package blogs

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

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

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

	token, ok := r.Context().Value("token").(*jwt.Token)
	if !ok {
		core.JSONError{
			Status:  core.Error,
			Message: "Couldn't retrieve your JWT.",
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok {
		core.JSONError{
			Status:  core.Error,
			Message: "Invalid token claims.",
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	id := claims["user_id"].(string)
	author_uuid, err := uuid.Parse(id)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: "Invalid token claims.",
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	blog.AuthorID = author_uuid

	if _, err := core.DB.NewInsert().
		Model(&blog).
		Exec(context.Background()); err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusNotAcceptable)
		return
	}

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