import assert from "node:assert/strict";
import { test } from "bun:test";

import { handleTaskTreeProxyHttp } from "./tasktree-proxy.ts";

test("TaskTree proxy requires auth and forwards the unchanged API path", async () => {
  const originalFetch = globalThis.fetch;
  let upstreamUrl = "";
  globalThis.fetch = (async (input) => {
    upstreamUrl = String(input);
    return Response.json({ ok: true, operation: "group.list", data: { groups: [] } });
  }) as typeof fetch;
  const response = captureResponse();
  try {
    await handleTaskTreeProxyHttp(
      { method: "GET", headers: {} },
      response,
      new URL("http://cloud.test/v1/tasktree/groups"),
      {
        env: { HWLAB_TASKTREE_URL: "http://hwlab-tasktree-api.hwlab-v03.svc.cluster.local:6673" },
        accessController: { async authenticate() { return { ok: true, actor: { id: "usr_test" } }; } }
      }
    );
    assert.equal(upstreamUrl, "http://hwlab-tasktree-api.hwlab-v03.svc.cluster.local:6673/v1/tasktree/groups");
    assert.equal(response.status, 200);
    assert.deepEqual(JSON.parse(response.body), { ok: true, operation: "group.list", data: { groups: [] } });
  } finally {
    globalThis.fetch = originalFetch;
  }
});

function captureResponse() {
  return {
    status: 0,
    body: "",
    writeHead(status: number) { this.status = status; },
    end(body: string) { this.body = body; }
  };
}
