import Redis from 'ioredis';

const isDockerContainer =
  process.env.IS_DOCKER === 'true' || process.env.HOSTNAME?.includes('klz-app');
const redisUrl =
  process.env.REDIS_URL ||
  (isDockerContainer ? 'redis://klz-redis:6379' : 'redis://localhost:6379');

// Only create a single instance in Node.js
const globalForRedis = global as unknown as { redis: Redis };

export const redis =
  globalForRedis.redis ||
  new Redis(redisUrl, {
    maxRetriesPerRequest: 3,
  });

if (process.env.NODE_ENV !== 'production') {
  globalForRedis.redis = redis;
}

export default redis;
