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/upload-target-preflight route", () => {
  beforeEach(() => {
    mockIsConvexEnabled.mockReturnValue(true);
    mockBuildDocumentBridgeContext.mockReset();
    mockBuildDocumentCommandEnvelope.mockReset();
    mockResolveRustBridgeCommandPlan.mockReset();
    mockDocumentBridgeErrorResponse.mockClear();
  });

  it("应通过 Rust tree.filetree.upload-target.preflight 返回规范化 upload target plan", async () => {
    mockBuildDocumentBridgeContext.mockResolvedValue({
      requestId: "req_filetree_upload_target_1",
      traceId: "trace_filetree_upload_target_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.upload-target.preflight",
      commandId: "cmd_filetree_upload_target_1",
      functionName: "tree:fileTreeUploadTargetPreflight",
      workspaceId: "ws_1",
      requestId: "req_filetree_upload_target_1",
      traceId: "trace_filetree_upload_target_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        fileTreeUploadTargetPlan: {
          workspaceId: "ws_1",
          targetDocumentId: "doc_target",
          targetMindmapId: "mind_1",
          targetSubPath: "mindmaps/mind_1",
        },
      },
    });

    const { POST } = await import("./route");
    const response = await POST(
      new Request("http://127.0.0.1:3000/api/tree/filetree/upload-target-preflight", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          workspaceId: "ws_fallback",
          targetDocumentId: null,
          targetRowId: "asset:asset_child_1",
          focusedRowId: null,
          activeDocumentId: "doc_active",
          rows: [],
          documentWorkspaces: [{ documentId: "doc_target", workspaceId: "ws_1" }],
        }),
      }),
    );

    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({
      requestId: "req_filetree_upload_target_1",
      traceId: "trace_filetree_upload_target_1",
      plan: {
        workspaceId: "ws_1",
        targetDocumentId: "doc_target",
        targetMindmapId: "mind_1",
        targetSubPath: "mindmaps/mind_1",
      },
    });
    expect(mockBuildDocumentCommandEnvelope).toHaveBeenCalledWith(
      expect.objectContaining({
        name: "tree.filetree.upload-target.preflight",
        payload: expect.objectContaining({
          workspaceId: "ws_fallback",
          targetRowId: "asset:asset_child_1",
          activeDocumentId: "doc_active",
        }),
        reason: "filetree-upload-target-preflight tree.filetree.upload-target.preflight",
        refs: ["file-tree-shell"],
      }),
    );
  });
});
