import sharp from "sharp";

// Wird nur auf Fotos aus einem Auftrag angewendet, dessen Rechnung noch nicht
// bezahlt ist (siehe ClientPhotoFolder.orderId + api/photos/[folderId]/[filename]) —
// schützt davor, dass Vorschau- oder gar Originalfotos vor Zahlungseingang
// unbeschränkt weiterverwendet werden. Verschwindet automatisch, sobald der
// Auftrag als bezahlt markiert wird, da hier live geprüft statt gespeichert wird.
function watermarkSvg(width: number, height: number): string {
  const tile = Math.max(180, Math.round(Math.min(width, height) / 4));
  const fontSize = Math.max(14, Math.round(tile / 11));
  return `
    <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <pattern id="wm" width="${tile}" height="${tile}" patternUnits="userSpaceOnUse" patternTransform="rotate(-30)">
          <text x="0" y="${tile / 2}" font-family="sans-serif" font-size="${fontSize}" fill="#ffffff" fill-opacity="0.38" letter-spacing="1">RAKKU · VORSCHAU</text>
        </pattern>
      </defs>
      <rect width="100%" height="100%" fill="url(#wm)" />
    </svg>
  `;
}

export async function applyWatermark(buffer: Buffer): Promise<Buffer> {
  const image = sharp(buffer);
  const meta = await image.metadata();
  const width = meta.width ?? 800;
  const height = meta.height ?? 600;
  return image
    .composite([{ input: Buffer.from(watermarkSvg(width, height)), blend: "over" }])
    .jpeg({ quality: 88 })
    .toBuffer();
}
