package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

	"git.yeij.top/AskaEth/Cyrene/gateway/internal/config"
)

// Auth 用户键值在context中的key
const UserIDKey = "user_id"
const IsAdminKey = "is_admin"

// JWTAuth JWT认证中间件
func JWTAuth(cfg *config.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供认证令牌"})
			c.Abort()
			return
		}

		// Bearer token
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "认证格式错误"})
			c.Abort()
			return
		}

		tokenString := parts[1]
		userID, err := cfg.ValidateToken(tokenString)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "认证令牌无效或已过期"})
			c.Abort()
			return
		}

		// 将userID注入上下文
		c.Set(UserIDKey, userID)
		// 设置管理员标记 (admin 用户 ID 为固定值 "admin")
		c.Set(IsAdminKey, userID == "admin")
		c.Next()
	}
}

// GetUserID 从上下文获取用户ID
func GetUserID(c *gin.Context) string {
	userID, _ := c.Get(UserIDKey)
	if userID == nil {
		return ""
	}
	return userID.(string)
}

// GetIsAdmin 从上下文获取是否为管理员
func GetIsAdmin(c *gin.Context) bool {
	isAdmin, _ := c.Get(IsAdminKey)
	if isAdmin == nil {
		return false
	}
	return isAdmin.(bool)
}
