import { PDFDocument } from "pdf-lib";

export interface DownloadMetadata {
  downloadedAt: string;
  downloadedById: string;
  downloadedByName?: string;
  downloadedByEmail?: string;
}

/**
 * Injects download-time metadata into an existing PDF's document properties.
 *
 * Appends download-specific key:value pairs to the PDF's Keywords field
 * (matching the semicolon-delimited format used at commit time) and updates
 * the ModificationDate.
 *
 * Returns the modified PDF as a `Uint8Array`.
 */
export async function injectPdfMetadata(
  pdfBytes: Buffer | Uint8Array,
  metadata: DownloadMetadata,
): Promise<Uint8Array> {
  const pdfDoc = await PDFDocument.load(pdfBytes);

  // Build new keyword entries in the same format used by generateQuote
  const newKeywordPairs = [
    `downloadedAt:${metadata.downloadedAt}`,
    `downloadedById:${metadata.downloadedById}`,
    metadata.downloadedByName
      ? `downloadedByName:${metadata.downloadedByName}`
      : null,
    metadata.downloadedByEmail
      ? `downloadedByEmail:${metadata.downloadedByEmail}`
      : null,
  ].filter(Boolean) as string[];

  // Append to existing keywords (preserve commit-time metadata)
  const existingKeywords = pdfDoc.getKeywords() ?? "";
  const separator = existingKeywords.length > 0 ? "; " : "";
  pdfDoc.setKeywords([
    existingKeywords + separator + newKeywordPairs.join("; "),
  ]);

  // Update modification date to download time
  pdfDoc.setModificationDate(new Date(metadata.downloadedAt));

  return pdfDoc.save();
}
