package handler

import (
	"kra/internal/service"
	"kra/internal/service/dto"

	"github.com/gin-gonic/gin"
)

type Permission struct{ service *service.PermissionService }

func NewPermission(service *service.PermissionService) *Permission {
	return &Permission{service: service}
}

func (h *Permission) Buttons(c *gin.Context) {
	var req dto.GetAuthorityButtonsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	selected, err := h.service.SelectedButtons(c.Request.Context(), req.AuthorityID, req.MenuID)
	if err != nil {
		Fail(c, "查询失败")
		return
	}
	Write(c, CodeSuccess, gin.H{"selected": selected}, "查询成功")
}

func (h *Permission) SetButtons(c *gin.Context) {
	var req dto.SetAuthorityButtonsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		Fail(c, err.Error())
		return
	}
	if err := h.service.SetSelectedButtons(c.Request.Context(), req.AuthorityID, req.MenuID, req.Selected); err != nil {
		Fail(c, "分配失败")
		return
	}
	Write(c, CodeSuccess, gin.H{}, "分配成功")
}

func (h *Permission) CanRemoveButton(c *gin.Context) {
	allowed, err := h.service.CanRemoveButton(c.Request.Context(), c.Query("id"))
	if err != nil {
		Fail(c, err.Error())
		return
	}
	if !allowed {
		Fail(c, "此按钮正在被使用无法删除")
		return
	}
	Write(c, CodeSuccess, gin.H{}, "删除成功")
}
