const test = require("node:test");
const assert = require("node:assert/strict");
const { createRateLimit } = require("../src/security/rateLimit");

function response() {
  return {
    headers: {},
    set(name, value) { this.headers[name] = value; },
    status(value) { this.statusCode = value; return this; },
    send(value) { this.body = value; return this; },
  };
}

test("rate limiter rejects requests beyond the configured window", () => {
  const middleware = createRateLimit({ windowMs: 60000, max: 2, error: "limited" });
  const req = { ip: "127.0.0.1", baseUrl: "/api/auth", path: "/signin/local" };
  let allowed = 0;

  middleware(req, response(), () => { allowed += 1; });
  middleware(req, response(), () => { allowed += 1; });
  const blocked = response();
  middleware(req, blocked, () => { allowed += 1; });

  assert.equal(allowed, 2);
  assert.equal(blocked.statusCode, 429);
  assert.deepEqual(blocked.body, { error: "limited" });
  assert.ok(blocked.headers["Retry-After"]);
});
