package roles

import (
	"context"
	"net/http"

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

func HandleAddPermission(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
	}

	var role models.Role
	count, err = core.DB.NewSelect().Model(&role).
		Where("id = ?", role_id).
		Limit(1).ScanAndCount(ctx)

	if count == 0 {
		core.JSONError{
			Status:  core.Error,
			Message: "Role doesn't exist.",
		}.Respond(w, http.StatusNotFound)
		return
	}

	permissionRole := models.PermissionToRole{
		PermissionResource: permission.Resource,
		PermissionAction:   permission.Action,
		RoleID:             role.ID,
	}
	_, err = core.DB.NewInsert().Model(&permissionRole).Ignore().
		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 added.",
	}.Respond(w, http.StatusCreated)
}
