package middleware

import (
	"strings"

	"hfb_sys/backend/internal/modules/auth"
	"hfb_sys/backend/pkg/response"

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

const (
	ContextUserID   = "user_id"
	ContextPhone    = "phone"
	ContextAdminID  = "admin_id"
	ContextUsername = "username"
)

func extractToken(c *gin.Context) string {
	header := c.GetHeader("Authorization")
	tokenText := strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
	if tokenText != "" && tokenText != header {
		return tokenText
	}
	return c.Query("token")
}

func Auth(jwtManager *auth.JWTManager) gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenText := extractToken(c)
		if tokenText == "" {
			response.Unauthorized(c, "缺少访问令牌")
			c.Abort()
			return
		}

		claims, err := jwtManager.ParseSubject(tokenText, "access", "user")
		if err != nil {
			response.Unauthorized(c, "访问令牌无效或已过期")
			c.Abort()
			return
		}

		c.Set(ContextUserID, claims.UserID)
		c.Set(ContextPhone, claims.Phone)
		c.Next()
	}
}

func AdminAuth(jwtManager *auth.JWTManager) gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenText := extractToken(c)
		if tokenText == "" {
			response.Unauthorized(c, "缺少后台访问令牌")
			c.Abort()
			return
		}

		claims, err := jwtManager.ParseSubject(tokenText, "access", "admin")
		if err != nil {
			response.Unauthorized(c, "后台访问令牌无效或已过期")
			c.Abort()
			return
		}

		c.Set(ContextAdminID, claims.UserID)
		c.Set(ContextUsername, claims.Phone)
		c.Next()
	}
}
