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

// MySQL database configuration
const mysqlConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'project_management',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  acquireTimeout: 60000,
  timeout: 60000,
  reconnect: true
};

const testMySQLConnection = async () => {
  console.log('🔄 Testing MySQL connection...');
  
  try {
    // Create connection pool
    const pool = mysql.createPool(mysqlConfig);
    console.log('✅ MySQL connection pool created');
    
    // Get a connection from the pool
    const connection = await pool.getConnection();
    console.log('✅ MySQL connection established');
    
    // Test a simple query
    const [rows] = await connection.execute('SELECT 1 as test');
    console.log('✅ MySQL query executed successfully:', rows[0]);
    
    // Release the connection
    connection.release();
    
    // Close the pool
    await pool.end();
    console.log('✅ MySQL connection pool closed');
    
    console.log('🎉 All MySQL tests passed!');
    return true;
  } catch (error) {
    console.error('❌ MySQL connection test failed:', error.message);
    return false;
  }
};

// Run test if this script is executed directly
if (require.main === module) {
  testMySQLConnection()
    .then((success) => {
      if (success) {
        console.log('✅ MySQL connection test completed successfully');
        process.exit(0);
      } else {
        console.log('❌ MySQL connection test failed');
        process.exit(1);
      }
    })
    .catch((error) => {
      console.error('💥 MySQL connection test failed with error:', error.message);
      process.exit(1);
    });
}

module.exports = { testMySQLConnection };