/**
 * BullMQ Workers Entry Point
 *
 * Starts all queue workers:
 * - Email worker (transactional emails, OTP, notifications)
 * - Webhook worker (n8n, Stripe, external integrations)
 * - Analytics worker (event tracking, metrics)
 *
 * Usage:
 * - Development: `npm run worker:dev`
 * - Production: `npm run worker:start`
 * - Docker: Runs automatically in worker container
 */

import 'server-only';
import { logger } from '@/lib/logger';
import { startEmailWorker } from './email.worker';
import { startWebhookWorker } from './webhook.worker';
import { startAnalyticsWorker } from './analytics.worker';
import { startSystemWorker } from './system.worker';
import { subscribeToQueueEvents, QUEUE_NAMES, getAllQueueStats, scheduleDailyDriftCheck } from '../bullmq';

/**
 * Start all BullMQ workers
 */
export async function startAllWorkers() {
  logger.info('[Workers] Starting BullMQ workers...');

  try {
    // Start workers
    const emailWorker = startEmailWorker();
    const webhookWorker = startWebhookWorker();
    const analyticsWorker = startAnalyticsWorker();
    const systemWorker = startSystemWorker();

    // Subscribe to queue events for monitoring
    subscribeToQueueEvents(QUEUE_NAMES.EMAIL);
    subscribeToQueueEvents(QUEUE_NAMES.WEBHOOK);
    subscribeToQueueEvents(QUEUE_NAMES.ANALYTICS);
    subscribeToQueueEvents(QUEUE_NAMES.SYSTEM);

    // Schedule daily drift check (runs at 2 AM daily)
    await scheduleDailyDriftCheck({
      countThreshold: 10,
      percentageThreshold: 1,
      sendAlertEmail: true,
    });

    // Log initial queue stats
    const stats = await getAllQueueStats();
    logger.info('[Workers] All workers started successfully', { stats });

    // Health check interval (every 60s)
    const healthCheckInterval = setInterval(async () => {
      const currentStats = await getAllQueueStats();
      logger.debug('[Workers] Health check', { stats: currentStats });
    }, 60000);

    // Graceful shutdown
    const shutdown = async () => {
      logger.info('[Workers] Shutting down workers...');
      clearInterval(healthCheckInterval);

      await Promise.all([
        emailWorker.close(),
        webhookWorker.close(),
        analyticsWorker.close(),
        systemWorker.close(),
      ]);

      logger.info('[Workers] All workers stopped');
      process.exit(0);
    };

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

    return { emailWorker, webhookWorker, analyticsWorker, systemWorker };
  } catch (error) {
    logger.error('[Workers] Failed to start workers', {
      error: error instanceof Error ? error.message : String(error),
    });
    throw error;
  }
}

// Auto-start workers if this file is run directly
if (require.main === module) {
  startAllWorkers().catch((error) => {
    logger.error('[Workers] Fatal error', { error });
    process.exit(1);
  });
}
