package middleware

import (
	"strings"

	"com.sclktx/m/v2/internal/common/response"
	"com.sclktx/m/v2/internal/common/utils"

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

// JWTAuth JWT 认证中间件
// 1. 从 Authorization header 提取 Bearer Token
// 2. 解析验证 JWT（签名 + 过期时间）
// 3. 将 user_id、role_code、role_codes 注入 gin.Context
// 4. 后续 Handler 通过 utils.GetUserID(c) / utils.GetRoleCodes(c) 获取
func JWTAuth(secret string) gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			response.Unauthorized(c, "未提供认证令牌")
			c.Abort()
			return
		}

		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			response.Unauthorized(c, "认证格式错误")
			c.Abort()
			return
		}

		claims, err := utils.ParseToken(parts[1], secret)
		if err != nil {
			response.Unauthorized(c, "认证令牌无效或已过期")
			c.Abort()
			return
		}

		// 注入用户信息到 Context
		c.Set("user_id", claims.UserID)
		c.Set("role_code", claims.RoleCode)
		c.Next()
	}
}
