const path = require('path');
const fs = require('fs');
const { Sequelize } = require('sequelize');
// backend/.env (two levels up from src/config/)
require('dotenv').config({ path: path.join(__dirname, '..', '..', '.env') });

const logging = process.env.NODE_ENV === 'development' ? console.log : false;

const defineOpts = {
  timestamps: true,
  underscored: true,
  freezeTableName: true,
};

const dialect = (process.env.DB_DIALECT || 'sqlite').toLowerCase();

let sequelize;

if (dialect === 'postgres' || dialect === 'postgresql') {
  sequelize = new Sequelize(
    process.env.DB_NAME || 'luckychit',
    process.env.DB_USER || 'postgres',
    process.env.DB_PASSWORD || 'password',
    {
      host: process.env.DB_HOST || 'localhost',
      port: process.env.DB_PORT || 5432,
      dialect: 'postgres',
      logging,
      pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000,
      },
      define: defineOpts,
    }
  );
} else {
  const rawStorage =
    process.env.SQLITE_STORAGE || path.join(__dirname, '../../data/luckychit.sqlite');
  const storage = path.isAbsolute(rawStorage)
    ? rawStorage
    : path.join(__dirname, '../../', rawStorage);
  const dir = path.dirname(storage);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }

  sequelize = new Sequelize({
    dialect: 'sqlite',
    storage,
    logging,
    define: defineOpts,
  });
}

const testConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('✅ Database connection has been established successfully.');
    const d = sequelize.getDialect();
    const loc = d === 'sqlite' ? `: ${sequelize.options.storage}` : '';
    console.log(`   (${d}${loc})`);
  } catch (error) {
    console.error('❌ Unable to connect to the database:', error);
  }
};

module.exports = { sequelize, testConnection };
