import { Provider } from "@nestjs/common";
import Redis from "ioredis";

export const REDIS_PUBSUB = "REDIS_PUBSUB";

/**
 * Load-bearing Redis connection used by libs/messaging to publish realtime
 * events (see libs/messaging/src/events-bus.ts) — distinct from
 * redis.provider.ts's dev-only, capped-retry client, which only backs the
 * throwaway /dev/ping demo. Normal ioredis retry/backoff applies: if Redis
 * is down, writes still succeed but nobody gets a live update until it's
 * back (acceptable — catch-up on reconnect, §5.3, is what repairs that gap).
 */
export const redisPubSubProvider: Provider = {
  provide: REDIS_PUBSUB,
  useFactory: () => {
    const client = new Redis(process.env.REDIS_URL ?? "redis://localhost:6379", {
      // Fail a publish() fast rather than queuing/retrying 20x per call —
      // events-bus.ts already treats a broadcast failure as non-fatal, so
      // there's no value in blocking the request for multiple retry rounds.
      maxRetriesPerRequest: 1,
    });
    client.on("error", () => undefined); // avoid unhandled 'error' event noise; retries/backoff still happen internally
    return client;
  },
};
