package middleware

import (
	"net/http"
	"opencatd-open/internal/dto"
	"opencatd-open/internal/model"

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

func AuthTeam(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {

		auth_token := c.GetHeader("Authorization")
		if len(auth_token) < 7 || auth_token[:7] != "Bearer " {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			c.Abort()
			return
		}
		auth_token = auth_token[7:]
		token := model.Token{}
		if err := db.Preload("Users").First(&token, "token = ?", auth_token).Error; err != nil {
			dto.WrapErrorAsOpenAI(c, http.StatusUnauthorized, "invalid_api_key")
			c.Abort()
			return
		}

		if token.User == nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			c.Abort()
			return
		}

		if !*token.User.Active || !*token.Active {
			dto.WrapErrorAsOpenAI(c, http.StatusForbidden, "User or API key is not active")
			c.Abort()
			return
		}

		if token.Name != "default" {
			dto.WrapErrorAsOpenAI(c, http.StatusForbidden, "Only default api key accessible")
			c.Abort()
			return
		}

		c.Set("user", token.User)
		c.Set("authed", true)
		// 可以在这里对 token 进行验证并检查权限
		c.Next()

	}
}

func AuthLLM(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {

		auth_token := c.GetHeader("Authorization")
		if len(auth_token) < 7 || auth_token[:7] != "Bearer " {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			c.Abort()
			return
		}
		auth_token = auth_token[7:]
		token := model.Token{}
		if err := db.Preload("User").Where("key = ?", auth_token).First(&token).Error; err != nil {
			dto.WrapErrorAsOpenAI(c, http.StatusUnauthorized, "invalid_api_key")
			c.Abort()
			return
		}

		if token.User == nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			c.Abort()
			return
		}

		if !*token.User.Active || !*token.Active {
			dto.WrapErrorAsOpenAI(c, http.StatusForbidden, "User or API key is not active")
			c.Abort()
			return
		}

		if !*token.User.UnlimitedQuota && *token.User.Quota <= 0 {
			dto.WrapErrorAsOpenAI(c, http.StatusForbidden, "quota_exceeded")
			c.Abort()
			return
		}

		if !*token.UnlimitedQuota && *token.Quota <= 0 {
			dto.WrapErrorAsOpenAI(c, http.StatusForbidden, "quota_exceeded")
			c.Abort()
			return
		}

		c.Set("user", token.User)
		c.Set("authed", true)
		// 可以在这里对 token 进行验证并检查权限

		c.Next()

	}
}
