/**
 * Worker Runner - Entry point for all worker types
 *
 * This file is the main entry point for Docker worker containers.
 * It reads WORKER_TYPE from environment and starts the appropriate worker.
 */

import { logger } from '../shared/utils/logger';

// Worker type from environment
const WORKER_TYPE = process.env.WORKER_TYPE || 'pdf';

async function startWorker(): Promise<void> {
  logger.info(`Starting ${WORKER_TYPE} worker...`);

  try {
    switch (WORKER_TYPE) {
      case 'pdf':
        await startPdfWorker();
        break;
      case 'exercise':
        await startExerciseWorker();
        break;
      case 'notification':
        await startNotificationWorker();
        break;
      default:
        logger.error(`Unknown worker type: ${WORKER_TYPE}`);
        process.exit(1);
    }
  } catch (error) {
    logger.error({ error }, `Failed to start ${WORKER_TYPE} worker`);
    process.exit(1);
  }
}

async function startPdfWorker(): Promise<void> {
  logger.info('PDF worker mode - waiting for jobs via API calls');

  // PDF worker is triggered via API, not a background queue
  // Keep the process alive
  logger.info('PDF worker ready');

  // Health check interval
  setInterval(() => {
    logger.debug('PDF worker heartbeat');
  }, 60000);
}

async function startExerciseWorker(): Promise<void> {
  await import('./exercise-generator.worker');

  logger.info('Exercise generator worker ready');

  // Health check interval
  setInterval(() => {
    logger.debug('Exercise worker heartbeat');
  }, 60000);

  // Handle shutdown
  process.on('SIGTERM', () => {
    logger.info('Received SIGTERM, shutting down exercise worker...');
    process.exit(0);
  });

  process.on('SIGINT', () => {
    logger.info('Received SIGINT, shutting down exercise worker...');
    process.exit(0);
  });
}

async function startNotificationWorker(): Promise<void> {
  const { startNotificationWorker, stopNotificationWorker } = await import('./notification-sender.worker');

  // Start the notification worker (polls database for pending notifications)
  startNotificationWorker();

  logger.info('Notification sender worker started successfully');

  // Handle shutdown
  process.on('SIGTERM', () => {
    logger.info('Received SIGTERM, shutting down notification worker...');
    stopNotificationWorker();
    process.exit(0);
  });

  process.on('SIGINT', () => {
    logger.info('Received SIGINT, shutting down notification worker...');
    stopNotificationWorker();
    process.exit(0);
  });
}

// Run the worker
startWorker().catch((error) => {
  logger.error({ error }, 'Worker startup failed');
  process.exit(1);
});