const mysql = require('mysql2/promise');
require('dotenv').config();

async function testConnection() {
  console.log('🔍 测试数据库连接...');
  console.log(`Host: ${process.env.DB_HOST}`);
  console.log(`Port: ${process.env.DB_PORT}`);
  console.log(`User: ${process.env.DB_USER}`);
  console.log(`Database: ${process.env.DB_NAME}`);
  
  const config = {
    host: process.env.DB_HOST,
    port: parseInt(process.env.DB_PORT),
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    connectTimeout: 60000,
    acquireTimeout: 60000,
    timeout: 60000
  };
  
  try {
    console.log('📡 尝试连接...');
    const connection = await mysql.createConnection(config);
    console.log('✅ 连接成功！');
    
    // 测试简单查询
    const [rows] = await connection.execute('SELECT 1 as test');
    console.log('✅ 查询测试成功:', rows);
    
    // 测试数据库信息
    const [version] = await connection.execute('SELECT VERSION() as version');
    console.log('📝 MySQL版本:', version[0].version);
    
    await connection.end();
    console.log('✅ 连接正常关闭');
    
  } catch (error) {
    console.error('❌ 连接失败:');
    console.error('错误代码:', error.code);
    console.error('错误信息:', error.message);
    console.error('错误详情:', error.sqlMessage || 'N/A');
    
    if (error.code === 'ER_ACCESS_DENIED_ERROR') {
      console.log('\n💡 可能的解决方案:');
      console.log('1. 检查用户名和密码是否正确');
      console.log('2. 确认用户有访问该数据库的权限');
      console.log('3. 检查IP白名单是否包含当前服务器IP');
    }
  }
}

testConnection();