import { logger } from './logger';

interface Stoppable {
  stop(): Promise<void>;
}

export function gracefulShutdown(services: Stoppable[]): void {
  const shutdown = async (signal: string) => {
    logger.info(`Received ${signal} signal, starting graceful shutdown...`);

    try {
      // Stop all services
      await Promise.all(services.map(service => service.stop()));
      
      logger.info('Graceful shutdown completed');
      process.exit(0);
    } catch (error) {
      logger.error('Error during shutdown', error);
      process.exit(1);
    }
  };

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

  // Handle uncaught errors
  process.on('uncaughtException', (error) => {
    logger.error('Uncaught exception', error);
    shutdown('uncaughtException');
  });

  process.on('unhandledRejection', (reason, promise) => {
    logger.error('Unhandled rejection', { reason, promise });
    shutdown('unhandledRejection');
  });
}