package roles

import (
	"context"
	"net/http"

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

func HandleRole(w http.ResponseWriter, r *http.Request) {
	uuid := r.PathValue("role_uuid")
	var role models.Role
	count, err := core.DB.NewSelect().
		Model(&role).
		Where("id = ?", uuid).
		Relation("Permissions").
		Limit(1).
		ScanAndCount(context.Background())
	if count == 0 {
		core.JSONError{
			Status:  core.Error,
			Message: "The role requested was not found.",
		}.Respond(w, http.StatusNotFound)
		return
	}
	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	core.JSONSuccess{
		Status:  core.Success,
		Message: "Role found.",
		Data:    role,
	}.Respond(w, http.StatusOK)
}
