package permissions

import (
	"context"
	"net/http"

	"fr.latosa-escrima/core"
)

func HandlePermissionsResource(w http.ResponseWriter, r *http.Request) {
	resource := r.PathValue("resource")
	var permissions core.Permissions
	count, err := core.DB.NewSelect().
		Model(&permissions).
		Where("resource = ?", resource).
		ScanAndCount(context.Background())
	if count == 0 {
		core.JSONSuccess{
			Status:  core.Success,
			Message: "No permission with this given resource 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: "Permissions found.",
		Data:    permissions,
	}.Respond(w, http.StatusOK)
}
