import { NextResponse } from "next/server";
import { z } from "zod";
const RATE_LIMIT_ERROR_KEY = "api.errors.rateLimit";
const RATE_LIMIT_ERROR_FALLBACK = "Too many requests. Please try again later.";
const RATE_LIMIT_FALLBACK_KEY = "global";
const RATE_LIMIT_UNAVAILABLE_KEY = "api.errors.rateLimitUnavailable";
const RATE_LIMIT_UNAVAILABLE_FALLBACK = "Service temporarily unavailable. Please try again later.";
const rateLimitErrorSchema = z.object({
  error: z.string().describe("Rate limit exceeded message")
});
async function checkRateLimit(rateLimiterService, config, key, errorMessage, options = {}) {
  const result = await rateLimiterService.consume(key, config);
  if (result.degraded && options.failClosed) {
    return NextResponse.json(
      { error: options.unavailableMessage ?? RATE_LIMIT_UNAVAILABLE_FALLBACK },
      { status: 503 }
    );
  }
  if (!result.allowed) {
    const retryAfterSec = Math.ceil(result.msBeforeNext / 1e3);
    return NextResponse.json(
      { error: errorMessage },
      {
        status: 429,
        headers: {
          "Retry-After": String(retryAfterSec),
          "X-RateLimit-Limit": String(config.points),
          "X-RateLimit-Remaining": String(result.remainingPoints),
          "X-RateLimit-Reset": String(retryAfterSec)
        }
      }
    );
  }
  return null;
}
function getClientIp(req, trustProxyDepth = 0) {
  const forwarded = req.headers.get("x-forwarded-for");
  if (!Number.isInteger(trustProxyDepth) || trustProxyDepth <= 0) {
    return null;
  }
  if (forwarded) {
    const ips = forwarded.split(",").map((ip) => ip.trim());
    const clientIndex = ips.length - trustProxyDepth;
    return clientIndex >= 0 ? ips[clientIndex] || null : null;
  }
  return trustProxyDepth === 1 ? req.headers.get("x-real-ip")?.trim() || null : null;
}
export {
  RATE_LIMIT_ERROR_FALLBACK,
  RATE_LIMIT_ERROR_KEY,
  RATE_LIMIT_FALLBACK_KEY,
  RATE_LIMIT_UNAVAILABLE_FALLBACK,
  RATE_LIMIT_UNAVAILABLE_KEY,
  checkRateLimit,
  getClientIp,
  rateLimitErrorSchema
};
//# sourceMappingURL=helpers.js.map
