import { PDFDocument } from 'pdf-lib';
import { ImageUtils } from '../../../shared/utilities/image-utils';

/**
 * Builds a single merged PDF from a list of paper-proof attachments (mostly phone photos).
 *
 * - Images are compressed in the browser (resized + re-encoded as JPEG) so the upload stays
 *   small — phone photos are 12MP+ and would otherwise be huge. One image per page.
 * - Files that are already PDFs are merged through page-by-page, unchanged.
 * - Other file types are skipped (and reported in `skipped`).
 *
 * All work happens client-side; the resulting Blob is uploaded as the session's proof.pdf.
 */

// US Letter, in PDF points (72pt = 1in).
const PAGE_W = 612;
const PAGE_H = 792;
const MARGIN = 36;

export interface ProofBuildResult {
  blob: Blob;
  /** Names of files that were skipped because the type is unsupported. */
  skipped: string[];
}

export async function buildProofPdf(files: File[]): Promise<ProofBuildResult> {
  const doc = await PDFDocument.create();
  const skipped: string[] = [];

  for (const file of files) {
    if (file.type === 'application/pdf') {
      const bytes = new Uint8Array(await file.arrayBuffer());
      const src = await PDFDocument.load(bytes);
      const pages = await doc.copyPages(src, src.getPageIndices());
      pages.forEach(p => doc.addPage(p));
      continue;
    }

    if (file.type.startsWith('image/')) {
      const compressed = await ImageUtils.compressForUpload(file);
      const jpgBytes = new Uint8Array(await compressed.arrayBuffer());
      const img = await doc.embedJpg(jpgBytes);

      const page = doc.addPage([PAGE_W, PAGE_H]);
      const maxW = PAGE_W - MARGIN * 2;
      const maxH = PAGE_H - MARGIN * 2;
      const scale = Math.min(maxW / img.width, maxH / img.height, 1);
      const w = img.width * scale;
      const h = img.height * scale;
      page.drawImage(img, {
        x: (PAGE_W - w) / 2,
        y: (PAGE_H - h) / 2,
        width: w,
        height: h,
      });
      continue;
    }

    skipped.push(file.name);
  }

  const bytes = await doc.save();
  // Copy into a fresh ArrayBuffer-backed view so the Blob type is unambiguous.
  const blob = new Blob([bytes.slice()], { type: 'application/pdf' });
  return { blob, skipped };
}
