const test = require("node:test");
const assert = require("node:assert/strict");
const { parseCookieHeader, sessionTokenFromRequest, protectCookieMutations } = require("../src/security/cookieAuth");

function request(overrides = {}) {
  const headers = { host: "workspace.test", cookie: "coaching_session=token", ...overrides.headers };
  return { method: "POST", protocol: "https", ...overrides, headers, get(name) { return headers[name.toLowerCase()]; } };
}

function response() {
  return { status(value) { this.statusCode = value; return this; }, send(value) { this.body = value; } };
}

test("cookie parser extracts the session", () => {
  assert.deepEqual(parseCookieHeader("one=1; coaching_session=abc%20123"), { one: "1", coaching_session: "abc 123" });
  assert.equal(sessionTokenFromRequest({ headers: { cookie: "coaching_session=token" } }), "token");
});

test("cookie mutations require a same-origin request", () => {
  let allowed = false;
  protectCookieMutations(request({ headers: { origin: "https://workspace.test" } }), response(), () => { allowed = true; });
  assert.equal(allowed, true);
  const blocked = response();
  protectCookieMutations(request({ headers: { origin: "https://attacker.test" } }), blocked, () => {});
  assert.equal(blocked.statusCode, 403);
});

test("bearer API requests remain available without browser CSRF headers", () => {
  let allowed = false;
  protectCookieMutations(request({ headers: { authorization: "Bearer api-token" } }), response(), () => { allowed = true; });
  assert.equal(allowed, true);
});
