import Redis from 'ioredis';
import { env } from './env';

const globalForRedis = globalThis as unknown as { __nexumiRedis?: Redis };

export const redis: Redis =
  globalForRedis.__nexumiRedis ??
  new Redis(env.REDIS_URL, {
    // BullMQ requires maxRetriesPerRequest: null on shared ioredis clients.
    maxRetriesPerRequest: null,
    // Defer the actual TCP connection until the first command is issued.
    // This keeps module import side-effect free, which matters for
    // Next.js's build-time "collect page data" step (no network access
    // there) and avoids unhandled 'error' events on unreachable hosts.
    lazyConnect: true
  });

redis.on('error', (error) => {
  console.error('[redis]', error.message);
});

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