import { PDFDocument, PDFTextField } from "pdf-lib";

export async function loadPdfForm(path: string) {
  const pdfDoc = await loadPdf(path);
  const form = pdfDoc.getForm();
  return form;
}

export async function loadPdf(path: string) {
  const pdfBytes = await Deno.readFile(path);
  const pdfDoc = await PDFDocument.load(pdfBytes);
  return pdfDoc;
}

export async function savePdf(doc: PDFDocument, path: string) {
  doc.getForm().getFields().forEach((field) => {
    if (field instanceof PDFTextField) {
      field.disableRichFormatting?.();
    }
  });
  const pdfBytes = await doc.save({ updateFieldAppearances: true });
  if (Deno.env.get("DRYRUN") || path.includes("dryrun")) return;
  await Deno.writeFile(path, pdfBytes);
}
