package roles

import (
	"context"
	"net/http"

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

func HandleRemovePermission(w http.ResponseWriter, r *http.Request) {
	ctx := context.Background()
	role_id := r.PathValue("role_uuid")
	resource := r.PathValue("resource")
	action := r.PathValue("action")
	var permission models.Permission
	count, err := core.DB.NewSelect().Model(&permission).
		Where("resource = ? AND action = ?", resource, action).
		Limit(1).ScanAndCount(ctx)
	if count == 0 {
		core.JSONError{
			Status:  core.Error,
			Message: "Permission doesn't exist.",
		}.Respond(w, http.StatusNotFound)
		return
	}

	_, err = core.DB.NewDelete().Model((*models.PermissionToRole)(nil)).
		Where("resource = ? AND action = ? AND role_id = ?", permission.Resource, permission.Action, role_id).
		Exec(ctx)

	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	core.JSONSuccess{
		Status:  core.Success,
		Message: "Permission removed.",
	}.Respond(w, http.StatusOK)
}
