import IORedis from 'ioredis';
import logger from '@utils/logger';

const redisUrl = process.env.REDIS_URL || 'redis://localhost:6379';
const redisPassword = process.env.REDIS_PASSWORD || undefined;

const redisOptions: any = {
  maxRetriesPerRequest: null, // Required for BullMQ
  enableReadyCheck: false,
  retryStrategy: (times: number) => {
    if (times > 5) {
      logger.error('[Redis] Connection failed after 5 attempts');
      return null;
    }
    return Math.min(times * 2000, 10000);
  },
  connectTimeout: 30000,
  commandTimeout: 20000,
  keepAlive: 30000,
  autoResubscribe: true,
  autoResendUnfulfilledCommands: true
};

if (redisPassword) {
  redisOptions.password = redisPassword;
  logger.info('[Redis] Using password authentication');
}

let sharedConnection: IORedis | null = null;

// Create a SINGLE shared connection for both Queue and Worker
export const getSharedRedisConnection = (): IORedis => {
  if (!sharedConnection) {
    logger.info(`[Redis] Connecting to ${redisUrl}`);
    
    sharedConnection = new IORedis(redisUrl, redisOptions);

    sharedConnection.on('connect', () => {
      logger.info(`[Redis] ✅ Connected successfully`);
    });

    sharedConnection.on('error', (err) => {
      logger.error('[Redis] Connection error:', err.message);
    });

    sharedConnection.on('close', () => {
      logger.warn('[Redis] Connection closed');
    });
  }
  
  return sharedConnection;
};

// Export for backwards compatibility
export const sharedRedisConnection = getSharedRedisConnection();

export default sharedRedisConnection;

