import { Request, Response } from 'express';
import { designService, COLOR_MAPPING } from '../services/design.service';
import { query, initializeDatabase } from '../database';

export const debugController = {
  initDb: async (req: Request, res: Response) => {
    try {
      await initializeDatabase();
      res.json({ success: true, message: '数据库已初始化' });
    } catch (error) {
      console.error('数据库初始化错误:', error);
      res.status(500).json({ success: false, error: '初始化失败' });
    }
  },

  checkDb: async (req: Request, res: Response) => {
    try {
      const tableExists = await query(`
        SELECT EXISTS (
          SELECT 1 FROM information_schema.tables 
          WHERE table_name = 'design_usage'
        )
      `);
      res.json({ exists: tableExists.rows[0].exists });
    } catch (error) {
      console.error('数据库检查错误:', error);
      res.status(500).json({ success: false, error: '检查失败' });
    }
  },

  generateTestData: async (req: Request, res: Response) => {
    try {
      const count = parseInt(req.query.count as string) || 100;
      const colorCodes = COLOR_MAPPING.map(c => c.code);
      
      for (let i = 0; i < count; i++) {
        const design = {
          part1: colorCodes[Math.floor(Math.random() * colorCodes.length)],
          part2: colorCodes[Math.floor(Math.random() * colorCodes.length)],
          part3: colorCodes[Math.floor(Math.random() * colorCodes.length)],
          part4: colorCodes[Math.floor(Math.random() * colorCodes.length)],
        };
        await designService.saveDesign(design);
      }
      
      res.json({ success: true, message: `已生成 ${count} 条记录` });
    } catch (error) {
      console.error('生成测试数据错误:', error);
      res.status(500).json({ success: false, error: '生成失败' });
    }
  },

  resetStatistics: async (req: Request, res: Response) => {
    try {
      await query('TRUNCATE TABLE design_usage');
      res.json({ success: true, message: '统计数据已重置' });
    } catch (error) {
      console.error('重置统计数据错误:', error);
      res.status(500).json({ success: false, error: '重置失败' });
    }
  }
};