import { PDFDocument } from '@cantoo/pdf-lib';
import { readFile, writeFile, rename } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { createReadStream } from 'node:fs';

export interface SignatureToEmbed {
  fieldId: string;
  dataURL: string;   // 'data:image/png;base64,...' from signature_pad or typed canvas
  x: number;        // PDF user space (bottom-left origin, points) — from signatureFields
  y: number;
  width: number;
  height: number;
  page: number;     // 1-indexed
}

export async function embedSignatureInPdf(
  preparedPdfPath: string,   // absolute path — ALWAYS use doc.preparedFilePath, NOT filePath
  signedPdfPath: string,     // absolute path to write signed output (uploads/clients/{id}/{uuid}_signed.pdf)
  signatures: SignatureToEmbed[]
): Promise<string> {            // returns SHA-256 hex digest (LEGAL-02)
  const pdfBytes = await readFile(preparedPdfPath);
  const pdfDoc = await PDFDocument.load(pdfBytes);
  const pages = pdfDoc.getPages();

  for (const sig of signatures) {
    const page = pages[sig.page - 1];
    if (!page) continue;
    const pngImage = await pdfDoc.embedPng(sig.dataURL); // accepts base64 DataURL directly
    page.drawImage(pngImage, {
      x: sig.x,
      y: sig.y,
      width: sig.width,
      height: sig.height,
    });
  }

  const modifiedBytes = await pdfDoc.save();
  const tmpPath = `${signedPdfPath}.tmp`;
  await writeFile(tmpPath, modifiedBytes);
  await rename(tmpPath, signedPdfPath); // atomic rename prevents corruption on partial write

  // LEGAL-02: SHA-256 hash of final signed PDF — computed from disk after rename
  return hashFile(signedPdfPath);
}

function hashFile(filePath: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const hash = createHash('sha256');
    createReadStream(filePath)
      .on('data', (chunk) => hash.update(chunk))
      .on('end', () => resolve(hash.digest('hex')))
      .on('error', reject);
  });
}
