const { Sequelize } = require('sequelize');
const logger = require('./logger');

const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
  host: process.env.DB_HOST,
  dialect: 'postgres',
  logging: (msg) => logger.debug(msg),
  pool: {
    max: parseInt(process.env.DB_POOL_MAX, 10) || 10,
    min: parseInt(process.env.DB_POOL_MIN, 10) || 0,
    acquire: parseInt(process.env.DB_POOL_ACQUIRE, 10) || 30000,
    idle: parseInt(process.env.DB_POOL_IDLE, 10) || 10000
  },
  dialectOptions: {
    ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false,
    connectTimeout: 60000
  },
  retry: {
    max: 5,
    backoffBase: 1000,
    backoffExponent: 1.5
  },
  benchmark: process.env.NODE_ENV === 'development',
  logQueryParameters: process.env.NODE_ENV === 'development'
});

const connectDB = async () => {
  let retries = 5;
  while (retries) {
    try {
      await sequelize.authenticate();
      logger.info('Database connection established successfully');
      return;
    } catch (err) {
      retries -= 1;
      logger.error(`Database connection attempt failed. Retries left: ${retries}`, { error: err.message });
      if (!retries) {
        logger.error('All database connection attempts failed. Exiting...', { error: err.stack });
        process.exit(1);
      }
      await new Promise(resolve => setTimeout(resolve, 5000));
    }
  }
};

process.on('SIGINT', async () => {
  try {
    await sequelize.close();
    logger.info('Database connection closed.');
    process.exit(0);
  } catch (err) {
    logger.error('Error during database disconnection:', err);
    process.exit(1);
  }
});

connectDB();

module.exports = sequelize;