import { beforeEach, describe, expect, it, vi } from "vitest";

const mockResolveMnoteWebInternalUrl = vi.fn();
const mockBuildForwardHeaders = vi.fn();
const mockFetch = vi.fn();

vi.mock("@/lib/mnote-web/internal-url", () => ({
  resolveMnoteWebInternalUrl: (...args: unknown[]) => mockResolveMnoteWebInternalUrl(...args),
}));

vi.mock("@/lib/server/forward-headers", () => ({
  buildForwardHeaders: (...args: unknown[]) => mockBuildForwardHeaders(...args),
}));

describe("/api/tree/shell route", () => {
  beforeEach(() => {
    mockResolveMnoteWebInternalUrl.mockReset();
    mockBuildForwardHeaders.mockReset();
    mockFetch.mockReset();
    vi.stubGlobal("fetch", mockFetch);
  });

  it("通过 3000 同源代理回源 mnote-web tree shell，并移除不应透传的响应头", async () => {
    mockResolveMnoteWebInternalUrl.mockResolvedValue("http://127.0.0.1:3104");
    mockBuildForwardHeaders.mockResolvedValue(
      new Headers({
        cookie: "session=abc",
        authorization: "Bearer test-token",
      }),
    );
    mockFetch.mockResolvedValue(
      new Response("<!doctype html><html><body>tree shell</body></html>", {
        status: 200,
        headers: {
          "content-type": "text/html; charset=utf-8",
          "set-cookie": "debug=1",
          connection: "keep-alive",
          "x-upstream": "mnote-web-tree",
        },
      }),
    );

    const { GET } = await import("./route");
    const response = await GET(
      new Request(
        "http://127.0.0.1:3000/api/tree/shell?workspaceId=ws_1&mode=page&activeDocumentId=doc_9",
        {
          method: "GET",
          headers: {
            cookie: "session=abc",
          },
        },
      ),
    );

    expect(mockFetch).toHaveBeenCalledWith(
      "http://127.0.0.1:3104/tree?workspaceId=ws_1&mode=page&activeDocumentId=doc_9",
      expect.objectContaining({
        method: "GET",
        headers: expect.any(Headers),
        cache: "no-store",
        redirect: "manual",
      }),
    );

    const fetchHeaders = mockFetch.mock.calls[0]?.[1]?.headers as Headers;
    expect(fetchHeaders.get("cookie")).toBe("session=abc");
    expect(fetchHeaders.get("authorization")).toBe("Bearer test-token");
    expect(fetchHeaders.get("accept")).toContain("text/html");
    expect(fetchHeaders.get("x-mnote-source-channel")).toBe("next_tree_shell_proxy");

    expect(response.status).toBe(200);
    expect(response.headers.get("content-type")).toContain("text/html");
    expect(response.headers.get("cache-control")).toBe("no-store");
    expect(response.headers.get("set-cookie")).toBeNull();
    expect(response.headers.get("connection")).toBeNull();
    expect(response.headers.get("x-upstream")).toBe("mnote-web-tree");
    expect(await response.text()).toContain("tree shell");
  });
});
