import { describe, expect, it } from "vitest";
import { buildPageAggregate } from "@/lib/documents/page-aggregate";
import type { PageOptionsState } from "@/types/page-options";

const pageOptions: PageOptionsState = {
  wideLayout: true,
  smallText: false,
  showHeadingNumbers: true,
  showToc: true,
  showStructure: false,
  protectEditing: false,
  showWordCount: true,
  collapseBacklinks: false,
  pageFont: "default",
  layoutDensity: "normal",
  hideChildPages: false,
  showBlockRefCount: false,
  embedDefaultBlockId: null,
};

describe("page-aggregate", () => {
  it("将页面 route 所需真相收口为统一聚合对象", () => {
    const aggregate = buildPageAggregate({
      documentId: "doc_1",
      workspaceId: "ws_1",
      title: " 页面标题 ",
      updatedAt: "2026-04-21T12:00:00.000Z",
      readOnly: true,
      disableDownload: true,
      disableCopy: false,
      pageOptions,
      content: [{ id: "block_1", type: "paragraph", content: [] }],
      revision: 7,
      conflictDetectionKey: "doc_1:7",
      pageSubtree: null,
      stats: {
        wordCount: 10,
        characterCount: 20,
        blockCount: 1,
        todoTotal: 0,
        todoDone: 0,
      },
    });

    expect(aggregate).toEqual({
      identity: {
        documentId: "doc_1",
        workspaceId: "ws_1",
      },
      head: {
        title: "页面标题",
        updatedAt: "2026-04-21T12:00:00.000Z",
        permissions: {
          readOnly: true,
          disableDownload: true,
          disableCopy: false,
        },
      },
      layout: {
        pageOptions,
      },
      body: {
        content: [{ id: "block_1", type: "paragraph", content: [] }],
        revision: 7,
        conflictDetectionKey: "doc_1:7",
      },
      tree: {
        pageSubtree: null,
      },
      stats: {
        wordCount: 10,
        characterCount: 20,
        blockCount: 1,
        todoTotal: 0,
        todoDone: 0,
      },
    });
  });

  it("缺省标题与可选字段时回退到稳定默认值", () => {
    const aggregate = buildPageAggregate({
      documentId: "doc_2",
      workspaceId: "ws_2",
      pageOptions,
      content: null,
    });

    expect(aggregate.head.title).toBe("无标题");
    expect(aggregate.head.permissions).toEqual({
      readOnly: false,
      disableDownload: false,
      disableCopy: false,
    });
    expect(aggregate.body).toEqual({
      content: null,
      revision: null,
      conflictDetectionKey: null,
    });
    expect(aggregate.tree.pageSubtree).toBeNull();
    expect(aggregate.stats).toBeNull();
  });
});
