package roles

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

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

func HandleNew(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.StatusInternalServerError)
		return
	}

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