import type { PageSubtreeProjection } from "@/lib/documents/page-subtree";
import type { DocumentStats, PageOptionsState } from "@/types/page-options";

export interface PageAggregateIdentity {
  documentId: string;
  workspaceId: string;
}

export interface PageAggregatePermissions {
  readOnly: boolean;
  disableDownload: boolean;
  disableCopy: boolean;
}

export interface PageAggregateHead {
  title: string;
  updatedAt: string | null;
  permissions: PageAggregatePermissions;
}

export interface PageAggregateLayout {
  pageOptions: PageOptionsState;
}

export interface PageAggregateBody {
  content: unknown;
  revision: number | null;
  conflictDetectionKey: string | null;
}

export interface PageAggregateTree {
  pageSubtree: PageSubtreeProjection | null;
}

export interface PageAggregateProjection {
  identity: PageAggregateIdentity;
  head: PageAggregateHead;
  layout: PageAggregateLayout;
  body: PageAggregateBody;
  tree: PageAggregateTree;
  stats: DocumentStats | null;
}

export function buildPageAggregate(input: {
  documentId: string;
  workspaceId: string;
  title?: string | null;
  updatedAt?: string | null;
  readOnly?: boolean;
  disableDownload?: boolean;
  disableCopy?: boolean;
  pageOptions: PageOptionsState;
  content: unknown;
  revision?: number | null;
  conflictDetectionKey?: string | null;
  pageSubtree?: PageSubtreeProjection | null;
  stats?: DocumentStats | null;
}): PageAggregateProjection {
  return {
    identity: {
      documentId: input.documentId,
      workspaceId: input.workspaceId,
    },
    head: {
      title: input.title?.trim() || "无标题",
      updatedAt: input.updatedAt ?? null,
      permissions: {
        readOnly: Boolean(input.readOnly),
        disableDownload: Boolean(input.disableDownload),
        disableCopy: Boolean(input.disableCopy),
      },
    },
    layout: {
      pageOptions: input.pageOptions,
    },
    body: {
      content: input.content ?? null,
      revision: input.revision ?? null,
      conflictDetectionKey: input.conflictDetectionKey ?? null,
    },
    tree: {
      pageSubtree: input.pageSubtree ?? null,
    },
    stats: input.stats ?? null,
  };
}
