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>
  `;
}

// Zentrale Entscheidung, ob ein Auftrag noch ein Wasserzeichen braucht —
// vorher 4x einzeln als `!order.paid` dupliziert (Bug-Fix, 26.09.2026):
// `paid` wird bei TFP-Aufträgen NIE gesetzt (siehe markOrderPaidAction in
// actions/admin.ts, atomarer Claim schließt compensationType "tfp" bewusst
// aus — bei TFP fließt kein Geld, "bezahlt" ergibt dort keinen Sinn). Ohne
// diese Ausnahme blieben TFP-Fotos für immer wasserzeichenbehaftet, obwohl
// nie eine Zahlung aussteht — real aufgetretener Fall bei zwei Kund:innen
// (Mandy Mannhaupt, Nicole Ender), von Till gemeldet.
export function needsPhotoWatermark(order: { compensationType: "paid" | "tfp"; paid: boolean } | null): boolean {
  return Boolean(order && order.compensationType === "paid" && !order.paid);
}

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();
}
