import express from 'express';
import { fetchDataSources, saveDataSource, fetchAIModels, saveAIModel, fetchSystemSettings, saveSystemSettings } from '../services/configService';
import { logger } from '../utils/logger';

const router = express.Router();

// 获取数据源列表
router.get('/datasources', async (req, res) => {
  try {
    const data = await fetchDataSources();
    res.status(200).json({ success: true, data });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取数据源列表失败' });
  }
});

// 保存数据源配置
router.post('/datasources', async (req, res) => {
  try {
    const data = await saveDataSource(req.body);
    res.status(200).json({ success: true, message: '配置保存成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: '保存数据源配置失败' });
  }
});

// 获取AI模型列表
router.get('/ai-models', async (req, res) => {
  try {
    const data = await fetchAIModels();
    res.status(200).json({ success: true, data });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取AI模型列表失败' });
  }
});

// 保存AI模型配置
router.post('/ai-models', async (req, res) => {
  try {
    const data = await saveAIModel(req.body);
    res.status(200).json({ success: true, message: '配置保存成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: '保存AI模型配置失败' });
  }
});

// 获取系统设置
router.get('/system', async (req, res) => {
  try {
    const data = await fetchSystemSettings();
    res.status(200).json({ success: true, data });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取系统设置失败' });
  }
});

// 保存系统设置
router.post('/system', async (req, res) => {
  try {
    const data = await saveSystemSettings(req.body);
    res.status(200).json({ success: true, message: '设置保存成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: '保存系统设置失败' });
  }
});

// 获取用户设置
router.get('/user', async (req, res) => {
  try {
    const data = {
      preferences: {
        theme: 'light',
        language: 'zh-CN',
        timezone: 'Asia/Shanghai'
      },
      notifications: {
        email: true,
        sms: false,
        wechat: true
      }
    };
    res.status(200).json({ success: true, data });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取用户设置失败' });
  }
});

// 保存用户设置
router.post('/user', async (req, res) => {
  try {
    // 模拟保存操作
    await new Promise(resolve => setTimeout(resolve, 200));
    res.status(200).json({ success: true, message: '设置保存成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: '保存用户设置失败' });
  }
});

// 测试数据库连接
router.post('/test-database', async (req, res) => {
  try {
    const { dbType, config } = req.body;
    logger.log(`测试${dbType}连接`, config);
    
    // 模拟测试操作
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    res.status(200).json({ success: true, message: `${dbType}连接测试成功` });
  } catch (error) {
    logger.error('测试数据库连接失败:', error);
    res.status(500).json({ success: false, message: '测试数据库连接失败' });
  }
});

// 测试数据源连接
router.post('/test-datasource', async (req, res) => {
  try {
    const { dsType, config } = req.body;
    logger.log(`测试${dsType}数据源连接`, config);
    
    // 模拟测试操作
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    res.status(200).json({ success: true, message: `${dsType}数据源连接测试成功` });
  } catch (error) {
    logger.error('测试数据源连接失败:', error);
    res.status(500).json({ success: false, message: '测试数据源连接失败' });
  }
});

// 保存配置
router.post('/save', async (req, res) => {
  try {
    const config = req.body;
    logger.log('保存配置:', config);
    
    // 保存配置到文件
    const fs = require('fs');
    const path = require('path');
    const configPath = path.join(__dirname, '../../../config.json');
    
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
    
    res.status(200).json({ success: true, message: '配置保存成功' });
  } catch (error) {
    logger.error('保存配置失败:', error);
    res.status(500).json({ success: false, message: '保存配置失败' });
  }
});

// 获取配置
router.get('/get', async (req, res) => {
  try {
    // 从文件读取配置
    const fs = require('fs');
    const path = require('path');
    const configPath = path.join(__dirname, '../../../config.json');
    
    let config = {};
    if (fs.existsSync(configPath)) {
      const configData = fs.readFileSync(configPath, 'utf8');
      config = JSON.parse(configData);
    }
    
    res.status(200).json({ success: true, data: config });
  } catch (error) {
    logger.error('获取配置失败:', error);
    res.status(500).json({ success: false, message: '获取配置失败' });
  }
});

export default router;