import { createMiddleware } from "hono/factory";
import { apiError } from "../lib/errors";
import type { AppEnv } from "../types";

const WINDOW_MS = 60_000;
const MAX_REQUESTS = 120;
const ACTIVATE_MAX_REQUESTS = 10;

const counters = new Map<string, { windowStart: number; count: number }>();

export function checkRateLimit(key: string, now: number, max = MAX_REQUESTS): boolean {
  const entry = counters.get(key);
  if (!entry || now - entry.windowStart >= WINDOW_MS) {
    counters.set(key, { windowStart: now, count: 1 });
    return true;
  }
  entry.count += 1;
  return entry.count <= max;
}

export function resetRateLimits(): void {
  counters.clear();
}

export const rateLimit = createMiddleware<AppEnv>(async (c, next) => {
  const site = c.get("site");
  if (!checkRateLimit(site.id, Date.now())) {
    return apiError(c, 429, "rate_limited", "Too many requests for this site");
  }
  await next();
});

export const activateRateLimit = createMiddleware<AppEnv>(async (c, next) => {
  const ip = c.req.header("cf-connecting-ip") ?? "unknown";
  if (!checkRateLimit(`activate:${ip}`, Date.now(), ACTIVATE_MAX_REQUESTS)) {
    return apiError(c, 429, "rate_limited", "Too many activation attempts");
  }
  await next();
});
