/**
 * Worker Service Entry Point for Redirect Intelligence v2
 * 
 * Handles bulk URL tracking jobs and background processing
 */

import dotenv from 'dotenv';
import { logger } from './lib/logger';
import { BulkTrackingWorker } from './workers/bulk-tracking.worker';

// Load environment variables
dotenv.config();

async function startWorker() {
  try {
    logger.info('🔄 Starting Redirect Intelligence Worker Service...');
    
    // Initialize bulk tracking worker
    const bulkWorker = new BulkTrackingWorker();
    await bulkWorker.start();
    
    logger.info('🚀 Worker service started successfully', {
      environment: process.env.NODE_ENV || 'development',
      redisHost: process.env.REDIS_HOST || 'localhost',
      concurrency: process.env.BULK_WORKER_CONCURRENCY || '3',
    });
    
    // Health check logging
    setInterval(() => {
      const health = bulkWorker.getHealthStatus();
      logger.debug('Worker health check', health);
    }, 30000); // Every 30 seconds
    
    // Graceful shutdown handlers
    const shutdown = async (signal: string) => {
      logger.info(`🛑 Received ${signal}, shutting down gracefully...`);
      try {
        await bulkWorker.stop();
        logger.info('✅ Worker shutdown completed');
        process.exit(0);
      } catch (error) {
        logger.error('❌ Error during shutdown:', error);
        process.exit(1);
      }
    };
    
    process.on('SIGTERM', () => shutdown('SIGTERM'));
    process.on('SIGINT', () => shutdown('SIGINT'));
    
    // Unhandled error handlers
    process.on('uncaughtException', (error) => {
      logger.error('💥 Uncaught Exception:', error);
      process.exit(1);
    });
    
    process.on('unhandledRejection', (reason, promise) => {
      logger.error('💥 Unhandled Rejection at:', promise, 'reason:', reason);
      process.exit(1);
    });
    
  } catch (error) {
    logger.error('❌ Failed to start worker service:', error);
    process.exit(1);
  }
}

// Start the worker
startWorker();