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

  it("应通过 Rust tree.filetree.delete.preflight 返回规范化 delete plan", async () => {
    mockBuildDocumentBridgeContext.mockResolvedValue({
      requestId: "req_filetree_delete_1",
      traceId: "trace_filetree_delete_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.delete.preflight",
      commandId: "cmd_filetree_delete_1",
      functionName: "tree:fileTreeDeletePreflight",
      workspaceId: "ws_1",
      requestId: "req_filetree_delete_1",
      traceId: "trace_filetree_delete_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        fileTreeDeletePlan: {
          rowIds: ["doc:doc_1", "asset:asset_1"],
          docIds: ["doc_1"],
          assetIds: ["asset_1"],
          assetDocumentIds: ["doc_other"],
        },
      },
    });

    const { POST } = await import("./route");
    const response = await POST(
      new Request("http://127.0.0.1:3000/api/tree/filetree/delete-preflight", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          workspaceId: "ws_1",
          rowIds: ["doc:doc_1", "asset:asset_1"],
          rows: [],
          documentParents: [],
        }),
      }),
    );

    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({
      requestId: "req_filetree_delete_1",
      traceId: "trace_filetree_delete_1",
      plan: {
        rowIds: ["doc:doc_1", "asset:asset_1"],
        docIds: ["doc_1"],
        assetIds: ["asset_1"],
        assetDocumentIds: ["doc_other"],
      },
    });
    expect(mockBuildDocumentCommandEnvelope).toHaveBeenCalledWith(
      expect.objectContaining({
        name: "tree.filetree.delete.preflight",
        payload: expect.objectContaining({
          workspaceId: "ws_1",
          rowIds: ["doc:doc_1", "asset:asset_1"],
        }),
        reason: "filetree-delete-preflight tree.filetree.delete.preflight",
        refs: ["file-tree-shell"],
      }),
    );
  });
});
