package middleware

import (
	"bsm/full/module/base/mgt/internal/impl"
	"bsm/full/module/base/mgt/internal/models"

	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/infra"
	coremw "git.apinb.com/bsm-sdk/core/middleware"
	"github.com/gin-gonic/gin"
)

const (
	superAdminRoleName = "超级管理员"
	rootAccount        = "root"
)

// IsSuperAdmin 判断用户是否为 root 账号或拥有超级管理员角色
func IsSuperAdmin(userID uint) bool {
	var user models.MgtUser
	if err := impl.DBService.Select("id", "account").Where("id = ?", userID).First(&user).Error; err != nil {
		return false
	}
	if user.Account == rootAccount {
		return true
	}
	if err := impl.DBService.Preload("Roles").Where("id = ?", userID).First(&user).Error; err != nil {
		return false
	}
	for _, role := range user.Roles {
		if role.Name == superAdminRoleName {
			return true
		}
	}
	return false
}

// RequireAdmin 要求超级管理员权限
func RequireAdmin() gin.HandlerFunc {
	return func(c *gin.Context) {
		auth, err := coremw.ParseAuth(c)
		if err != nil {
			infra.Response.Error(c, err)
			c.Abort()
			return
		}
		if !IsSuperAdmin(auth.ID) {
			infra.Response.Error(c, errcode.ErrPermissionDenied)
			c.Abort()
			return
		}
		c.Next()
	}
}

// EnsureSelfOrAdmin 仅允许访问本人数据或超级管理员访问
func EnsureSelfOrAdmin(c *gin.Context, targetUserID uint) bool {
	auth, err := coremw.ParseAuth(c)
	if err != nil {
		infra.Response.Error(c, err)
		return false
	}
	if targetUserID == 0 || targetUserID == auth.ID {
		return true
	}
	if IsSuperAdmin(auth.ID) {
		return true
	}
	infra.Response.Error(c, errcode.ErrPermissionDenied)
	return false
}
