const { Sequelize } = require("sequelize");
const config = require("./config"); // Шлях до твого файлу з конфігом

const isLocal = config.dbUri === "local";

const sequelize = isLocal
  ? new Sequelize({
      dialect: "sqlite",
      storage: "./database.sqlite",
      logging: false,
      dialectOptions: { timeout: 20000 },
      pool: { max: 1, min: 1, idle: 10000, acquire: 30000 },
    })
  : new Sequelize(config.dbUri, {
      dialect: "postgres",
      logging: false,
      dialectOptions: {
        ssl: {
          require: true,
          rejectUnauthorized: false,
        },
      },
      pool: { max: 5, min: 0, idle: 10000, acquire: 30000 },
    });

sequelize.initDatabase = async () => {
  try {
    await sequelize.authenticate();

    if (isLocal) {
      await sequelize.query("PRAGMA journal_mode=WAL;");
      await sequelize.query("PRAGMA foreign_keys = OFF;");
    }

    await sequelize.sync({ alter: true });

    if (isLocal) {
      await sequelize.query("PRAGMA foreign_keys = ON;");
    }

    console.log(`✅ Database connected (${isLocal ? "SQLite" : "Postgres"})`);
    return true;
  } catch (error) {
    console.error("❌ Database Init Error:", error);
    throw error;
  }
};

module.exports = sequelize;
