import type { Metadata } from "next";

export const dynamic = "force-dynamic";

import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { getLogoUrl } from "@/lib/appwrite/storage";
import { WatermarkClient } from "./watermark-client";

export const metadata: Metadata = {
  title: "Fotoğraf Damgala — KovakEmlak CRM",
};

async function fetchLogoAsDataUrl(logoUrl: string): Promise<string | null> {
  try {
    const res = await fetch(logoUrl, { next: { revalidate: 3600 } });
    if (!res.ok) return null;
    const buffer = Buffer.from(await res.arrayBuffer());
    const mime = res.headers.get("content-type") ?? "image/png";
    return `data:${mime};base64,${buffer.toString("base64")}`;
  } catch {
    return null;
  }
}

export default async function WatermarkPage() {
  const ctx = await requireTenant();
  const logoUrl = getLogoUrl(ctx.settings?.logo ?? null);
  const logoDataUrl = logoUrl ? await fetchLogoAsDataUrl(logoUrl) : null;
  return <WatermarkClient logoDataUrl={logoDataUrl} />;
}
