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

let pool;

const connectDB = async () => {
  try {
    pool = await mysql.createPool({
      host: process.env.MYSQL_HOST,
      user: process.env.MYSQL_USER,
      password: process.env.MYSQL_PASSWORD,
      database: process.env.MYSQL_DATABASE,
      port: process.env.PORT || 3306,
      waitForConnections: true,
      connectionLimit: 100,
      queueLimit: 0,
    });

    const [rows] = await pool.query('SELECT 1');
    console.log('✅ MySQL Connected');
  } catch (error) {
    console.error(`❌ MySQL Connection Error: ${error.message}`);
    process.exit(1);
  }
};

const getPool = () => {
  if (!pool) {
    throw new Error('MySQL pool not initialized. Call connectDB first.');
  }
  return pool;
};

module.exports = { connectDB, getPool };