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

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

/** Next.js sets this while collecting page data / compiling the production build. */
function isNextProductionBuild(): boolean {
  return process.env.NEXT_PHASE === 'phase-production-build';
}

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) => {
  // Redis is intentionally unreachable during `next build` (Docker build
  // stage uses a placeholder REDIS_URL). Queues are lazy, but any stray
  // connect attempt should stay silent rather than spam AggregateError.
  if (isNextProductionBuild()) {
    return;
  }
  const detail =
    error instanceof Error
      ? error.message || ('code' in error ? String((error as NodeJS.ErrnoException).code) : error.name)
      : String(error);
  console.error('[redis]', detail);
});

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