import { rateLimit, type Options } from "express-rate-limit";
import { makeLogger } from "./logger.js";

const logger = makeLogger("rate-limiter");

function envInt(key: string, fallback: number): number {
  const v = process.env[key];
  const n = v ? parseInt(v, 10) : NaN;
  return Number.isNaN(n) ? fallback : n;
}

function limiter(windowMs: number, max: number, overrideKey?: string) {
  const resolvedMax = overrideKey ? envInt(overrideKey, max) : max;
  return rateLimit({
    windowMs,
    max: resolvedMax,
    standardHeaders: "draft-7",
    legacyHeaders: false,
    handler: (req, res) => {
      const ip =
        (req.headers["x-forwarded-for"] as string | undefined)?.split(",")[0]?.trim() ??
        req.socket.remoteAddress ??
        "unknown";
      logger.warn("rate limit hit", {
        route:    req.path,
        method:   req.method,
        ip,
        retry_after_s: Math.ceil(windowMs / 1000),
      });
      res.status(429).json({
        error: "rate_limited",
        message: "Too many requests — please slow down.",
        retryAfterSeconds: Math.ceil(windowMs / 1000),
      });
    },
  } satisfies Partial<Options>);
}

// POST /api/jobs — 30 req/min per IP (configurable via RATE_LIMIT_JOBS)
export const jobsLimiter = limiter(60_000, 30, "RATE_LIMIT_JOBS");

// POST /api/sessions — 10 req/min per IP (configurable via RATE_LIMIT_SESSIONS)
export const sessionsLimiter = limiter(60_000, 10, "RATE_LIMIT_SESSIONS");

// POST /api/bootstrap — 3 req/hour per IP (configurable via RATE_LIMIT_BOOTSTRAP)
export const bootstrapLimiter = limiter(60 * 60_000, 3, "RATE_LIMIT_BOOTSTRAP");
