import { app } from "./app";
import { env } from "./config/env";
import { logger } from "./common/utils/logger";
import { prisma } from "./config/prisma";
import { createServer } from "http";
import { initSocket } from "./config/socket";

const httpServer = createServer(app);
initSocket(httpServer);

const server = httpServer.listen(env.PORT, () => {
  logger.info(`🚀 Server running on http://localhost:${env.PORT}`);
});

async function shutdown(signal: string) {
  logger.info(`${signal} received. Shutting down gracefully...`);
  server.close(async () => {
    await prisma.$disconnect();
    process.exit(0);
  });
}

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

process.on("uncaughtException", (err: Error) => {
  logger.fatal(
    { err, stack: err.stack },
    "FATAL: Uncaught Exception. Shutting down...",
  );
  process.exit(1);
});

process.on("unhandledRejection", (reason: unknown) => {
  logger.fatal({ reason }, "FATAL: Unhandled Promise Rejection.");
  process.exit(1);
});
