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

const mockIsConvexEnabled = vi.fn(() => true);
const mockBuildDocumentBridgeContext = vi.fn();
const mockBuildDocumentCommandEnvelope = vi.fn();
const mockResolveRustBridgeCommandPlan = vi.fn();
const mockDocumentBridgeErrorResponse = vi.fn((error: unknown) =>
  Response.json(
    {
      error: error instanceof Error ? error.message : String(error),
    },
    {
      status:
        typeof (error as { status?: unknown })?.status === "number"
          ? ((error as { status: number }).status ?? 500)
          : 500,
    },
  ),
);

vi.mock("@/lib/convex/enabled", () => ({
  isConvexEnabled: () => mockIsConvexEnabled(),
}));

vi.mock("@/lib/documents/bridge", () => ({
  buildDocumentBridgeContext: mockBuildDocumentBridgeContext,
  buildDocumentCommandEnvelope: mockBuildDocumentCommandEnvelope,
  documentBridgeErrorResponse: (...args: Parameters<typeof mockDocumentBridgeErrorResponse>) =>
    mockDocumentBridgeErrorResponse(...args),
}));

vi.mock("@/lib/documents/rust-runtime", () => ({
  resolveRustBridgeCommandPlan: (...args: Parameters<typeof mockResolveRustBridgeCommandPlan>) =>
    mockResolveRustBridgeCommandPlan(...args),
}));

describe("/api/tree/filetree/paste-preflight route", () => {
  beforeEach(() => {
    mockIsConvexEnabled.mockReturnValue(true);
    mockBuildDocumentBridgeContext.mockReset();
    mockBuildDocumentCommandEnvelope.mockReset();
    mockResolveRustBridgeCommandPlan.mockReset();
    mockDocumentBridgeErrorResponse.mockClear();
  });

  it("应通过 Rust tree.filetree.paste.preflight 返回规范化 paste plan", async () => {
    mockBuildDocumentBridgeContext.mockResolvedValue({
      requestId: "req_filetree_paste_1",
      traceId: "trace_filetree_paste_1",
      workspaceId: "ws_1",
      actor: {
        actorType: "user",
        actorId: "user_1",
        sessionId: null,
      },
      source: {
        channel: "next-route",
        client: "wolai-frontend",
      },
      tenantId: null,
      deploymentId: null,
      projectId: null,
      authToken: null,
      idempotencyKey: null,
      validateOnly: true,
      dryRun: true,
    });
    mockBuildDocumentCommandEnvelope.mockImplementation((input: unknown) => input);
    mockResolveRustBridgeCommandPlan.mockResolvedValue({
      kind: "command",
      commandName: "tree.filetree.paste.preflight",
      commandId: "cmd_filetree_paste_1",
      functionName: "tree:fileTreePastePreflight",
      workspaceId: "ws_1",
      requestId: "req_filetree_paste_1",
      traceId: "trace_filetree_paste_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        fileTreePastePlan: {
          targetDocumentId: "doc_target",
          targetMindmapId: "mind_1",
          targetSubPath: "mindmaps/mind_1",
          rowIds: ["index:doc_1", "asset:asset_1"],
          docItems: [{ documentId: "doc_1", recursive: false }],
          copyableAssetIds: ["asset_1"],
          resourceTransferPlan: {
            action: "copy",
            assetIds: ["asset_1"],
            targetDocumentId: "doc_target",
            targetSubPath: "mindmaps/mind_1",
          },
        },
      },
    });

    const { POST } = await import("./route");
    const response = await POST(
      new Request("http://127.0.0.1:3000/api/tree/filetree/paste-preflight", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          workspaceId: "ws_1",
          targetDocumentId: null,
          focusedRowId: "asset-folder:mind_1",
          activeDocumentId: "doc_active",
          rowIds: ["index:doc_1", "asset:asset_1"],
          rows: [],
        }),
      }),
    );

    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({
      requestId: "req_filetree_paste_1",
      traceId: "trace_filetree_paste_1",
      plan: {
        targetDocumentId: "doc_target",
        targetMindmapId: "mind_1",
        targetSubPath: "mindmaps/mind_1",
        rowIds: ["index:doc_1", "asset:asset_1"],
        docItems: [{ documentId: "doc_1", recursive: false }],
        copyableAssetIds: ["asset_1"],
        resourceTransferPlan: {
          action: "copy",
          assetIds: ["asset_1"],
          targetDocumentId: "doc_target",
          targetSubPath: "mindmaps/mind_1",
        },
      },
    });
    expect(mockBuildDocumentCommandEnvelope).toHaveBeenCalledWith(
      expect.objectContaining({
        name: "tree.filetree.paste.preflight",
        payload: expect.objectContaining({
          workspaceId: "ws_1",
          focusedRowId: "asset-folder:mind_1",
          rowIds: ["index:doc_1", "asset:asset_1"],
        }),
        reason: "filetree-paste-preflight tree.filetree.paste.preflight",
        refs: ["file-tree-shell"],
      }),
    );
  });
});
