import { parseBooleanWithDefault } from "@open-mercato/shared/lib/boolean";
import { createLogger } from "@open-mercato/shared/lib/logger";
const VALID_STRATEGIES = ["memory", "redis"];
const logger = createLogger("ratelimit").child({ component: "config" });
function readRateLimitConfig() {
  const strategy = process.env.RATE_LIMIT_STRATEGY ?? "memory";
  if (!VALID_STRATEGIES.includes(strategy)) {
    throw new Error(`Invalid RATE_LIMIT_STRATEGY "${strategy}". Must be one of: ${VALID_STRATEGIES.join(", ")}`);
  }
  const trustProxyDepth = parseTrustProxyDepth(process.env.RATE_LIMIT_TRUST_PROXY_DEPTH);
  const integrationTest = parseBooleanWithDefault(process.env.OM_INTEGRATION_TEST, false);
  const enabled = integrationTest ? false : parseBooleanWithDefault(process.env.RATE_LIMIT_ENABLED, true);
  return {
    enabled,
    strategy,
    keyPrefix: process.env.RATE_LIMIT_KEY_PREFIX ?? "rl",
    redisUrl: process.env.REDIS_URL,
    trustProxyDepth
  };
}
function readEndpointRateLimitConfig(envPrefix, defaults) {
  return {
    points: parsePositiveInt(process.env[`RATE_LIMIT_${envPrefix}_POINTS`]) ?? defaults.points,
    duration: parsePositiveInt(process.env[`RATE_LIMIT_${envPrefix}_DURATION`]) ?? defaults.duration,
    blockDuration: parsePositiveInt(process.env[`RATE_LIMIT_${envPrefix}_BLOCK_DURATION`]) ?? defaults.blockDuration,
    keyPrefix: defaults.keyPrefix
  };
}
function parsePositiveInt(raw) {
  if (raw === void 0 || raw === "") return void 0;
  const parsed = Number(raw);
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
}
function parseTrustProxyDepth(raw) {
  if (raw === void 0 || raw.trim() === "") return 0;
  const parsed = Number(raw);
  if (Number.isInteger(parsed) && parsed >= 0) return parsed;
  logger.warn("Invalid RATE_LIMIT_TRUST_PROXY_DEPTH; using safe direct mode", { value: raw });
  return 0;
}
export {
  readEndpointRateLimitConfig,
  readRateLimitConfig
};
//# sourceMappingURL=config.js.map
