import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ConvexHttpClient } from "convex/browser";
import { resolveKernelFileTreeProjection } from "./kernel-file-tree";

const mockBuildDocumentBridgeContextWithActor = vi.fn();
const mockBuildDocumentQueryEnvelope = vi.fn();
const mockExecuteRustBridgeQuery = vi.fn();

vi.mock("@/lib/documents/bridge", () => ({
  buildDocumentBridgeContextWithActor: (...args: unknown[]) =>
    mockBuildDocumentBridgeContextWithActor(...args),
  buildDocumentQueryEnvelope: (...args: unknown[]) => mockBuildDocumentQueryEnvelope(...args),
}));

vi.mock("@/lib/documents/rust-runtime", () => ({
  executeRustBridgeQuery: (...args: unknown[]) => mockExecuteRustBridgeQuery(...args),
}));

describe("resolveKernelFileTreeProjection", () => {
  beforeEach(() => {
    mockBuildDocumentBridgeContextWithActor.mockReset().mockReturnValue({
      requestId: "req_1",
      traceId: "trace_1",
    });
    mockBuildDocumentQueryEnvelope.mockReset().mockImplementation((input) => input);
    mockExecuteRustBridgeQuery.mockReset().mockResolvedValue({
      projectionId: "kernel_projection:file_tree:page_root",
      projection: "file_tree",
      rootNodeId: "page_root",
      items: [],
      edges: [],
    });
  });

  it("把搜索词传入 Rust kernel.project_view，而不是交给宿主裁剪", async () => {
    await resolveKernelFileTreeProjection({
      client: { query: vi.fn() } as unknown as ConvexHttpClient,
      request: new Request("http://127.0.0.1:3000/api/tree/projections/file"),
      workspaceId: "ws_1",
      actor: {
        actorType: "user",
        actorId: "user_1",
        sessionId: null,
      },
      dataset: {
        active_workspace_id: "ws_1",
        documents: [],
      },
      rootNodeId: "page_root",
      depth: 2,
      query: "  预算  ",
      maxResults: 12,
    });

    expect(mockBuildDocumentQueryEnvelope).toHaveBeenCalledWith({
      name: "kernel.project_view",
      payload: expect.objectContaining({
        projection: "file_tree",
        workspaceId: "ws_1",
        rootNodeId: "page_root",
        depth: 2,
        query: "预算",
        maxResults: 12,
      }),
    });
    expect(mockExecuteRustBridgeQuery).toHaveBeenCalledTimes(1);
  });
});
