package middleware

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

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

func AdminJWTAuth(secret string) gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			response.Unauthorized(c, "未提供认证令牌")
			c.Abort()
			return
		}
		var tokenStr string
		if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
			tokenStr = authHeader[7:]
		} else {
			tokenStr = authHeader
		}
		claims, err := utils.ParseAdminToken(tokenStr, secret)
		if err != nil {
			response.Unauthorized(c, "管理员令牌无效或已过期")
			c.Abort()
			return
		}
		c.Set("admin_id", claims.AdminID)
		c.Set("admin_account", claims.Account)
		c.Next()
	}
}
