package middleware

import (
	"metazone.cc/metalab/internal/common"
	"metazone.cc/metalab/internal/config"

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

// AuthMiddleware 认证中间件（结构体模式，持有 DB 依赖用于实时令牌吊销校验）
type AuthMiddleware struct {
	cfg      *config.Config
	userRepo tokenVersionStore
}

// NewAuthMiddleware 构造函数
func NewAuthMiddleware(cfg *config.Config, userRepo tokenVersionStore) *AuthMiddleware {
	return &AuthMiddleware{cfg: cfg, userRepo: userRepo}
}

// Required 登录认证中间件：校验 JWT → 检查 token_version → 注入用户信息
func (am *AuthMiddleware) Required() gin.HandlerFunc {
	return func(c *gin.Context) {
		claims, err := am.authenticateToken(c)
		if err != nil {
			common.ClearAuthCookies(c, am.cfg)
			c.AbortWithStatusJSON(401, gin.H{
				"success": false, "message": "登录已过期，请重新登录",
			})
			return
		}
		injectUserContext(c, claims)
		c.Next()
	}
}

// Optional 可选认证：已登录且版本通过则注入，未登录或版本不匹配也放行
func (am *AuthMiddleware) Optional() gin.HandlerFunc {
	return func(c *gin.Context) {
		claims, err := am.authenticateToken(c)
		if err != nil {
			c.Next()
			return
		}
		injectUserContext(c, claims)
		c.Next()
	}
}
