// src/services/worker.ts
import { gracefulShutdown } from './workers.server';
import { logger } from './logger.server';

logger.info('[Worker] Initializing worker process...');

// The workers are instantiated as side effects of importing workers.server.ts.
// This pattern ensures they start immediately upon import.

// Handle graceful shutdown
const handleShutdown = (signal: string) => {
  logger.info(`[Worker] Received ${signal}. Initiating graceful shutdown...`);
  gracefulShutdown(signal).catch((error: unknown) => {
    logger.error({ err: error }, '[Worker] Error during shutdown.');
    process.exit(1);
  });
};

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

// Catch unhandled errors to log them before crashing
process.on('uncaughtException', (err) => {
  logger.error({ err }, '[Worker] Uncaught exception');
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error({ reason, promise }, '[Worker] Unhandled Rejection');
});

logger.info('[Worker] Worker process is running and listening for jobs.');