import {
  blocksFromTiptapDoc,
  editorBlockDocumentFromContent,
  editorBlockDocumentFromTiptapDoc,
  tiptapDocFromBlocks,
  tiptapDocFromEditorBlockDocument,
} from "@/lib/documents/tiptap-content-converter";
import { describe, expect, it } from "vitest";

describe("tiptap-content-converter", () => {
  it("keeps empty content editable", () => {
    expect(tiptapDocFromBlocks([])).toEqual({
      type: "doc",
      content: [{ type: "paragraph", attrs: {}, content: [] }],
    });
    expect(blocksFromTiptapDoc({ type: "doc", content: [] })).toEqual([]);
  });

  it("preserves stable block ids through paragraph round-trip", () => {
    const blocks = [{ id: "p1", type: "paragraph", content: "你好，世界" }];
    expect(blocksFromTiptapDoc(tiptapDocFromBlocks(blocks as never))).toEqual([
      { id: "p1", type: "paragraph", props: undefined, content: "你好，世界" },
    ]);
  });

  it("round-trips p0.5 block families through editor block document", () => {
    const document = editorBlockDocumentFromContent([
      { id: "p1", type: "paragraph", content: "段落" },
      { id: "h1", type: "heading", props: { level: 2 }, content: "标题" },
      { id: "b1", type: "bullet_list_item", content: "项目" },
      { id: "n1", type: "numbered_list_item", content: "序号" },
      { id: "t1", type: "todo", props: { checked: true }, content: "待办" },
      { id: "q1", type: "quote", content: "引用" },
      { id: "c1", type: "code_block", props: { language: "ts" }, content: "const x = 1" },
    ] as never);

    const tiptapDoc = tiptapDocFromEditorBlockDocument(document);
    const roundTrip = editorBlockDocumentFromTiptapDoc(tiptapDoc, "doc-1");

    expect(roundTrip.rootBlockIds).toEqual(["p1", "h1", "b1", "n1", "t1", "q1", "c1"]);
    expect(roundTrip.blocks.map((block) => [block.blockId, block.blockType])).toEqual([
      ["p1", "paragraph"],
      ["h1", "heading"],
      ["b1", "bullet_list_item"],
      ["n1", "numbered_list_item"],
      ["t1", "todo"],
      ["q1", "quote"],
      ["c1", "code_block"],
    ]);
    expect(roundTrip.blocks[1].props?.headingLevel).toBe(2);
    expect(roundTrip.blocks[4].props?.checked).toBe(true);
    expect(roundTrip.blocks[6].props?.language).toBe("ts");
  });
});
