package system

import (
	"kra/internal/biz/system"
	jwtPkg "kra/pkg/jwt"
	"kra/pkg/response"

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

type AuthorityApi struct{}

// CreateAuthorityRequest 创建角色请求
type CreateAuthorityRequest struct {
	AuthorityId   uint   `json:"authorityId" binding:"required"`
	AuthorityName string `json:"authorityName" binding:"required"`
	ParentId      *uint  `json:"parentId"`
	DefaultRouter string `json:"defaultRouter"`
}

// UpdateAuthorityRequest 更新角色请求
type UpdateAuthorityRequest struct {
	AuthorityId   uint   `json:"authorityId" binding:"required"`
	AuthorityName string `json:"authorityName" binding:"required"`
	ParentId      *uint  `json:"parentId"`
	DefaultRouter string `json:"defaultRouter"`
}

// DeleteAuthorityRequest 删除角色请求
type DeleteAuthorityRequest struct {
	AuthorityId uint `json:"authorityId" binding:"required"`
}

// CopyAuthorityRequest 复制角色请求
type CopyAuthorityRequest struct {
	OldAuthorityId uint                   `json:"oldAuthorityId" binding:"required"`
	Authority      CreateAuthorityRequest `json:"authority" binding:"required"`
}

// SetDataAuthorityRequest 设置数据权限请求
type SetDataAuthorityRequest struct {
	AuthorityId     uint   `json:"authorityId" binding:"required"`
	DataAuthorityId []uint `json:"dataAuthorityId"`
}

// GetAuthorityListRequest 获取角色列表请求
type GetAuthorityListRequest struct {
	Page     int `json:"page"`
	PageSize int `json:"pageSize"`
}

// CreateAuthority
// @Tags      Authority
// @Summary   创建角色
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      CreateAuthorityRequest                                 true  "权限id, 权限名, 父角色id"
// @Success   200   {object}  response.Response{data=system.Authority,msg=string}  "创建角色,返回包括系统角色详情"
// @Router    /authority/createAuthority [post]
func (a *AuthorityApi) CreateAuthority(c *gin.Context) {
	var req CreateAuthorityRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	authority := &system.Authority{
		AuthorityId:   req.AuthorityId,
		AuthorityName: req.AuthorityName,
		ParentId:      req.ParentId,
		DefaultRouter: req.DefaultRouter,
	}

	created, err := authorityUsecase.CreateAuthority(c, authority)
	if err != nil {
		response.FailWithMessage("创建失败: "+err.Error(), c)
		return
	}

	// 刷新Casbin权限
	if err := casbinUsecase.FreshCasbin(); err != nil {
		response.FailWithMessage("创建成功，权限刷新失败: "+err.Error(), c)
		return
	}

	response.OkWithDetailed(gin.H{"authority": created}, "创建成功", c)
}

// DeleteAuthority
// @Tags      Authority
// @Summary   删除角色
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      DeleteAuthorityRequest         true  "删除角色"
// @Success   200   {object}  response.Response{msg=string}  "删除角色"
// @Router    /authority/deleteAuthority [post]
func (a *AuthorityApi) DeleteAuthority(c *gin.Context) {
	var req DeleteAuthorityRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if err := authorityUsecase.DeleteAuthority(c, req.AuthorityId); err != nil {
		response.FailWithMessage("删除失败: "+err.Error(), c)
		return
	}

	// 刷新Casbin权限
	_ = casbinUsecase.FreshCasbin()

	response.OkWithMessage("删除成功", c)
}

// UpdateAuthority
// @Tags      Authority
// @Summary   更新角色信息
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      UpdateAuthorityRequest                                 true  "权限id, 权限名, 父角色id"
// @Success   200   {object}  response.Response{data=system.Authority,msg=string}  "更新角色信息,返回包括系统角色详情"
// @Router    /authority/updateAuthority [post]
func (a *AuthorityApi) UpdateAuthority(c *gin.Context) {
	var req UpdateAuthorityRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	authority := &system.Authority{
		AuthorityId:   req.AuthorityId,
		AuthorityName: req.AuthorityName,
		ParentId:      req.ParentId,
		DefaultRouter: req.DefaultRouter,
	}

	updated, err := authorityUsecase.UpdateAuthority(c, authority)
	if err != nil {
		response.FailWithMessage("更新失败: "+err.Error(), c)
		return
	}

	response.OkWithDetailed(gin.H{"authority": updated}, "更新成功", c)
}

// GetAuthorityList
// @Tags      Authority
// @Summary   分页获取角色列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      GetAuthorityListRequest                              true  "页码, 每页大小"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "分页获取角色列表,返回包括列表,总数,页码,每页数量"
// @Router    /authority/getAuthorityList [post]
func (a *AuthorityApi) GetAuthorityList(c *gin.Context) {
	// 从JWT获取当前用户的角色ID
	claims, exists := c.Get("claims")
	if !exists {
		response.FailWithMessage("获取用户信息失败", c)
		return
	}
	customClaims := claims.(*jwtPkg.CustomClaims)

	list, err := authorityUsecase.GetAuthorityInfoList(c, customClaims.AuthorityID)
	if err != nil {
		response.FailWithMessage("获取失败", c)
		return
	}

	response.OkWithDetailed(gin.H{"list": list}, "获取成功", c)
}

// CopyAuthority
// @Tags      Authority
// @Summary   拷贝角色
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      CopyAuthorityRequest                                   true  "旧角色id, 新权限id, 新权限名, 新父角色id"
// @Success   200   {object}  response.Response{data=system.Authority,msg=string}  "拷贝角色,返回包括系统角色详情"
// @Router    /authority/copyAuthority [post]
func (a *AuthorityApi) CopyAuthority(c *gin.Context) {
	var req CopyAuthorityRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 从JWT获取当前用户的角色ID
	claims, exists := c.Get("claims")
	if !exists {
		response.FailWithMessage("获取用户信息失败", c)
		return
	}
	customClaims := claims.(*jwtPkg.CustomClaims)

	authority := &system.Authority{
		AuthorityId:   req.Authority.AuthorityId,
		AuthorityName: req.Authority.AuthorityName,
		ParentId:      req.Authority.ParentId,
		DefaultRouter: req.Authority.DefaultRouter,
	}

	created, err := authorityUsecase.CopyAuthority(c, customClaims.AuthorityID, req.OldAuthorityId, authority)
	if err != nil {
		response.FailWithMessage("复制失败: "+err.Error(), c)
		return
	}

	response.OkWithDetailed(gin.H{"authority": created}, "复制成功", c)
}

// SetDataAuthority
// @Tags      Authority
// @Summary   设置角色资源权限
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      SetDataAuthorityRequest        true  "设置角色资源权限"
// @Success   200   {object}  response.Response{msg=string}  "设置角色资源权限"
// @Router    /authority/setDataAuthority [post]
func (a *AuthorityApi) SetDataAuthority(c *gin.Context) {
	var req SetDataAuthorityRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 从JWT获取当前用户的角色ID
	claims, exists := c.Get("claims")
	if !exists {
		response.FailWithMessage("获取用户信息失败", c)
		return
	}
	customClaims := claims.(*jwtPkg.CustomClaims)

	if err := authorityUsecase.SetDataAuthority(c, customClaims.AuthorityID, req.AuthorityId, req.DataAuthorityId); err != nil {
		response.FailWithMessage("设置失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("设置成功", c)
}
