const mysql = require('mysql2/promise');

// Load environment variables
require('dotenv').config();

async function testConnection() {
  const config = {
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
  };

  console.log('Testing database connection with config:');
  console.log(`Host: ${config.host}`);
  console.log(`Port: ${config.port}`);
  console.log(`Database: ${config.database}`);
  console.log(`User: ${config.user}`);

  try {
    const connection = await mysql.createConnection(config);
    console.log('✅ Successfully connected to the database!');
    
    // Test a simple query
    const [rows] = await connection.execute('SELECT 1 as connected');
    console.log('✅ Query test successful:', rows[0]);
    
    // Check if users table exists
    const [tables] = await connection.execute('SHOW TABLES LIKE "users"');
    if (tables.length > 0) {
      console.log('✅ Users table exists');
      
      // Count users in the table
      const [userRows] = await connection.execute('SELECT COUNT(*) as count FROM users');
      console.log(`✅ Found ${userRows[0].count} users in the users table`);
    } else {
      console.log('⚠️ Users table does not exist');
    }
    
    await connection.end();
    console.log('✅ Database connection test completed successfully!');
  } catch (error) {
    console.error('❌ Database connection failed:', error.message);
    if (error.code) {
      console.error('Error code:', error.code);
    }
    if (error.errno) {
      console.error('Error number:', error.errno);
    }
    if (error.sqlState) {
      console.error('SQL State:', error.sqlState);
    }
  }
}

testConnection();