import { apiClient } from '../api/client';

/**
 * Filled `template_application_form.docx` (docxtpl) from the same
 * `officialBieuMau` object as the Review tab export.
 */
export function fetchApplicationFormDocxPreview(
  officialBieuMau: Record<string, unknown>,
): Promise<ArrayBuffer> {
  return apiClient.postArrayBuffer('/api/v1/docx/preview-application-form', {
    officialBieuMau,
  });
}

/**
 * Same filled template as {@link fetchApplicationFormDocxPreview}, converted server-side
 * with LibreOffice so the PDF layout matches the Word export (for signing / printing).
 */
export function fetchApplicationFormOfficialPdf(
  officialBieuMau: Record<string, unknown>,
): Promise<ArrayBuffer> {
  return apiClient.postArrayBuffer(
    '/api/v1/docx/preview-application-form-pdf',
    { officialBieuMau },
    { timeout: 180_000 },
  );
}

/** Upload an existing `.docx` and convert to PDF on server via LibreOffice. */
export type DocxServerPdfFixOptions = {
  relaxJustifiedSoftBreaks?: boolean;
  stripTableRowHeights?: boolean;
};

/** Upload an existing `.docx` and convert to PDF on server via LibreOffice. */
export function convertUploadedDocxToOfficialPdf(
  file: File,
  options: DocxServerPdfFixOptions = {},
): Promise<ArrayBuffer> {
  const { relaxJustifiedSoftBreaks = true, stripTableRowHeights = false } = options;
  const formData = new FormData();
  formData.append('file', file, file.name);
  formData.append('relax_justified_softbreaks', String(relaxJustifiedSoftBreaks));
  formData.append('strip_table_row_heights', String(stripTableRowHeights));
  return apiClient.postArrayBuffer('/api/v1/docx/convert-pdf', formData, {
    timeout: 180_000,
  });
}
