const { Sequelize } = require('sequelize');
const config = require('./config/config.json').development;

console.log('Docker数据库配置:', {
  host: config.host,
  database: config.database,
  username: config.username,
  dialect: config.dialect
});

const sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  dialect: config.dialect,
  logging: console.log,
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },
  dialectOptions: {
    ssl: false,
    connectTimeout: 60000
  }
});

async function testDockerConnection() {
  try {
    console.log('\n正在测试Docker数据库连接...');
    await sequelize.authenticate();
    console.log('✅ Docker数据库连接成功!');
    
    // 测试查询
    console.log('\n正在测试查询...');
    const [results] = await sequelize.query('SELECT 1 as test, NOW() as current_time');
    console.log('✅ 查询测试成功:', results);
    
    // 检查数据库版本
    const [version] = await sequelize.query('SELECT VERSION() as version');
    console.log('MySQL版本:', version[0].version);
    
    // 测试连接池状态
    console.log('\n连接池状态:');
    console.log('- 总连接数:', sequelize.connectionManager.pool.size);
    console.log('- 可用连接数:', sequelize.connectionManager.pool.available);
    console.log('- 使用中连接数:', sequelize.connectionManager.pool.using);
    console.log('- 等待连接数:', sequelize.connectionManager.pool.waiting);
    
  } catch (error) {
    console.error('❌ Docker数据库连接失败:');
    console.error('错误类型:', error.name);
    console.error('错误代码:', error.code || error.original?.code);
    console.error('错误消息:', error.message);
    
    if (error.code === 'ECONNREFUSED') {
      console.error('\n🔍 连接被拒绝分析:');
      console.error('- Docker MySQL容器可能未启动');
      console.error('- 端口3306可能被占用');
      console.error('- 建议检查: docker ps | grep mysql');
    }
    
  } finally {
    await sequelize.close();
    console.log('\n数据库连接已关闭');
  }
}

testDockerConnection();