import { createApp } from "./app.js";
import { config } from "./config.js";
import { pool } from "./db/client.js";

const app = createApp();
const server = app.listen(config.port, () => {
  console.log(`[bousla-api] listening on http://127.0.0.1:${config.port} (${config.env})`);
});

async function shutdown(signal: string): Promise<void> {
  console.log(`[bousla-api] ${signal} received, shutting down...`);
  server.close(async () => {
    await pool.end().catch(() => undefined);
    process.exit(0);
  });
  // Force-exit if connections refuse to drain
  setTimeout(() => process.exit(1), 10_000).unref();
}

process.on("SIGINT", () => void shutdown("SIGINT"));
process.on("SIGTERM", () => void shutdown("SIGTERM"));
