import Redis from "ioredis";

const REDIS_URL = process.env.REDIS_URL || "redis://127.0.0.1:6379";

/**
 * Shared Redis client for BullMQ.
 * BullMQ requires maxRetriesPerRequest: null.
 *
 * lazyConnect + connectTimeout mean: don't auto-connect on require(),
 * and if Redis is unreachable, fail within 3 s instead of hanging forever.
 */
export const redisConnection = new Redis(REDIS_URL, {
  maxRetriesPerRequest: null,
  enableReadyCheck: false,
  lazyConnect: true,
  connectTimeout: 3_000,       // give up after 3 s if Redis is down
  retryStrategy: (times) => {
    // Stop retrying after 2 attempts so a missing Redis server is
    // reported quickly rather than blocking the request indefinitely.
    if (times > 2) return null;
    return Math.min(times * 500, 1_000);
  },
});

redisConnection.on("error", (err) => {
  console.error("[Redis] connection error:", err.message);
});

redisConnection.on("connect", () => {
  console.log("[Redis] connected at", REDIS_URL);
});

/** True once a successful connection has been established. */
export let redisReady = false;
redisConnection.on("ready", () => { redisReady = true; });
redisConnection.on("close", () => { redisReady = false; });
