import { Logger } from "@nestjs/common";
import type { INestApplication } from "@nestjs/common";

import { bootstrap } from "./app/bootstrap.js";

const logger = new Logger("Main");
let app: INestApplication | null = null;

const signals: NodeJS.Signals[] = ["SIGINT", "SIGTERM"];
for (const signal of signals) {
  process.once(signal, () => {
    void (async () => {
      logger.log(`Received ${signal}. Closing Nest application...`);

      if (!app) {
        logger.warn("Nest application not initialized. Exiting immediately.");
        process.exit(0);
      }

      try {
        await app.close();
        logger.log("Nest application closed gracefully.");
      } catch (error) {
        const resolvedError = error as Error;
        logger.error(
          `Error during Nest application shutdown: ${resolvedError.message}`,
          resolvedError.stack
        );
      } finally {
        process.exit(0);
      }
    })();
  });
}

process.on("uncaughtException", error => {
  logger.error(`Uncaught Exception: ${error.message}`, error.stack);
  process.exit(1);
});

process.on("unhandledRejection", reason => {
  const message = reason instanceof Error ? reason.message : String(reason);
  const stack = reason instanceof Error ? reason.stack : undefined;
  logger.error(`Unhandled Rejection: ${message}`, stack);
});

void bootstrap()
  .then(startedApp => {
    app = startedApp;
  })
  .catch(error => {
    const resolvedError = error as Error;
    logger.error(
      `Failed to bootstrap the Nest application: ${resolvedError.message}`,
      resolvedError.stack
    );
    process.exit(1);
  });
