/**
 * Worker entry point for the crm-worker container.
 *
 * Imports all BullMQ workers and registers recurring job schedules.
 * In production this runs as a separate process (Dockerfile.worker).
 * In development, server.ts imports workers inline instead.
 */

import { logger } from '@/lib/logger';
import { registerRecurringJobs } from '@/lib/queue/scheduler';

// Import all workers - the act of importing starts them
import { emailWorker } from '@/lib/queue/workers/email';
import { documentsWorker } from '@/lib/queue/workers/documents';
import { notificationsWorker } from '@/lib/queue/workers/notifications';
import { importWorker } from '@/lib/queue/workers/import';
import { exportWorker } from '@/lib/queue/workers/export';
import { aiWorker } from '@/lib/queue/workers/ai';
import { bulkWorker } from '@/lib/queue/workers/bulk';
import { maintenanceWorker } from '@/lib/queue/workers/maintenance';
import { reportsWorker } from '@/lib/queue/workers/reports';
import { webhooksWorker } from '@/lib/queue/workers/webhooks';

// Keep references so workers aren't GC'd
const workers = [
  emailWorker,
  documentsWorker,
  notificationsWorker,
  importWorker,
  exportWorker,
  aiWorker,
  bulkWorker,
  maintenanceWorker,
  reportsWorker,
  webhooksWorker,
];

async function main(): Promise<void> {
  logger.info({ workerCount: workers.length }, 'BullMQ workers started');

  await registerRecurringJobs();
  logger.info('Recurring jobs registered');

  // Graceful shutdown
  const shutdown = async () => {
    logger.info('Shutting down workers...');
    await Promise.all(workers.map((w) => w.close()));
    logger.info('All workers closed');
    process.exit(0);
  };

  process.on('SIGTERM', shutdown);
  process.on('SIGINT', shutdown);
}

main().catch((err) => {
  logger.error(err, 'Worker process failed to start');
  process.exit(1);
});
