package middleware

import (
	"log"

	"metazone.cc/metalab/internal/common"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

// authenticateToken 统一的认证核心流程：读 Cookie → 解析 JWT → 检查 token_version
func (am *AuthMiddleware) authenticateToken(c *gin.Context) (jwt.MapClaims, error) {
	tokenStr, err := c.Cookie(common.CookieName)
	if err != nil {
		return nil, err
	}
	claims, err := parseToken(tokenStr, am.cfg.JWT.Secret)
	if err != nil {
		return nil, err
	}
	uid := uint(claims["uid"].(float64))
	tokenVer := int(claims["ver"].(float64))
	currentVer, err := am.userRepo.FindTokenVersion(uid)
	if err != nil {
		return nil, err
	}
	if tokenVer != currentVer {
		log.Printf("[authenticateToken] REVOKED: uid=%d tokenVer=%d dbVer=%d", uid, tokenVer, currentVer)
		return nil, common.ErrTokenRevoked
	}
	return claims, nil
}

// injectUserContext 将 JWT claims 中的用户信息注入 gin context
func injectUserContext(c *gin.Context, claims jwt.MapClaims) {
	if claims == nil {
		return
	}
	uid, ok := claims["uid"].(float64)
	if !ok {
		return
	}
	c.Set("uid", uint(uid))
	c.Set("email", claims["email"])
	c.Set("username", claims["username"])
	c.Set("role", claims["role"])
}
