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

describe("documentMoveOrder Convex helper", () => {
  it("assertDocumentMoveWriteOperationMatches 应只接受 Rust tree write operation，并返回内部 move plan", () => {
    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",
        },
      ],
      documentId: "doc_b",
      parentId: null,
      sortOrder: 0,
    });

    const normalized = assertDocumentMoveWriteOperationMatches(
      {
        family: "tree",
        schema: "mnote.tree.write_operation",
        schemaVersion: 1,
        operation: "tree.subtree.move.write",
        workspaceId: "ws_1",
        documentId: "doc_b",
        fromParentId: "source",
        toParentId: null,
        requestedSortOrder: 0,
        normalizedSortOrder: 0,
        patches: [
          {
            documentId: "doc_b",
            parentId: null,
            sortOrder: 0,
            moved: true,
          },
        ],
      },
      actual,
    );

    expect(normalized).toEqual({
      documentId: "doc_b",
      fromParentId: "source",
      toParentId: null,
      requestedSortOrder: 0,
      normalizedSortOrder: 0,
      patches: [
        {
          documentId: "doc_b",
          parentId: null,
          sortOrder: 0,
          moved: true,
        },
      ],
    });

    expect(() => assertDocumentMoveWriteOperationMatches({ ...actual, operation: "documents.move" }, actual)).toThrow(
      "Rust move write operation 与 Convex 当前排序状态不一致",
    );
  });

  it("assertDocumentMoveWriteOperationMatches 应拒绝缺少正式 write operation 外壳的旧 move plan", () => {
    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",
        },
      ],
      documentId: "doc_b",
      parentId: null,
      sortOrder: 0,
    });

    expect(() => assertDocumentMoveWriteOperationMatches(actual, actual)).toThrow(
      "Rust move write operation 与 Convex 当前排序状态不一致",
    );
  });
});
