package middleware

import (
	"log"
	"net/http"

	"metazone.cc/metalab/internal/model"

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

// RequireMinRole 角色权限检查（用于 API 路由）
// 不足时返回 JSON 403
func RequireMinRole(minRole string) gin.HandlerFunc {
	return func(c *gin.Context) {
		role, exists := c.Get("role")
		if !exists || !model.HasMinRole(role.(string), minRole) {
			c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
				"success": false, "message": "权限不足",
			})
			return
		}
		c.Next()
	}
}

// RequirePageRole 角色权限检查（用于 SSR 页面路由）
// 不足时 302 跳转首页
func RequirePageRole(minRole string) gin.HandlerFunc {
	return func(c *gin.Context) {
		role, exists := c.Get("role")
		if !exists || !model.HasMinRole(role.(string), minRole) {
			log.Printf("[RequirePageRole] DENY: role=%v need=%s path=%s → 302", role, minRole, c.Request.URL.Path)
			c.Redirect(http.StatusFound, "/")
			c.Abort()
			return
		}
		c.Next()
	}
}
