const { Sequelize } = require('sequelize');
require('dotenv').config();

const sequelize = new Sequelize(
  process.env.MYSQL_DATABASE,
  process.env.MYSQL_USER,
  process.env.MYSQL_PASSWORD,
  {
    host: process.env.DB_HOST,
    dialect: 'mysql',
    logging: false,
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    }
  }
);

// Test Connection
const connectDB = async () => {
  let retries = 20; // Increased retries for slow DB startup
  while (retries > 0) {
    try {
      console.log(`[Database] Attempting to connect... (Retries left: ${retries})`);
      await sequelize.authenticate();
      console.log('[Database] Connection has been established successfully.');
      return;
    } catch (error) {
      console.error(`[Database] Unable to connect. Retrying in 5s...`, error.message);
      retries -= 1;
      await new Promise(res => setTimeout(res, 5000)); // Wait 5 seconds
    }
  }
  console.error('[Database] Failed to connect after multiple attempts.');
  process.exit(1);
};

module.exports = { sequelize, connectDB };
