import { createFlueClient } from "@flue/sdk";
import { describe, expect, test } from "vitest";

import { createFlueFetch } from "./flue-transport";

const BASE_URL = new URL("https://flue.example/api/");

describe("createFlueFetch", () => {
  test("overlapping SDK agent sends keep distinct request IDs", async () => {
    const firstResponse = Promise.withResolvers<Response>();
    const secondResponse = Promise.withResolvers<Response>();
    const bothStarted = Promise.withResolvers<boolean>();
    const capturedHeaders: Headers[] = [];
    let requestCount = 0;
    let requestId = 0;

    const fetchImpl: typeof fetch = (input, init) => {
      capturedHeaders.push(new Headers(init?.headers));
      requestCount += 1;
      if (requestCount === 2) {
        bothStarted.resolve(true);
      }
      if (requestCount === 1) {
        return firstResponse.promise;
      }
      if (requestCount === 2) {
        return secondResponse.promise;
      }
      throw new Error(`Unexpected request: ${String(input)}`);
    };
    const client = createFlueClient({
      baseUrl: BASE_URL.toString(),
      fetch: createFlueFetch({
        baseUrl: BASE_URL,
        fetchImpl,
        generateRequestId: () => `request-${(requestId += 1)}`,
      }),
      headers: { authorization: "Bearer current-jwt" },
    });

    const firstSend = client.agents.send("zopu", "org-a", {
      message: "first",
    });
    const secondSend = client.agents.send("zopu", "org-a", {
      message: "second",
    });
    await bothStarted.promise;

    expect(capturedHeaders).toHaveLength(2);
    expect(capturedHeaders[0]?.get("x-zopu-request-id")).toBe("request-1");
    expect(capturedHeaders[1]?.get("x-zopu-request-id")).toBe("request-2");
    expect(capturedHeaders[0]?.get("authorization")).toBe("Bearer current-jwt");
    expect(capturedHeaders[1]?.get("authorization")).toBe("Bearer current-jwt");

    firstResponse.resolve(
      Response.json(
        {
          offset: "1",
          streamUrl: "http://internal/streams/first",
          submissionId: "submission-1",
        },
        { status: 202 }
      )
    );
    secondResponse.resolve(
      Response.json(
        {
          offset: "2",
          streamUrl: "http://internal/streams/second",
          submissionId: "submission-2",
        },
        { status: 202 }
      )
    );

    await expect(Promise.all([firstSend, secondSend])).resolves.toEqual([
      {
        offset: "1",
        streamUrl: "https://flue.example/streams/first",
        submissionId: "submission-1",
      },
      {
        offset: "2",
        streamUrl: "https://flue.example/streams/second",
        submissionId: "submission-2",
      },
    ]);
  });

  test("history and stream observation requests remain untagged", async () => {
    const capturedHeaders: Headers[] = [];
    const fetchImpl: typeof fetch = (_input, init) => {
      capturedHeaders.push(new Headers(init?.headers));
      return Promise.resolve(new Response(null, { status: 204 }));
    };
    const flueFetch = createFlueFetch({
      baseUrl: BASE_URL,
      fetchImpl,
      generateRequestId: () => "must-not-be-used",
    });

    await flueFetch("https://flue.example/api/agents/zopu/org-a?view=history", {
      headers: { authorization: "Bearer current-jwt" },
      method: "GET",
    });
    await flueFetch("https://flue.example/api/agents/zopu/org-a?view=updates", {
      headers: { authorization: "Bearer current-jwt" },
      method: "GET",
    });

    expect(capturedHeaders).toHaveLength(2);
    expect(capturedHeaders[0]?.has("x-zopu-request-id")).toBe(false);
    expect(capturedHeaders[1]?.has("x-zopu-request-id")).toBe(false);
  });
});
