import { env } from "./config/env.js";
import { buildServer } from "./api/server.js";
import { ping as pingDb, closePool } from "./db/mysql.js";
import { closeRedis } from "./redis/redis.js";

/**
 * Bootstrap da API. Confere o banco antes de subir e faz shutdown gracioso.
 */
async function main(): Promise<void> {
  await pingDb(); // falha cedo se o MySQL não estiver acessível

  const app = await buildServer();
  await app.listen({ port: env.PORT, host: env.HOST });

  const shutdown = async (signal: string): Promise<void> => {
    app.log.info(`Recebido ${signal}, encerrando...`);
    await app.close();
    await closePool();
    await closeRedis();
    process.exit(0);
  };
  process.on("SIGINT", () => void shutdown("SIGINT"));
  process.on("SIGTERM", () => void shutdown("SIGTERM"));
}

main().catch((err) => {
  console.error("Falha ao iniciar a API:", err instanceof Error ? err.message : err);
  process.exit(1);
});
