import { describe, expect, it } from "vitest";
import {
  assertDocumentMoveWriteOperationMatches,
  buildDocumentMoveOrderPlanFromDocuments,
} from "../../../convex/_utils/documentMoveOrder";

describe("documentMoveOrder", () => {
  it("按 Rust canonical move order plan 计算跨父移动和越界 clamp", () => {
    const plan = buildDocumentMoveOrderPlanFromDocuments({
      documents: [
        {
          id: "target",
          parent_id: null,
          sort_order: 0,
          created_at: "2026-04-25T00:00:00Z",
        },
        {
          id: "doc_a",
          parent_id: "source",
          sort_order: 0,
          created_at: "2026-04-25T00:00:01Z",
        },
        {
          id: "doc_b",
          parent_id: "source",
          sort_order: 1,
          created_at: "2026-04-25T00:00:02Z",
        },
        {
          id: "doc_c",
          parent_id: "target",
          sort_order: 0,
          created_at: "2026-04-25T00:00:03Z",
        },
      ],
      documentId: "doc_b",
      parentId: "target",
      sortOrder: -2,
    });

    expect(plan).toEqual({
      documentId: "doc_b",
      fromParentId: "source",
      toParentId: "target",
      requestedSortOrder: -2,
      normalizedSortOrder: 0,
      patches: [
        {
          documentId: "doc_b",
          parentId: "target",
          sortOrder: 0,
          moved: true,
        },
        {
          documentId: "doc_c",
          parentId: "target",
          sortOrder: 1,
          moved: false,
        },
      ],
    });
  });

  it("treeWriteOperation 与当前排序状态不一致时拒绝执行", () => {
    const actual = buildDocumentMoveOrderPlanFromDocuments({
      documents: [
        {
          id: "doc_a",
          parent_id: "source",
          sort_order: 0,
          created_at: "2026-04-25T00:00:01Z",
        },
        {
          id: "doc_b",
          parent_id: "source",
          sort_order: 1,
          created_at: "2026-04-25T00:00:02Z",
        },
        {
          id: "doc_c",
          parent_id: "target",
          sort_order: 0,
          created_at: "2026-04-25T00:00:03Z",
        },
      ],
      documentId: "doc_b",
      parentId: "target",
      sortOrder: 0,
    });

    expect(() =>
      assertDocumentMoveWriteOperationMatches(
        {
          family: "tree",
          schema: "mnote.tree.write_operation",
          schemaVersion: 1,
          operation: "tree.subtree.move.write",
          workspaceId: "ws_1",
          ...actual,
          patches: actual.patches.map((patch) =>
            patch.documentId === "doc_c" ? { ...patch, sortOrder: 9 } : patch,
          ),
        },
        actual,
      ),
    ).toThrow("Rust move write operation 与 Convex 当前排序状态不一致");
  });
});
