import Redis from 'ioredis';

export function createRedis(overrides = {}) {
  const url = overrides.url ?? process.env.REDIS_URL;

  const options = {
    lazyConnect: true,
    maxRetriesPerRequest: 3,
    enableOfflineQueue: false,
    retryStrategy(times) {
      return Math.min(times * 200, 2_000);
    },
    ...overrides,
  };

  if (url) {
    return new Redis(url, options);
  }

  return new Redis({
    host: overrides.host ?? process.env.REDIS_HOST ?? 'localhost',
    port: overrides.port ?? (Number(process.env.REDIS_PORT) || 6379),
    username: overrides.username ?? process.env.REDIS_USERNAME,
    password: overrides.password ?? process.env.REDIS_PASSWORD,
    ...options,
  });
}
