import { Queue } from 'bullmq';
import { sharedRedisConnection } from './redisConnection';
import logger from '@utils/logger';

let pauseResumeQueue: Queue | null = null;

const QUEUE_ERROR_LOG_INTERVAL_MS = 2 * 60 * 1000;
let lastPauseResumeQueueErrorLog = 0;

try {
  // Use shared Redis connection for both Queue and Worker
  pauseResumeQueue = new Queue('pauseResumeQueue', {
    connection: sharedRedisConnection,
    defaultJobOptions: {
      removeOnComplete: {
        age: 86400, // Keep completed jobs for 24 hours
        count: 1000
      },
      removeOnFail: false,
      attempts: 3,
      backoff: {
        type: 'exponential',
        delay: 5000
      }
    }
  });
  
  pauseResumeQueue.on('error', (error) => {
    const now = Date.now();
    if (now - lastPauseResumeQueueErrorLog >= QUEUE_ERROR_LOG_INTERVAL_MS) {
      lastPauseResumeQueueErrorLog = now;
      logger.error('[Pause Resume Queue] Queue error (Redis may be down):', (error as Error)?.message || error);
    }
  });

  logger.info('[Pause Resume Queue] ✅ Queue initialized');
} catch (error) {
  logger.error('[Pause Resume Queue] Failed to initialize:', error);
  pauseResumeQueue = null;
}

export { pauseResumeQueue };

