package middleware

import (
	"strconv"
	"strings"

	"kra/pkg/casbin"
	"kra/pkg/response"
	"kra/pkg/utils"

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

// CasbinConfig Casbin中间件配置
type CasbinConfig struct {
	RouterPrefix string // 路由前缀，需要从路径中去除
}

// 全局配置
var casbinConfig *CasbinConfig

// SetCasbinConfig 设置Casbin配置
func SetCasbinConfig(cfg *CasbinConfig) {
	casbinConfig = cfg
}

// CasbinHandler Casbin权限拦截器（与 kra 保持一致）
func CasbinHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		waitUse, _ := utils.GetClaims(c)
		if waitUse == nil {
			response.FailWithDetailed(gin.H{}, "权限不足", c)
			c.Abort()
			return
		}

		// 获取请求的PATH
		path := c.Request.URL.Path
		// 去除路由前缀
		if casbinConfig != nil && casbinConfig.RouterPrefix != "" {
			path = strings.TrimPrefix(path, casbinConfig.RouterPrefix)
		}

		// 获取请求方法
		act := c.Request.Method
		// 获取用户的角色
		sub := strconv.Itoa(int(waitUse.AuthorityID))

		// 判断策略中是否存在
		e := casbin.GetEnforcer()
		if e == nil {
			response.FailWithDetailed(gin.H{}, "Casbin未初始化", c)
			c.Abort()
			return
		}

		success, _ := e.Enforce(sub, path, act)
		if !success {
			response.FailWithDetailed(gin.H{}, "权限不足", c)
			c.Abort()
			return
		}
		c.Next()
	}
}
