import type { Editor } from "@tiptap/react"
import {
  resolveDocumentPageLayout,
  type DocPageLayout,
  type DocPageSetup,
} from "@/lib/drive/doc-page-setup"
import type { DocParagraphStylesCatalog } from "@/lib/drive/docs-paragraph-styles"
import type { PageFormatId } from "@/lib/drive/page-formats"
import type { TipTapJSON } from "@/lib/drive/richtext-import"

export type DocsExportSnapshot = {
  title: string
  sourceName: string
  body: TipTapJSON
  pageSetup: DocPageSetup | null
  pageLayout: DocPageLayout
  paragraphStyles: DocParagraphStylesCatalog
  pageCount: number
  getPageStackElement: () => HTMLElement | null
}

export function buildDocsExportSnapshot(params: {
  editor: Editor | null
  sourceName: string
  title?: string
  pageSetup: DocPageSetup | null
  fallbackFormatId: PageFormatId
  paragraphStyles: DocParagraphStylesCatalog
  pageCount: number
  getPageStackElement: () => HTMLElement | null
}): DocsExportSnapshot | null {
  if (!params.editor) return null
  return {
    title: params.title ?? params.sourceName,
    sourceName: params.sourceName,
    body: params.editor.getJSON() as TipTapJSON,
    pageSetup: params.pageSetup,
    pageLayout: resolveDocumentPageLayout(params.pageSetup, params.fallbackFormatId),
    paragraphStyles: params.paragraphStyles,
    pageCount: Math.max(1, params.pageCount),
    getPageStackElement: params.getPageStackElement,
  }
}
