const env = require('./config/env');
const { app } = require('./app');
const { pool } = require('./db/pool');
const { ensureInvimaTables } = require('../invima/service');
const {
  cleanupExpiredSessions,
  ensureAuthTables,
  ensureDefaultAdmin
} = require('./auth/auth.service');

const start = async () => {
  try {
    await pool.query('SELECT 1');
    await ensureAuthTables(pool);
    await ensureInvimaTables(pool);
    const admin = await ensureDefaultAdmin(pool);
    await cleanupExpiredSessions(pool);

    const server = app.listen(env.PORT, () => {
      console.log(`[BOOT] API en http://localhost:${env.PORT}`);
      if (admin.created) {
        console.log(`[BOOT] Usuario admin creado: ${admin.user.username}`);
      }
    });

    const shutdown = async (signal) => {
      console.log(`[BOOT] Cerrando servidor (${signal})`);
      server.close(async () => {
        await pool.end();
        process.exit(0);
      });
    };

    process.once('SIGINT', () => shutdown('SIGINT'));
    process.once('SIGTERM', () => shutdown('SIGTERM'));
  } catch (error) {
    console.error('[BOOT] No se pudo iniciar:', error);
    process.exit(1);
  }
};

start();
