import { createApp } from "./app.js";
import { env } from "./config/env.js";
import { runMigrations } from "./db/migrate.js";
import { pool } from "./db/pool.js";
import { ensureDefaultAdmin } from "./modules/auth/auth.service.js";

const boot = async () => {
  await runMigrations();

  await ensureDefaultAdmin();

  const app = createApp();

  const server = app.listen(env.API_PORT, () => {
    console.log(`Rental API listening on ${env.API_PORT}`);
  });

  const shutdown = async () => {
    server.close(async () => {
      await pool.end();
      process.exit(0);
    });
  };

  process.on("SIGINT", shutdown);
  process.on("SIGTERM", shutdown);
};

boot().catch(async (error) => {
  console.error(error);
  await pool.end();
  process.exit(1);
});
