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

let tatQueue: Queue | null = null;

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

try {
  // Use shared Redis connection for both Queue and Worker
  tatQueue = new Queue('tatQueue', {
    connection: sharedRedisConnection,
    defaultJobOptions: {
      removeOnComplete: true,
      removeOnFail: false,
      attempts: 2,
      backoff: {
        type: 'fixed',
        delay: 5000
      }
    }
  });
  
  tatQueue.on('error', (error) => {
    const now = Date.now();
    if (now - lastTatQueueErrorLog >= QUEUE_ERROR_LOG_INTERVAL_MS) {
      lastTatQueueErrorLog = now;
      logger.error('[TAT Queue] Queue error (Redis may be down):', (error as Error)?.message || error);
    }
  });

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

export { tatQueue };

