import { createMiddleware } from "hono/factory";

type Store = Map<string, { count: number; resetAt: number }>;

function createRateLimiter(max: number, windowMs: number) {
  const store: Store = new Map();
  return createMiddleware(async (c, next) => {
    const key =
      c.req.header("x-forwarded-for") ??
      c.req.header("cf-connecting-ip") ??
      "unknown";
    const now = Date.now();
    const entry = store.get(key);
    if (!entry || entry.resetAt < now) {
      store.set(key, { count: 1, resetAt: now + windowMs });
      return next();
    }
    entry.count++;
    if (entry.count > max) {
      return c.json({ error: "Too many requests" }, 429);
    }
    return next();
  });
}

export const inviteJoinLimiter = createRateLimiter(10, 60 * 60 * 1000);  // 10/hour
export const scannerLimiter = createRateLimiter(50, 60 * 60 * 1000);     // 50/hour
export const authLimiter = createRateLimiter(10, 60 * 1000);             // 10/minute
