package middleware

import (
	"net/http"
	"strings"

	"git.echol.cn/loser/ai_proxy/server/service"
	"github.com/gin-gonic/gin"
)

var aiApiKeyService = service.ServiceGroupApp.AppServiceGroup.AiApiKeyService

// AiAuth AI接口鉴权中间件
func AiAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头获取 Authorization
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": gin.H{
					"message": "未提供API密钥",
					"type":    "invalid_request_error",
					"code":    "missing_api_key",
				},
			})
			c.Abort()
			return
		}

		// 提取 API Key (支持 "Bearer sk-xxx" 和 "sk-xxx" 两种格式)
		apiKey := strings.TrimPrefix(authHeader, "Bearer ")
		apiKey = strings.TrimSpace(apiKey)

		// 验证 API Key
		keyInfo, err := aiApiKeyService.ValidateApiKey(apiKey)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": gin.H{
					"message": err.Error(),
					"type":    "invalid_request_error",
					"code":    "invalid_api_key",
				},
			})
			c.Abort()
			return
		}

		// 将密钥信息存入上下文
		c.Set("ai_api_key", keyInfo)
		c.Next()
	}
}
