import type { DocsExportSnapshot } from "@/lib/drive/docs-export-snapshot"
import { prepareContentForDocxExport } from "@/lib/drive/docs-export-prepare"
import { patchDocxPageSetup } from "@/lib/drive/docx-page-setup-export"
import { patchDocxHeaderFooter } from "@/lib/drive/docx-header-footer-export"
import { patchDocxAnchoredGraphics } from "@/lib/drive/docx-position-export"

export async function exportDocsToDocx(snapshot: DocsExportSnapshot): Promise<Blob> {
  const { content, anchoredGraphics } = await prepareContentForDocxExport(
    snapshot.body,
    snapshot.paragraphStyles
  )

  const { generateDOCX } = await import("@docen/export-docx")
  const generated = await generateDOCX(content, {
    outputType: "uint8array",
    title: snapshot.title,
  })

  let buffer: Uint8Array = generated as Uint8Array

  if (snapshot.pageSetup) {
    buffer = await patchDocxPageSetup(buffer, snapshot.pageSetup)
    buffer = await patchDocxHeaderFooter(buffer, snapshot.pageSetup)
  }

  if (anchoredGraphics.length > 0) {
    buffer = await patchDocxAnchoredGraphics(buffer, anchoredGraphics)
  }

  return new Blob([buffer], {
    type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  })
}
