import { getCachedRateLimiterService } from "@open-mercato/core/bootstrap";
import { checkRateLimit, getClientIp, RATE_LIMIT_ERROR_KEY, RATE_LIMIT_ERROR_FALLBACK } from "@open-mercato/shared/lib/ratelimit/helpers";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { computeEmailHash } from "@open-mercato/core/modules/auth/lib/emailHash";
async function checkAuthRateLimit(options) {
  try {
    const isIntegrationTestMode = process.env.OM_TEST_MODE === "1" && process.env.OM_TEST_AUTH_RATE_LIMIT_MODE === "opt-in";
    if (isIntegrationTestMode) {
      const rateLimitHeader = options.req.headers.get("x-om-test-rate-limit");
      if (rateLimitHeader !== "on") {
        return { error: null, compoundKey: null };
      }
    }
    const rateLimiterService = getCachedRateLimiterService();
    if (!rateLimiterService) return { error: null, compoundKey: null };
    const clientIp = getClientIp(options.req, rateLimiterService.trustProxyDepth);
    if (!clientIp) return { error: null, compoundKey: null };
    const { translate } = await resolveTranslations();
    const errorMessage = translate(RATE_LIMIT_ERROR_KEY, RATE_LIMIT_ERROR_FALLBACK);
    const ipError = await checkRateLimit(rateLimiterService, options.ipConfig, clientIp, errorMessage);
    if (ipError) return { error: ipError, compoundKey: null };
    if (options.compoundConfig && options.compoundIdentifier) {
      const hash = computeEmailHash(options.compoundIdentifier);
      const compoundKey = `${clientIp}:${hash}`;
      const compoundError = await checkRateLimit(rateLimiterService, options.compoundConfig, compoundKey, errorMessage);
      if (compoundError) return { error: compoundError, compoundKey };
      return { error: null, compoundKey };
    }
    return { error: null, compoundKey: null };
  } catch {
    return { error: null, compoundKey: null };
  }
}
async function resetAuthRateLimit(compoundKey, config) {
  try {
    const rateLimiterService = getCachedRateLimiterService();
    if (rateLimiterService) {
      await rateLimiterService.delete(compoundKey, config);
    }
  } catch {
  }
}
export {
  checkAuthRateLimit,
  resetAuthRateLimit
};
//# sourceMappingURL=rateLimitCheck.js.map
