import { createLogger } from "../logger/index.js";
const logger = createLogger("shared").child({ component: "redis" });
const REDIS_WIRE_PROTOCOL = 2;
function getRedisUrl(prefix) {
  if (prefix) {
    const prefixed = process.env[`${prefix}_REDIS_URL`];
    if (prefixed) return prefixed;
  }
  return process.env.REDIS_URL || null;
}
function getRedisUrlOrThrow(prefix) {
  const url = getRedisUrl(prefix);
  if (url) return url;
  const which = prefix ? `${prefix}_REDIS_URL or REDIS_URL` : "REDIS_URL";
  throw new Error(
    `Redis URL is not configured. Set ${which} in your environment to use a Redis-backed strategy.`
  );
}
function parseRedisUrl(url) {
  try {
    const parsed = new URL(url);
    const dbStr = parsed.pathname ? parsed.pathname.slice(1) : "";
    const dbParsed = dbStr !== "" ? parseInt(dbStr, 10) : NaN;
    const db = Number.isNaN(dbParsed) ? void 0 : dbParsed;
    const familyValue = parsed.searchParams.get("family");
    const familyParsed = familyValue !== null ? parseInt(familyValue, 10) : NaN;
    const family = [0, 4, 6].includes(familyParsed) ? familyParsed : void 0;
    return {
      host: parsed.hostname || "localhost",
      port: parseInt(parsed.port, 10) || 6379,
      username: parsed.username ? decodeURIComponent(parsed.username) : void 0,
      password: parsed.password ? decodeURIComponent(parsed.password) : void 0,
      db,
      tls: parsed.protocol === "rediss:" ? {} : void 0,
      family,
      protocol: REDIS_WIRE_PROTOCOL
    };
  } catch {
    const safeUrl = url.replace(/\/\/[^:]*:[^@]*@/, "//<redacted>@");
    logger.warn("Failed to parse Redis URL, falling back to localhost:6379", { url: safeUrl });
    return { host: "localhost", port: 6379, protocol: REDIS_WIRE_PROTOCOL };
  }
}
function resolveRedisConnection(prefix) {
  const url = getRedisUrl(prefix);
  if (!url) return null;
  return { url, ...parseRedisUrl(url) };
}
export {
  REDIS_WIRE_PROTOCOL,
  getRedisUrl,
  getRedisUrlOrThrow,
  parseRedisUrl,
  resolveRedisConnection
};
//# sourceMappingURL=connection.js.map
