const WINDOW_MS = 60_000;
const MAX_REQUESTS = 5;

interface RateLimitEntry {
  count: number;
  resetAt: number;
}

const hits = new Map<string, RateLimitEntry>();

export function checkOtpRateLimit(ip: string): { allowed: boolean; retryAfter?: number } {
  if (process.env.CORE_API_USE_MOCK === "true") {
    return { allowed: true };
  }

  const now = Date.now();
  const entry = hits.get(ip);

  if (!entry || now >= entry.resetAt) {
    hits.set(ip, { count: 1, resetAt: now + WINDOW_MS });
    return { allowed: true };
  }

  if (entry.count >= MAX_REQUESTS) {
    return { allowed: false, retryAfter: Math.ceil((entry.resetAt - now) / 1000) };
  }

  entry.count += 1;
  return { allowed: true };
}

/** @internal Test helper */
export function resetOtpRateLimitForTests(): void {
  hits.clear();
}
