/**
 * Config Service
 * 处理用户配置的存储和检索
 */

import { prisma } from '../lib/prisma';

export interface UserConfigData {
  ocr?: {
    provider?: string;
    confidenceThreshold?: number;
    baiduApiKey?: string;
    baiduSecretKey?: string;
    tencentSecretId?: string;
    tencentSecretKey?: string;
    rapidocrUrl?: string;
  };
  ai?: {
    defaultProvider?: string;
    glmApiKey?: string;
    glmApiUrl?: string;
    glmModel?: string;
    minimaxApiKey?: string;
    minimaxApiUrl?: string;
    minimaxModel?: string;
    deepseekApiKey?: string;
    deepseekApiUrl?: string;
    deepseekModel?: string;
    kimiApiKey?: string;
    kimiApiUrl?: string;
    kimiModel?: string;
    openaiApiKey?: string;
    openaiApiUrl?: string;
    openaiModel?: string;
    anthropicApiKey?: string;
    anthropicApiUrl?: string;
    anthropicModel?: string;
  };
}

export class ConfigService {
  /**
   * 保存用户配置
   */
  static async saveConfig(userId: string, config: UserConfigData) {
    const operations: Promise<any>[] = [];

    // 保存 OCR 配置
    if (config.ocr) {
      const ocrKeys = [
        { key: 'ocr.provider', value: config.ocr.provider },
        { key: 'ocr.confidenceThreshold', value: config.ocr.confidenceThreshold?.toString() },
        { key: 'ocr.baiduApiKey', value: config.ocr.baiduApiKey },
        { key: 'ocr.baiduSecretKey', value: config.ocr.baiduSecretKey },
        { key: 'ocr.tencentSecretId', value: config.ocr.tencentSecretId },
        { key: 'ocr.tencentSecretKey', value: config.ocr.tencentSecretKey },
        { key: 'ocr.rapidocrUrl', value: config.ocr.rapidocrUrl },
      ];

      for (const item of ocrKeys) {
        if (item.value !== undefined) {
          operations.push(
            prisma.config.upsert({
              where: {
                user_id_key: {
                  user_id: userId,
                  key: item.key,
                },
              },
              create: {
                user_id: userId,
                key: item.key,
                value: item.value,
              },
              update: {
                value: item.value,
              },
            })
          );
        }
      }
    }

    // 保存 AI 配置
    if (config.ai) {
      const aiKeys = [
        { key: 'ai.defaultProvider', value: config.ai.defaultProvider },
        { key: 'ai.glmApiKey', value: config.ai.glmApiKey },
        { key: 'ai.glmApiUrl', value: config.ai.glmApiUrl },
        { key: 'ai.glmModel', value: config.ai.glmModel },
        { key: 'ai.minimaxApiKey', value: config.ai.minimaxApiKey },
        { key: 'ai.minimaxApiUrl', value: config.ai.minimaxApiUrl },
        { key: 'ai.minimaxModel', value: config.ai.minimaxModel },
        { key: 'ai.deepseekApiKey', value: config.ai.deepseekApiKey },
        { key: 'ai.deepseekApiUrl', value: config.ai.deepseekApiUrl },
        { key: 'ai.deepseekModel', value: config.ai.deepseekModel },
        { key: 'ai.kimiApiKey', value: config.ai.kimiApiKey },
        { key: 'ai.kimiApiUrl', value: config.ai.kimiApiUrl },
        { key: 'ai.kimiModel', value: config.ai.kimiModel },
        { key: 'ai.openaiApiKey', value: config.ai.openaiApiKey },
        { key: 'ai.openaiApiUrl', value: config.ai.openaiApiUrl },
        { key: 'ai.openaiModel', value: config.ai.openaiModel },
        { key: 'ai.anthropicApiKey', value: config.ai.anthropicApiKey },
        { key: 'ai.anthropicApiUrl', value: config.ai.anthropicApiUrl },
        { key: 'ai.anthropicModel', value: config.ai.anthropicModel },
      ];

      for (const item of aiKeys) {
        if (item.value !== undefined) {
          operations.push(
            prisma.config.upsert({
              where: {
                user_id_key: {
                  user_id: userId,
                  key: item.key,
                },
              },
              create: {
                user_id: userId,
                key: item.key,
                value: item.value,
              },
              update: {
                value: item.value,
              },
            })
          );
        }
      }
    }

    await Promise.all(operations);

    // 返回所有配置
    return this.getConfig(userId);
  }

  /**
   * 获取用户配置
   */
  static async getConfig(userId: string): Promise<UserConfigData> {
    const configs = await prisma.config.findMany({
      where: { user_id: userId },
    });

    const result: UserConfigData = {
      ocr: {},
      ai: {},
    };

    for (const config of configs) {
      const keys = config.key.split('.');
      const category = keys[0] as 'ocr' | 'ai';
      const key = keys.slice(1).join('') as keyof any;

      if (result[category]) {
        // 转换数值类型
        if (key === 'confidenceThreshold') {
          (result[category] as any)[key] = parseFloat(config.value);
        } else {
          (result[category] as any)[key] = config.value;
        }
      }
    }

    return result;
  }

  /**
   * 删除用户配置
   */
  static async deleteConfig(userId: string, key: string) {
    await prisma.config.deleteMany({
      where: {
        user_id: userId,
        key,
      },
    });
  }

  /**
   * 清空用户配置
   */
  static async clearConfig(userId: string) {
    await prisma.config.deleteMany({
      where: { user_id: userId },
    });
  }
}
