package system

import (
	"strconv"

	"kra/internal/biz/system"

	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/transport/http"
)

// AuthorityBtnService 角色按钮权限服务
type AuthorityBtnService struct {
	uc *system.AuthorityBtnUsecase
}

// NewAuthorityBtnService 创建角色按钮权限服务
func NewAuthorityBtnService(uc *system.AuthorityBtnUsecase) *AuthorityBtnService {
	return &AuthorityBtnService{uc: uc}
}

// GetAuthorityBtnRequest 获取角色按钮权限请求
type GetAuthorityBtnRequest struct {
	AuthorityId uint `json:"authorityId"`
	MenuID      uint `json:"menuID"`
}

// GetAuthorityBtnResponse 获取角色按钮权限响应
type GetAuthorityBtnResponse struct {
	Selected []uint `json:"selected"`
}

// SetAuthorityBtnRequest 设置角色按钮权限请求
type SetAuthorityBtnRequest struct {
	AuthorityId uint   `json:"authorityId"`
	MenuID      uint   `json:"menuID"`
	Selected    []uint `json:"selected"`
}

// RegisterRoutes 注册路由
func (s *AuthorityBtnService) RegisterRoutes(rg *RouterGroup) {
	// 角色按钮权限（不需要操作记录）
	rg.Private.POST("/authorityBtn/getAuthorityBtn", s.handleGetAuthorityBtn)
	rg.Private.POST("/authorityBtn/setAuthorityBtn", s.handleSetAuthorityBtn)
	rg.Private.POST("/authorityBtn/canRemoveAuthorityBtn", s.handleCanRemoveAuthorityBtn)
}

func (s *AuthorityBtnService) handleGetAuthorityBtn(ctx http.Context) error {
	var req GetAuthorityBtnRequest
	if err := ctx.Bind(&req); err != nil {
		return err
	}
	selected, err := s.uc.GetAuthorityBtn(ctx, req.AuthorityId, req.MenuID)
	if err != nil {
		return errors.InternalServer("QUERY_ERROR", err.Error())
	}
	return ctx.Result(200, map[string]any{
		"code": 0,
		"msg":  "查询成功",
		"data": GetAuthorityBtnResponse{Selected: selected},
	})
}

func (s *AuthorityBtnService) handleSetAuthorityBtn(ctx http.Context) error {
	var req SetAuthorityBtnRequest
	if err := ctx.Bind(&req); err != nil {
		return err
	}
	if err := s.uc.SetAuthorityBtn(ctx, req.AuthorityId, req.MenuID, req.Selected); err != nil {
		return errors.InternalServer("SET_ERROR", err.Error())
	}
	return ctx.Result(200, map[string]any{"code": 0, "msg": "分配成功"})
}

func (s *AuthorityBtnService) handleCanRemoveAuthorityBtn(ctx http.Context) error {
	idStr := ctx.Request().URL.Query().Get("id")
	if idStr == "" {
		return errors.BadRequest("INVALID_ID", "id参数不能为空")
	}
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return errors.BadRequest("INVALID_ID", "id参数格式错误")
	}
	if err := s.uc.CanRemoveAuthorityBtn(ctx, uint(id)); err != nil {
		return errors.BadRequest("BTN_IN_USE", err.Error())
	}
	return ctx.Result(200, map[string]any{"code": 0, "msg": "删除成功"})
}
