import "tsconfig-paths/register";
import { Logger, type INestApplication } from "@nestjs/common";

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

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);
        return;
      }

      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);
      }
    })();
  });
}

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);
  });
