import { PDFDocument } from 'pdf-lib';

/**
 * Result of inspecting a PDF's AcroForm. Used by the Documenso template
 * sync flow to surface what AcroForm fields the operator's uploaded PDF
 * actually has - so the admin can verify their fillable PDF matches the
 * CRM's expected field-label set before any EOI is sent in anger.
 */
export interface AcroFormField {
  name: string;
  /**
   * `getType()` from pdf-lib's PDFField subclasses - usually one of
   * `PDFTextField`, `PDFCheckBox`, `PDFDropdown`, `PDFRadioGroup`,
   * `PDFSignature`, `PDFButton`. Exposed verbatim so the UI can show
   * the admin what each field expects at the AcroForm layer.
   */
  type: string;
}

/**
 * Parses the AcroForm in `pdfBytes` and returns one descriptor per form
 * field. Returns an empty array when the PDF has no AcroForm at all
 * (i.e. a flat / non-fillable PDF). Never throws on a missing form -
 * the caller treats "empty list" as a signal to nudge the operator
 * that their PDF isn't actually fillable.
 */
export async function inspectPdfAcroForm(pdfBytes: Buffer | Uint8Array): Promise<AcroFormField[]> {
  const doc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true });
  const form = doc.getForm();
  const fields = form.getFields();
  return fields.map((f) => ({
    name: f.getName(),
    type: f.constructor.name,
  }));
}
