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

const envName = process.env.NODE_ENV || 'development';
const fileConfig = require('./config.json')[envName];

if (!fileConfig) {
  throw new Error(
    `[DB] Kein Eintrag in config/config.json für NODE_ENV="${envName}".`
  );
}

const database = process.env.DB_NAME || fileConfig.database;
const username = process.env.DB_USER || fileConfig.username;
const password =
  process.env.DB_PASSWORD === undefined ? fileConfig.password : process.env.DB_PASSWORD;
const host = process.env.DB_HOST || fileConfig.host;

const sequelizeOptions = {
  host,
  dialect: fileConfig.dialect || 'mysql',
  dialectOptions: fileConfig.dialectOptions,
  retry: {
    match: [
      /ConnectionError/,
      /SequelizeConnectionError/,
      /SequelizeConnectionRefusedError/,
      /SequelizeHostNotFoundError/,
      /SequelizeHostNotReachableError/,
      /SequelizeInvalidConnectionError/,
      /SequelizeConnectionTimedOutError/,
    ],
    max: 5,
  },
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000,
  },
  logging: process.env.DB_LOGGING === '1' ? console.log : false,
};

if (process.env.DB_PORT) {
  sequelizeOptions.port = parseInt(process.env.DB_PORT, 10);
} else if (fileConfig.port) {
  sequelizeOptions.port = fileConfig.port;
}

const sequelize = new Sequelize(database, username, password, sequelizeOptions);

async function connectWithRetry() {
  try {
    await sequelize.authenticate();
    console.log(
      `[DB] Verbindung OK — host=${host} database=${database} user=${username} (NODE_ENV=${envName})`
    );
  } catch (error) {
    console.error('[DB] Verbindung fehlgeschlagen:', error.message);
    console.error(
      `[DB] Erwartete Quelle: config/config.json → "${envName}" oder Umgebungsvariablen DB_HOST, DB_USER, DB_PASSWORD, DB_NAME`
    );
    setTimeout(connectWithRetry, 5000);
  }
}

connectWithRetry();

module.exports = sequelize;
