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

const isURL = !!process.env.DATABASE_URL;

const sequelize = isURL
  ? new Sequelize(process.env.DATABASE_URL, {
    dialect: "postgres",
    //logging: (msg) => logger.debug(msg),
    dialectOptions: {
      ssl: {
        require: true,
        rejectUnauthorized: false, // REQUIRED for Render
      },
    },
    pool: {
      max: 5,
      min: 1,
      acquire: 30000,
      idle: 10000,
    },
    define: {
      timestamps: true,
      underscored: true,
      freezeTableName: true,
    },
  })
  : new Sequelize(
    process.env.DB_NAME,
    process.env.DB_USER,
    process.env.DB_PASSWORD,
    {
      host: process.env.DB_HOST,
      port: process.env.DB_PORT || 3306,
      dialect: "mysql",
      //logging: (msg) => logger.debug(msg),
      logging: false,
      //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,
      },

      define: {
        timestamps: true,
        underscored: true,
        freezeTableName: true,
      },
      dialectOptions: {
        decimalNumbers: true,
        ssl: { rejectUnauthorized: false }
      }/*  */
    }
  );

const connectDB = async () => {
  try {
    await sequelize.authenticate();
    logger.info('MySql Connected successfully');

    // Sync models in development (be careful in production)
    if (process.env.NODE_ENV === 'development') {
      // await sequelize.sync({ alter: true });
      // logger.info('Database synchronized');
    }

    return sequelize;
  } catch (error) {
    logger.error(`Error connecting to MySql: ${error.message}`);
    process.exit(1);
  }
};

// Graceful shutdown
process.on('SIGINT', async () => {
  await sequelize.close();
  logger.info('MySql connection closed through app termination');
  process.exit(0);
});

module.exports = { sequelize, connectDB };