package app

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"time"

	"git.echol.cn/loser/ai_proxy/server/global"
	"git.echol.cn/loser/ai_proxy/server/model/app"
	"git.echol.cn/loser/ai_proxy/server/model/common/request"
)

type AiApiKeyService struct{}

// GenerateApiKey 生成API密钥
func (s *AiApiKeyService) GenerateApiKey() string {
	bytes := make([]byte, 32)
	rand.Read(bytes)
	return "sk-" + hex.EncodeToString(bytes)
}

// CreateAiApiKey 创建API密钥
func (s *AiApiKeyService) CreateAiApiKey(apiKey *app.AiApiKey) error {
	if apiKey.Key == "" {
		apiKey.Key = s.GenerateApiKey()
	}
	return global.GVA_DB.Create(apiKey).Error
}

// DeleteAiApiKey 删除API密钥
func (s *AiApiKeyService) DeleteAiApiKey(id uint, userID uint) error {
	return global.GVA_DB.Where("id = ? AND user_id = ?", id, userID).Delete(&app.AiApiKey{}).Error
}

// UpdateAiApiKey 更新API密钥
func (s *AiApiKeyService) UpdateAiApiKey(apiKey *app.AiApiKey, userID uint) error {
	return global.GVA_DB.Where("user_id = ?", userID).Updates(apiKey).Error
}

// GetAiApiKey 查询API密钥
func (s *AiApiKeyService) GetAiApiKey(id uint, userID uint) (apiKey app.AiApiKey, err error) {
	err = global.GVA_DB.Where("id = ? AND user_id = ?", id, userID).First(&apiKey).Error
	return
}

// GetAiApiKeyList 获取API密钥列表
func (s *AiApiKeyService) GetAiApiKeyList(info request.PageInfo, userID uint) (list []app.AiApiKey, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&app.AiApiKey{}).Where("user_id = ?", userID)
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Order("id desc").Find(&list).Error
	return
}

// ValidateApiKey 验证API密钥
func (s *AiApiKeyService) ValidateApiKey(key string) (*app.AiApiKey, error) {
	var apiKey app.AiApiKey
	if err := global.GVA_DB.Where("key = ? AND enabled = ?", key, true).First(&apiKey).Error; err != nil {
		return nil, fmt.Errorf("无效的API密钥")
	}

	// 检查是否过期
	if apiKey.ExpiresAt != nil && time.Now().Unix() > *apiKey.ExpiresAt {
		return nil, fmt.Errorf("API密钥已过期")
	}

	return &apiKey, nil
}

// CheckModelPermission 检查模型权限
func (s *AiApiKeyService) CheckModelPermission(apiKey *app.AiApiKey, model string) bool {
	// 如果没有限制，允许所有模型
	if len(apiKey.AllowedModels) == 0 {
		return true
	}

	// 检查模型是否在允许列表中
	for _, allowedModel := range apiKey.AllowedModels {
		if allowedModel == model || allowedModel == "*" {
			return true
		}
	}

	return false
}

// CheckPresetPermission 检查预设权限
func (s *AiApiKeyService) CheckPresetPermission(apiKey *app.AiApiKey, presetName string) bool {
	// 如果没有限制，允许所有预设
	if len(apiKey.AllowedPresets) == 0 {
		return true
	}

	// 检查预设是否在允许列表中
	for _, allowedPreset := range apiKey.AllowedPresets {
		if allowedPreset == presetName || allowedPreset == "*" {
			return true
		}
	}

	return false
}
