import { createMiddleware } from "hono/factory";
import { logError } from "@/lib/logger";

/**
 * Fixed-window rate limit on Redis, shared by the Kevo and Guru public
 * (agent-facing) endpoints.
 * ponytail: per-instance window key, no sliding window — enough to blunt
 * abuse of a secret-protected endpoint; upgrade to a token bucket if the
 * agent fleet ever legitimately bursts past this.
 */
export const rateLimit = (prefix: string, limit: number, windowSecs: number) =>
  createMiddleware(async (c, next) => {
    try {
      const redis = c.get("redisDB");
      const ip =
        c.req.header("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";
      const key = `${prefix}:rl:${c.req.path}:${ip}:${Math.floor(Date.now() / 1000 / windowSecs)}`;
      const count = await redis.incr(key);
      if (count === 1) await redis.expire(key, windowSecs);
      if (count > limit) return c.text("Too many requests", 429);
    } catch (err) {
      // Redis trouble must not take the tool endpoints down with it.
      logError(`[${prefix}] rate limiter unavailable: ${err}`);
    }
    await next();
  });
