import { get, run, query } from '../database';
import { v4 as uuidv4 } from 'uuid';

export interface SystemConfig {
  id: string;
  configType: string;
  configValue: any;
  updatedAt: string;
}

export interface QuizConfig {
  singleRatio: number;
  multipleRatio: number;
  judgmentRatio: number;
  textRatio: number;
  totalScore: number;
}

export interface AdminUser {
  username: string;
  password: string;
}

export class SystemConfigModel {
  // 获取配置
  static async getConfig(configType: string): Promise<any> {
    const sql = `SELECT config_value as configValue FROM system_configs WHERE config_type = ?`;
    const result = await get(sql, [configType]);
    
    if (!result) {
      return null;
    }
    
    try {
      return JSON.parse(result.configValue);
    } catch {
      return result.configValue;
    }
  }

  // 更新配置
  static async updateConfig(configType: string, configValue: any): Promise<void> {
    const valueStr = typeof configValue === 'string' ? configValue : JSON.stringify(configValue);
    const sql = `
      INSERT OR REPLACE INTO system_configs (id, config_type, config_value, updated_at) 
      VALUES (
        COALESCE((SELECT id FROM system_configs WHERE config_type = ?), ?),
        ?, ?, datetime('now')
      )
    `;
    
    await run(sql, [configType, uuidv4(), configType, valueStr]);
  }

  // 获取抽题配置
  static async getQuizConfig(): Promise<QuizConfig> {
    const config = await this.getConfig('quiz_config');
    return config || {
      singleRatio: 40,
      multipleRatio: 30,
      judgmentRatio: 20,
      textRatio: 10,
      totalScore: 100
    };
  }

  // 更新抽题配置
  static async updateQuizConfig(config: QuizConfig): Promise<void> {
    // 验证比例总和
    const totalRatio = config.singleRatio + config.multipleRatio + config.judgmentRatio + config.textRatio;
    if (totalRatio !== 100) {
      throw new Error('题型比例总和必须为100%');
    }
    
    // 验证分值
    if (config.totalScore <= 0) {
      throw new Error('总分必须大于0');
    }
    
    await this.updateConfig('quiz_config', config);
  }

  // 获取管理员用户
  static async getAdminUser(): Promise<AdminUser | null> {
    // 临时解决方案：直接返回默认管理员用户，不依赖数据库
    return { username: 'admin', password: 'admin123' };
  }

  // 验证管理员登录
  static async validateAdminLogin(username: string, password: string): Promise<boolean> {
    // 临时解决方案：直接验证用户名和密码，不依赖数据库
    // 初始管理员账号：admin / admin123
    return username === 'admin' && password === 'admin123';
  }

  // 更新管理员密码
  static async updateAdminPassword(username: string, newPassword: string): Promise<void> {
    await this.updateConfig('admin_user', { username, password: newPassword });
  }

  // 获取所有配置（管理员用）
  static async getAllConfigs(): Promise<SystemConfig[]> {
    const sql = `SELECT id, config_type as configType, config_value as configValue, updated_at as updatedAt FROM system_configs ORDER BY config_type`;
    const configs = await query(sql);
    
    return configs.map((config: any) => ({
      id: config.id,
      configType: config.configType,
      configValue: this.parseConfigValue(config.configValue),
      updatedAt: config.updatedAt
    }));
  }

  // 解析配置值
  private static parseConfigValue(value: string): any {
    try {
      return JSON.parse(value);
    } catch {
      return value;
    }
  }
}