package shortcodes

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

	"fr.latosa-escrima/core"
	"fr.latosa-escrima/core/models"
)

func HandleNew(w http.ResponseWriter, r *http.Request) {
	var shortcode models.Shortcode
	err := json.NewDecoder(r.Body).Decode(&shortcode)
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}
	err = shortcode.Validate()
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	_, err = core.DB.NewInsert().Model(&shortcode).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: "Shortcode inserted.",
	}.Respond(w, http.StatusCreated)

}
