import { beforeAll, describe, expect, it, vi } from "vitest";
import type { ConvexHttpClient } from "convex/browser";
import {
  buildRustBridgeCommandArtifactPlan,
  executeRustBridgeMutationTransport,
  materializeRustTreeStreamDelta,
  readRustTreeDomainEventPlan,
  readRustTreeDomainEventPlans,
  readRustTreeDomainEventType,
  resolveRustRuntimeProcessEnv,
  type RustBridgeCommandPlan,
} from "./rust-runtime";

vi.mock("@/lib/convex/api", () => ({
  api: {
    documents: {
      move: "documents.move",
      copyTree: "documents.copyTree",
      updateStats: "documents.updateStats",
    },
    mediaAssets: {
      batchCopy: "mediaAssets.batchCopy",
      batchMove: "mediaAssets.batchMove",
    },
    mindmaps: {
      get: "mindmaps.get",
      put: "mindmaps.put",
      applyCommand: "mindmaps.applyCommand",
    },
  },
}));

vi.mock("@/lib/documents/bridge", () => ({
  DocumentBridgeError: class DocumentBridgeError extends Error {
    status: number;
    code: string;
    details?: unknown;

    constructor(message: string, status: number, code: string, details?: unknown) {
      super(message);
      this.name = "DocumentBridgeError";
      this.status = status;
      this.code = code;
      this.details = details;
    }
  },
}));

let runtimeSelection: Record<string, unknown> = {};

beforeAll(async () => {
  try {
    runtimeSelection = (await import("@/lib/documents/rust-runtime-selection")) as Record<string, unknown>;
  } catch {
    runtimeSelection = {};
  }
});

describe("shouldUseBuiltBridgeRuntimeBinary", () => {
  it("当源码比已编译二进制更新时应放弃旧二进制", () => {
    const decide = runtimeSelection.shouldUseBuiltBridgeRuntimeBinary;
    expect(typeof decide).toBe("function");
    if (typeof decide !== "function") {
      return;
    }

    expect(
      decide({
        builtBinaryMtimeMs: 100,
        latestSourceMtimeMs: 200,
      }),
    ).toBe(false);
  });

  it("当二进制不旧于源码时仍可直接复用", () => {
    const decide = runtimeSelection.shouldUseBuiltBridgeRuntimeBinary;
    expect(typeof decide).toBe("function");
    if (typeof decide !== "function") {
      return;
    }

    expect(
      decide({
        builtBinaryMtimeMs: 300,
        latestSourceMtimeMs: 200,
      }),
    ).toBe(true);
  });
});

describe("resolveRustRuntimeProcessEnv", () => {
  it("未设置默认 toolchain 时应注入仓库声明的 Rust toolchain", () => {
    expect(resolveRustRuntimeProcessEnv({} as NodeJS.ProcessEnv)).toMatchObject({
      CARGO_TERM_COLOR: "never",
      RUSTUP_TOOLCHAIN: "1.89.0",
    });
  });

  it("应保留调用方显式设置的 Rust toolchain", () => {
    expect(
      resolveRustRuntimeProcessEnv({
        RUSTUP_TOOLCHAIN: "nightly",
      } as unknown as NodeJS.ProcessEnv),
    ).toMatchObject({
      CARGO_TERM_COLOR: "never",
      RUSTUP_TOOLCHAIN: "nightly",
    });
  });
});

describe("executeRustBridgeQueryTransport", () => {
  it("mindmap.projection.get transport 包装为 Rust projection 合同", async () => {
    const { executeRustBridgeQueryTransport } = await import("./rust-runtime");
    const query = vi.fn().mockResolvedValue({
      data: {
        data: { uid: "root", text: "Rust 导图" },
        children: [{ data: { uid: "child", text: "分支主题" }, children: [] }],
      },
      meta: { updated_at: "2026-05-10T00:00:00.000Z" },
    });

    const result = await executeRustBridgeQueryTransport({
      client: { query } as unknown as ConvexHttpClient,
      plan: {
        kind: "query",
        queryName: "mindmap.projection.get",
        functionName: "mindmaps:getProjection",
        workspaceId: "ws_1",
        requestId: "req_1",
        traceId: "trace_1",
        actorId: "user_1",
        payloadJson: "{}",
        argsJson: {
          docId: "doc_1",
          mindmapId: "mind_1",
        },
      },
    });

    expect(query).toHaveBeenCalledWith("mindmaps.get", {
      docId: "doc_1",
      mindmapId: "mind_1",
    });
    expect(result).toMatchObject({
      schema: "mnote.mindmap_projection.v1",
      projection: "mindmap_subtree",
      source: "rust-kernel",
      owner: "rust-kernel",
      documentId: "doc_1",
      mindmapId: "mind_1",
      title: "Rust 导图",
      nodeCount: 2,
      meta: {
        requestId: "req_1",
        traceId: "trace_1",
        workspaceId: "ws_1",
        updatedAt: "2026-05-10T00:00:00.000Z",
      },
    });
  });

  it("mindmap.simple_mind_map_scene.get transport 包装为 simple-mind-map adapter projection", async () => {
    const { executeRustBridgeQueryTransport } = await import("./rust-runtime");
    const query = vi.fn().mockResolvedValue({
      data: {
        data: { uid: "root", text: "KMIND" },
        children: [{ data: { uid: "topic", text: "二级节点" }, children: [] }],
      },
      meta: { updated_at: "2026-05-10T00:00:00.000Z" },
    });

    const result = await executeRustBridgeQueryTransport({
      client: { query } as unknown as ConvexHttpClient,
      plan: {
        kind: "query",
        queryName: "mindmap.simple_mind_map_scene.get",
        functionName: "mindmaps:getProjection",
        workspaceId: "ws_1",
        requestId: "req_1",
        traceId: "trace_1",
        actorId: "user_1",
        payloadJson: "{}",
        argsJson: {
          docId: "doc_1",
          mindmapId: "mind_1",
        },
      },
    });

    expect(query).toHaveBeenCalledWith("mindmaps.get", {
      docId: "doc_1",
      mindmapId: "mind_1",
    });
    expect(result).toMatchObject({
      schema: "mnote.mindmap.simple_mind_map_scene.v1",
      runtime: "simple-mind-map",
      source: "rust-kernel",
      owner: "rust-kernel",
      documentId: "doc_1",
      mindmapId: "mind_1",
      rootNodeId: "root",
      kernelRevision: 1,
      meta: {
        requestId: "req_1",
        traceId: "trace_1",
        workspaceId: "ws_1",
        updatedAt: "2026-05-10T00:00:00.000Z",
      },
    });
    expect((result as { root?: { data?: { text?: string } } }).root?.data?.text).toBe("KMIND");
  });

  it("mindmap.editor_scene.get transport 包装为 Rust editor scene 合同", async () => {
    const { executeRustBridgeQueryTransport } = await import("./rust-runtime");
    const query = vi.fn().mockResolvedValue({
      data: {
        data: { uid: "root", text: "KMIND" },
        children: [
          {
            data: { uid: "topic", text: "二级节点" },
            children: [
              { data: { uid: "branch-1", text: "分支主题" }, children: [] },
              { data: { uid: "branch-2", text: "分支主题" }, children: [] },
            ],
          },
        ],
      },
      meta: { updated_at: "2026-05-10T00:00:00.000Z" },
    });

    const result = await executeRustBridgeQueryTransport({
      client: { query } as unknown as ConvexHttpClient,
      plan: {
        kind: "query",
        queryName: "mindmap.editor_scene.get",
        functionName: "mindmaps:getEditorScene",
        workspaceId: "ws_1",
        requestId: "req_1",
        traceId: "trace_1",
        actorId: "user_1",
        payloadJson: "{}",
        argsJson: {
          docId: "doc_1",
          mindmapId: "mind_1",
          rootNodeId: "root",
        },
      },
    });

    expect(query).toHaveBeenCalledWith("mindmaps.get", {
      docId: "doc_1",
      mindmapId: "mind_1",
    });
    expect(result).toMatchObject({
      schema: "mnote.mindmap_editor_scene.v1",
      source: "rust-kernel",
      documentId: "doc_1",
      mindmapId: "mind_1",
      rootNodeId: "root",
      capabilities: {
        canEditText: true,
        canAddChild: true,
        canAddSiblingAfter: true,
        canDeleteNode: true,
      },
    });
    expect((result as { nodes?: unknown[] }).nodes).toHaveLength(4);
    expect((result as { edges?: unknown[] }).edges).toHaveLength(3);
  });
});

describe("executeRustBridgeMutationTransport", () => {
  it("mindmap.command.apply 应注册为 mindmaps.applyCommand transport", async () => {
    const mutation = vi.fn().mockResolvedValue({
      ok: true,
      applied: 1,
      errors: [],
      workspace_id: "ws_1",
      document_id: "doc_1",
      mindmap_id: "mind_1",
      updated_at: "2026-05-10T00:00:00.000Z",
    });
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "mindmap.command.apply",
      commandId: "cmd_mindmap_apply",
      functionName: "mindmaps:applyCommand",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: "idem_1",
      payloadJson: "{}",
      argsJson: {
        documentId: "doc_1",
        mindmapId: "mind_1",
        commands: [
          { type: "renameNode", mapId: "mind_1", nodeId: "root", title: "新标题" },
        ],
        canonicalCommand: "mindmap.command.apply",
      },
    };

    await executeRustBridgeMutationTransport({
      client: { mutation } as unknown as ConvexHttpClient,
      plan,
    });

    expect(mutation).not.toHaveBeenCalledWith("mindmaps.put", expect.anything());
    expect(mutation).toHaveBeenCalledWith("mindmaps.applyCommand", {
      docId: "doc_1",
      mindmapId: "mind_1",
      commands: [
        { type: "renameNode", mapId: "mind_1", nodeId: "root", title: "新标题" },
      ],
    });
  });

  it("documents.move 应把 Rust treeWriteOperation 透传给 Convex 写执行器", async () => {
    const movePlan = {
      documentId: "doc_b",
      fromParentId: "source",
      toParentId: "target",
      requestedSortOrder: 0,
      normalizedSortOrder: 0,
      patches: [
        {
          documentId: "doc_b",
          parentId: "target",
          sortOrder: 0,
          moved: true,
        },
      ],
    };
    const treeWriteOperation = {
      family: "tree",
      schema: "mnote.tree.write_operation",
      schemaVersion: 1,
      operation: "tree.subtree.move.write",
      workspaceId: "ws_1",
      ...movePlan,
    };
    const mutation = vi.fn().mockResolvedValue({ ok: true });
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "tree.subtree.move",
      commandId: "cmd_move",
      functionName: "documents:move",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: "idem_1",
      payloadJson: "{}",
      argsJson: {
        id: "doc_b",
        parentId: "target",
        sortOrder: 0,
        treeWriteOperation,
      },
    };

    await executeRustBridgeMutationTransport({
      client: { mutation } as unknown as ConvexHttpClient,
      plan,
    });

    expect(mutation).toHaveBeenCalledTimes(1);
    expect(mutation.mock.calls[0]?.[1]).toMatchObject({
      id: "doc_b",
      parentId: "target",
      sortOrder: 0,
      treeWriteOperation,
    });
  });

  it("documents.copyTree 应注册为 Rust tree.subtree.copy 的 transport", async () => {
    const mutation = vi.fn().mockResolvedValue({ items: [] });
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "tree.subtree.copy",
      commandId: "cmd_copy",
      functionName: "documents:copyTree",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: "idem_1",
      payloadJson: "{}",
      argsJson: {
        targetParentId: "parent_1",
        items: [
          {
            documentId: "doc_1",
            recursive: true,
          },
        ],
      },
    };

    await executeRustBridgeMutationTransport({
      client: { mutation } as unknown as ConvexHttpClient,
      plan,
    });

    expect(mutation).toHaveBeenCalledWith("documents.copyTree", {
      targetParentId: "parent_1",
      items: [
        {
          documentId: "doc_1",
          recursive: true,
        },
      ],
    });
  });

  it("documents.updateStats 应注册为 Rust metadata transport", async () => {
    const mutation = vi.fn().mockResolvedValue({
      ok: true,
      updated_at: "2026-04-26T00:00:00.000Z",
    });
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "documents.stats.update",
      commandId: "cmd_stats",
      functionName: "documents:updateStats",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: "idem_1",
      payloadJson: "{}",
      argsJson: {
        id: "doc_1",
        wordCount: 12,
        characterCount: 34,
        blockCount: 5,
        todoTotal: 6,
        todoDone: 2,
      },
    };

    await executeRustBridgeMutationTransport({
      client: { mutation } as unknown as ConvexHttpClient,
      plan,
    });

    expect(mutation).toHaveBeenCalledWith("documents.updateStats", {
      id: "doc_1",
      wordCount: 12,
      characterCount: 34,
      blockCount: 5,
      todoTotal: 6,
      todoDone: 2,
    });
  });

  it("tree.resource.copy/move 应把 Rust resourceTransferPlan 透传给媒体 transport", async () => {
    const mutation = vi.fn().mockResolvedValue({ items: [] });
    const basePlan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "tree.resource.copy",
      commandId: "cmd_asset_copy",
      functionName: "mediaAssets:batchCopy",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: "idem_1",
      payloadJson: "{}",
      argsJson: {
        assetIds: ["asset_1", "asset_2"],
        targetDocumentId: "doc_target",
        targetSubPath: "mindmaps/mind_1",
        resourceTransferPlan: {
          action: "copy",
          assetIds: ["asset_1", "asset_2"],
          targetDocumentId: "doc_target",
          targetSubPath: "mindmaps/mind_1",
        },
      },
    };

    await executeRustBridgeMutationTransport({
      client: { mutation } as unknown as ConvexHttpClient,
      plan: basePlan,
    });

    await executeRustBridgeMutationTransport({
      client: { mutation } as unknown as ConvexHttpClient,
      plan: {
        ...basePlan,
        commandName: "tree.resource.move",
        commandId: "cmd_asset_move",
        functionName: "mediaAssets:batchMove",
        argsJson: {
          ...basePlan.argsJson,
          resourceTransferPlan: {
            action: "move",
            assetIds: ["asset_1", "asset_2"],
            targetDocumentId: "doc_target",
            targetSubPath: "mindmaps/mind_1",
          },
        },
      },
    });

    expect(mutation).toHaveBeenNthCalledWith(1, "mediaAssets.batchCopy", {
      userId: "user_1",
      assetIds: ["asset_1", "asset_2"],
      targetDocumentId: "doc_target",
      targetSubPath: "mindmaps/mind_1",
      resourceTransferPlan: {
        action: "copy",
        assetIds: ["asset_1", "asset_2"],
        targetDocumentId: "doc_target",
        targetSubPath: "mindmaps/mind_1",
      },
    });
    expect(mutation).toHaveBeenNthCalledWith(2, "mediaAssets.batchMove", {
      userId: "user_1",
      assetIds: ["asset_1", "asset_2"],
      targetDocumentId: "doc_target",
      targetSubPath: "mindmaps/mind_1",
      resourceTransferPlan: {
        action: "move",
        assetIds: ["asset_1", "asset_2"],
        targetDocumentId: "doc_target",
        targetSubPath: "mindmaps/mind_1",
      },
    });
  });
});

describe("materializeRustTreeStreamDelta", () => {
  it("应把 Rust noop hint 物化为 noop delta", () => {
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "page.body.save",
      commandId: "cmd_save",
      functionName: "documents:updateContent",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        streamDeltaHint: {
          family: "tree",
          kind: "noop",
          args: {},
        },
      },
    };

    expect(
      materializeRustTreeStreamDelta({
        plan,
        result: {
          revision: 8,
          conflict_detection_key: "doc_1:8",
        },
      }),
    ).toEqual({
      op: "noop",
    });
  });

  it("应把 Rust resync_required hint 物化为保守 resync delta", () => {
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "page.body.save",
      commandId: "cmd_save",
      functionName: "documents:updateContent",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        streamDeltaHint: {
          family: "tree",
          kind: "resync_required",
          args: {
            reason: "page_body_saved",
            pageId: "doc_1",
          },
        },
      },
    };

    expect(
      materializeRustTreeStreamDelta({
        plan,
        result: {
          revision: 8,
          conflict_detection_key: "doc_1:8",
        },
      }),
    ).toEqual({
      op: "resync_required",
      reason: "page_body_saved",
      pageId: "doc_1",
    });
  });

  it("应按 Rust move_document hint 与 mutation canonical 结果生成细粒度 delta", () => {
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "tree.subtree.move",
      commandId: "cmd_move",
      functionName: "documents:move",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        streamDeltaHint: {
          family: "tree",
          kind: "move_document",
          args: {
            documentId: "doc_1",
            parentId: "parent_requested",
            sortOrder: 9,
          },
        },
      },
    };

    expect(
      materializeRustTreeStreamDelta({
        plan,
        result: {
          parent_id: "parent_actual",
          sort_order: 2,
          updated_at: "2026-04-26T00:00:00Z",
        },
      }),
    ).toEqual({
      op: "move_document",
      documentId: "doc_1",
      parentId: "parent_actual",
      sortOrder: 2,
      updatedAt: "2026-04-26T00:00:00Z",
    });
  });

  it("应按 Rust copy_result hint 从结果 items 中生成 upsert_documents delta", () => {
    const document = {
      id: "copy_1",
      workspace_id: "ws_1",
      title: "复制页面",
      parent_id: "parent_1",
      sort_order: 0,
      is_starred: false,
      access_scope: "private",
      is_template: false,
      created_at: "2026-04-26T00:00:00Z",
      updated_at: "2026-04-26T00:00:00Z",
    };
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "tree.subtree.copy",
      commandId: "cmd_copy",
      functionName: "documents:copyTree",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        streamDeltaHint: {
          family: "tree",
          kind: "copy_result",
          args: {
            itemsField: "items",
            documentField: "document",
          },
        },
      },
    };

    expect(
      materializeRustTreeStreamDelta({
        plan,
        result: {
          items: [
            {
              oldId: "doc_1",
              newId: "copy_1",
              document,
            },
          ],
        },
      }),
    ).toEqual({
      op: "upsert_documents",
      upsertDocuments: [document],
    });
  });

  it("应按 Rust result_document hint 从根结果生成 upsert_document delta", () => {
    const document = {
      id: "copy_2",
      workspace_id: "ws_1",
      title: "复制页面 2",
      parent_id: "parent_1",
      sort_order: 1,
      is_starred: false,
      access_scope: "private",
      is_template: false,
      created_at: "2026-04-26T00:00:00Z",
      updated_at: "2026-04-26T00:00:00Z",
    };
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "documents.duplicate",
      commandId: "cmd_duplicate",
      functionName: "documents:duplicateWithMindmaps",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        streamDeltaHint: {
          family: "tree",
          kind: "result_document",
          args: {},
        },
      },
    };

    expect(
      materializeRustTreeStreamDelta({
        plan,
        result: document,
      }),
    ).toEqual({
      op: "upsert_document",
      document,
    });
  });

  it("应按 Rust asset_result hint 从结果 items 中生成 upsert_assets delta", () => {
    const asset = {
      id: "asset_1",
      workspace_id: "ws_1",
      document_id: "doc_target",
      asset_type: "file",
      file_url: "/file.pdf",
      thumbnail_url: "/file.pdf",
      file_name: "file.pdf",
      file_size: 1024,
      mime_type: "application/pdf",
      ocr_text: null,
      ocr_status: null,
      created_at: "2026-04-26T00:00:00Z",
      updated_at: "2026-04-26T00:00:00Z",
    };
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "tree.resource.move",
      commandId: "cmd_asset_move",
      functionName: "mediaAssets:batchMove",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        streamDeltaHint: {
          family: "tree",
          kind: "asset_result",
          args: {
            itemsField: "items",
          },
        },
      },
    };

    expect(
      materializeRustTreeStreamDelta({
        plan,
        result: {
          items: [asset],
        },
      }),
    ).toEqual({
      op: "upsert_assets",
      upsertAssets: [asset],
    });
  });
});

describe("readRustTreeDomainEventType", () => {
  it("应从 Rust domainEventHint 读取正式树域 event type", () => {
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "tree.node.archive",
      commandId: "cmd_archive",
      functionName: "documents:softDelete",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        domainEventHint: {
          family: "tree",
          eventType: "tree.node.archived",
        },
      },
    };

    expect(readRustTreeDomainEventType(plan)).toBe("tree.node.archived");
  });

  it("应优先读取 Rust domainEventPlan 作为正式树域事件计划", () => {
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "tree.subtree.move",
      commandId: "cmd_move",
      functionName: "documents:move",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        domainEventPlan: {
          family: "tree",
          schema: "mnote.tree.domain_event",
          schemaVersion: 1,
          eventType: "tree.subtree.moved",
          streamDeltaHint: {
            family: "tree",
            kind: "move_document",
            args: {
              documentId: "doc_1",
              parentId: "parent_1",
              sortOrder: 0,
            },
          },
        },
        domainEventHint: {
          family: "tree",
          eventType: "legacy.should_not_win",
        },
      },
    };

    expect(readRustTreeDomainEventType(plan)).toBe("tree.subtree.moved");
    expect(readRustTreeDomainEventPlan(plan)).toEqual({
      family: "tree",
      schema: "mnote.tree.domain_event",
      schemaVersion: 1,
      eventType: "tree.subtree.moved",
      streamDeltaHint: {
        family: "tree",
        kind: "move_document",
        args: {
          documentId: "doc_1",
          parentId: "parent_1",
          sortOrder: 0,
        },
      },
    });
  });

  it("应保留 Rust formal domainEventPlan payload schema，并拆出 snapshot 独立事件", () => {
    const plan: RustBridgeCommandPlan = {
      kind: "command",
      commandName: "page.body.save",
      commandId: "cmd_save",
      functionName: "documents:updateContent",
      workspaceId: "ws_1",
      requestId: "req_1",
      traceId: "trace_1",
      actorId: "user_1",
      idempotencyKey: null,
      payloadJson: "{}",
      argsJson: {
        domainEventPlan: {
          family: "tree",
          schema: "mnote.tree.domain_event",
          schemaVersion: 1,
          eventType: "page.body.saved",
          payload: {
            page: {
              id: "doc_1",
              workspaceId: "ws_1",
            },
            blocks: {
              ids: ["block_1"],
              count: 1,
            },
          },
          streamDeltaHint: {
            family: "tree",
            kind: "resync_required",
            args: {
              reason: "page_body_saved",
              pageId: "doc_1",
            },
          },
        },
        domainEventPlans: [
          {
            family: "tree",
            schema: "mnote.tree.domain_event",
            schemaVersion: 1,
            eventType: "page.body.saved",
            payload: {
              page: {
                id: "doc_1",
                workspaceId: "ws_1",
              },
              blocks: {
                ids: ["block_1"],
                count: 1,
              },
            },
            streamDeltaHint: {
              family: "tree",
              kind: "resync_required",
              args: {
                reason: "page_body_saved",
                pageId: "doc_1",
              },
            },
          },
          {
            family: "tree",
            schema: "mnote.tree.domain_event",
            schemaVersion: 1,
            eventType: "document.snapshot.saved",
            payload: {
              page: {
                id: "doc_1",
                workspaceId: "ws_1",
              },
              snapshot: {
                version: 8,
                contentHash: "fnv1a64:d039f8f3496411e8",
                updatedAt: null,
              },
            },
            streamDeltaHint: {
              family: "tree",
              kind: "resync_required",
              args: {
                reason: "page_body_saved",
                pageId: "doc_1",
              },
            },
          },
        ],
      },
    };

    expect(readRustTreeDomainEventPlan(plan)).toEqual({
      family: "tree",
      schema: "mnote.tree.domain_event",
      schemaVersion: 1,
      eventType: "page.body.saved",
      payload: {
        page: {
          id: "doc_1",
          workspaceId: "ws_1",
        },
        blocks: {
          ids: ["block_1"],
          count: 1,
        },
      },
      streamDeltaHint: {
        family: "tree",
        kind: "resync_required",
        args: {
          reason: "page_body_saved",
          pageId: "doc_1",
        },
      },
    });
    expect(readRustTreeDomainEventPlans(plan).map((eventPlan) => eventPlan.eventType)).toEqual([
      "page.body.saved",
      "document.snapshot.saved",
    ]);
    expect(readRustTreeDomainEventPlans(plan)[0]?.payload).not.toHaveProperty("snapshot");
    expect(readRustTreeDomainEventPlans(plan)[1]?.payload).toMatchObject({
      page: {
        id: "doc_1",
        workspaceId: "ws_1",
      },
      snapshot: {
        version: 8,
        contentHash: "fnv1a64:d039f8f3496411e8",
        updatedAt: null,
      },
    });
  });
});

describe("buildRustBridgeCommandArtifactPlan", () => {
  it("应通过 Rust runtime commandArtifact 输入生成 artifact plan", async () => {
    const artifactPlan = await buildRustBridgeCommandArtifactPlan({
      context: {
        deploymentId: null,
        projectId: null,
        workspaceId: "ws_1",
        requestId: "req_artifact_1",
        traceId: "trace_artifact_1",
        actor: {
          actorType: "user",
          actorId: "user_1",
          sessionId: null,
        },
        source: {
          channel: "next-route",
          client: "vitest",
        },
        tenantId: null,
        authToken: null,
        idempotencyKey: "idem_1",
        validateOnly: false,
        dryRun: false,
      },
      envelope: {
        name: "tree.subtree.move",
        commandId: "cmd_artifact_1",
        idempotencyKey: "idem_1",
        actor: {
          actorType: "user",
          actorId: "user_1",
          sessionId: null,
        },
        source: {
          channel: "next-route",
          client: "vitest",
        },
        target: {
          workspaceId: "ws_1",
          pageId: "doc_1",
        },
        payload: {
          documentId: "doc_1",
          parentId: "parent_1",
          sortOrder: 0,
        },
        preflightData: null,
        reason: "test",
        refs: ["test"],
        dryRun: false,
        validateOnly: false,
      },
      plan: {
        kind: "command",
        commandName: "tree.subtree.move",
        commandId: "cmd_artifact_1",
        functionName: "documents:move",
        workspaceId: "ws_1",
        requestId: "req_artifact_1",
        traceId: "trace_artifact_1",
        actorId: "user_1",
        idempotencyKey: "idem_1",
        source: {
          channel: "next-route",
          client: "vitest",
        },
        payloadJson: "{}",
        argsJson: {
          domainEventPlan: {
            family: "tree",
            schema: "mnote.tree.domain_event",
            schemaVersion: 1,
            eventType: "page.body.saved",
            payload: {
              page: {
                id: "doc_1",
                workspaceId: "ws_1",
              },
              blocks: {
                ids: ["block_1"],
                count: 1,
              },
            },
            streamDeltaHint: {
              family: "tree",
              kind: "resync_required",
              args: {
                reason: "page_body_saved",
                pageId: "doc_1",
              },
            },
          },
          domainEventPlans: [
            {
              family: "tree",
              schema: "mnote.tree.domain_event",
              schemaVersion: 1,
              eventType: "page.body.saved",
              payload: {
                page: {
                  id: "doc_1",
                  workspaceId: "ws_1",
                },
                blocks: {
                  ids: ["block_1"],
                  count: 1,
                },
              },
              streamDeltaHint: {
                family: "tree",
                kind: "resync_required",
                args: {
                  reason: "page_body_saved",
                  pageId: "doc_1",
                },
              },
            },
            {
              family: "tree",
              schema: "mnote.tree.domain_event",
              schemaVersion: 1,
              eventType: "document.snapshot.saved",
              payload: {
                page: {
                  id: "doc_1",
                  workspaceId: "ws_1",
                },
                snapshot: {
                  version: 8,
                  contentHash: "fnv1a64:d039f8f3496411e8",
                  updatedAt: null,
                },
              },
              streamDeltaHint: {
                family: "tree",
                kind: "resync_required",
                args: {
                  reason: "page_body_saved",
                  pageId: "doc_1",
                },
              },
            },
          ],
        },
      },
      result: {
        parent_id: "parent_1",
        sort_order: 2,
        updated_at: "2026-04-26T10:00:00Z",
      },
      now: "2026-04-26T10:00:01Z",
    });

    expect(artifactPlan?.commandLog).toMatchObject({
      id: "clog_cmd_artifact_1",
      workspaceId: "ws_1",
      commandName: "tree.subtree.move",
      payload: {
        documentId: "doc_1",
        parentId: "parent_1",
        sortOrder: 0,
        streamDelta: {
          op: "resync_required",
          reason: "page_body_saved",
          pageId: "doc_1",
        },
      },
    });
    expect(artifactPlan?.commandLog.commandId).toBe("cmd_artifact_1");
    expect(artifactPlan?.domainEvent?.commandId).toBe("cmd_artifact_1");
    expect(artifactPlan?.domainEvents?.map((event) => event.eventType)).toEqual([
      "page.body.saved",
      "document.snapshot.saved",
    ]);
    expect(artifactPlan?.domainEvent).toMatchObject({
      id: "evt_cmd_artifact_1",
      eventType: "page.body.saved",
      payload: {
        schema: "mnote.tree.domain_event",
        schemaVersion: 1,
        eventType: "page.body.saved",
        command_id: "cmd_artifact_1",
        page: {
          id: "doc_1",
          workspaceId: "ws_1",
        },
        blocks: {
          ids: ["block_1"],
          count: 1,
        },
        streamDelta: {
          op: "resync_required",
          reason: "page_body_saved",
          pageId: "doc_1",
        },
      },
    });
    expect(artifactPlan?.domainEvent?.payload).not.toHaveProperty("snapshot");
    expect(artifactPlan?.domainEvents?.[1]).toMatchObject({
      id: "evt_cmd_artifact_1_02_document_snapshot_saved",
      eventType: "document.snapshot.saved",
      payload: {
        schema: "mnote.tree.domain_event",
        schemaVersion: 1,
        eventType: "document.snapshot.saved",
        command_id: "cmd_artifact_1",
        page: {
          id: "doc_1",
          workspaceId: "ws_1",
        },
        snapshot: {
          version: 8,
          contentHash: "fnv1a64:d039f8f3496411e8",
          updatedAt: null,
        },
        streamDelta: {
          op: "resync_required",
          reason: "page_body_saved",
          pageId: "doc_1",
        },
      },
    });
  }, 30_000);
});
