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

import { caseRunInternalFetch, handleCaseRunHttp } from "./server-caserun-http.ts";

test("CaseRun internal requests reuse bootstrap key only for the internal origin", async () => {
  const calls: Array<{ url: string; authorization: string | null }> = [];
  const fetchImpl = async (input: URL | RequestInfo, init: RequestInit = {}) => {
    const headers = new Headers(init.headers);
    calls.push({ url: input instanceof Request ? input.url : String(input), authorization: headers.get("authorization") });
    return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
  };
  const internalFetch = caseRunInternalFetch(fetchImpl as typeof fetch, "http://hwlab-cloud-api.hwlab-v03.svc.cluster.local:6667", { HWLAB_BOOTSTRAP_ADMIN_API_KEY: "hwl_live_test" });
  await internalFetch("http://hwlab-cloud-api.hwlab-v03.svc.cluster.local:6667/v1/hwpod-node-ops", { method: "POST" });
  await internalFetch("https://lab-dev.hwpod.com/v1/hwpod-node-ops", { method: "POST" });
  assert.deepEqual(calls, [
    { url: "http://hwlab-cloud-api.hwlab-v03.svc.cluster.local:6667/v1/hwpod-node-ops", authorization: "Bearer hwl_live_test" },
    { url: "https://lab-dev.hwpod.com/v1/hwpod-node-ops", authorization: null }
  ]);
});

test("cloud-api preserves same-origin CaseRun routes as a pure HarnessRL proxy", async () => {
  const calls: Array<{ url: string; method: string; body: unknown }> = [];
  const fetchImpl = async (input: URL | RequestInfo, init: RequestInit = {}) => {
    const body = init.body ? JSON.parse(String(init.body)) : null;
    calls.push({ url: String(input), method: String(init.method), body });
    return Response.json({ ok: true, runId: "proxy-run", status: "queued", authority: "harnessrl" }, { status: 202 });
  };
  const server = createServer((request, response) => {
    const url = new URL(request.url ?? "/", "http://cloud-api.test");
    void handleCaseRunHttp(request, response, url, { env: { HARNESSRL_API_URL: "http://hwlab-harnessrl-api:6675" }, fetchImpl });
  });
  await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  try {
    const address = server.address();
    if (!address || typeof address === "string") throw new Error("server address unavailable");
    const response = await fetch(`http://127.0.0.1:${address.port}/v1/caserun/runs`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ caseId: "software-smoke" }) });
    assert.equal(response.status, 202);
    assert.deepEqual(await response.json(), { ok: true, runId: "proxy-run", status: "queued", authority: "harnessrl" });
    assert.deepEqual(calls, [{ url: "http://hwlab-harnessrl-api:6675/v1/caserun/runs", method: "POST", body: { caseId: "software-smoke" } }]);
  } finally {
    await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
  }
});

test("cloud-api refuses to recreate an in-process CaseRun fallback", async () => {
  const server = createServer((request, response) => {
    const url = new URL(request.url ?? "/", "http://cloud-api.test");
    void handleCaseRunHttp(request, response, url, { env: {} });
  });
  await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  try {
    const address = server.address();
    if (!address || typeof address === "string") throw new Error("server address unavailable");
    const response = await fetch(`http://127.0.0.1:${address.port}/v1/caserun/cases`);
    const payload = await response.json();
    assert.equal(response.status, 503);
    assert.equal(payload.error.code, "harnessrl_api_url_required");
  } finally {
    await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
  }
});
