import { logger } from '@goodgo/logger';

import { app } from './app';
import { appConfig } from './config/app.config';
import { prisma, connectDatabase } from './config/database.config';

const startServer = async () => {
  try {
    await connectDatabase();

    const server = app.listen(appConfig.port, () => {
      logger.info(`Service started on port ${appConfig.port}`, {
        port: appConfig.port,
        nodeEnv: appConfig.nodeEnv,
      });
    });

    // EN: Graceful shutdown
    // VI: Đóng ứng dụng một cách an toàn
    const shutdown = async (signal: string) => {
      logger.info(`${signal} received, shutting down gracefully`);

      server.close(async () => {
        logger.info('HTTP server closed');

        try {
          await prisma.$disconnect();
          logger.info('Database connection closed');
          process.exit(0);
        } catch (error) {
          logger.error('Error during shutdown', { error });
          process.exit(1);
        }
      });

      // EN: Force shutdown after 10s
      // VI: Buộc dừng sau 10 giây
      setTimeout(() => {
        logger.error('Forcing shutdown after timeout');
        process.exit(1);
      }, 10000);
    };

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

  } catch (error) {
    logger.error('Failed to start server', { error });
    process.exit(1);
  }
};

startServer();
