import { readFile } from "node:fs/promises";
import path from "node:path";
import { renderToBuffer } from "@react-pdf/renderer";
import sharp from "sharp";
import { isLocale, localizedPath, type Locale } from "@alterra/shared";
import { fetchProperty } from "@/lib/api";
import { getPropertyCopy } from "@/lib/propertyCopy";
import { PropertySheet } from "@/lib/propertySheet";
import { siteUrl } from "@/lib/seo";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/** Fetches a photo and returns it as a JPEG data URI (react-pdf only reads JPEG/PNG). */
const toJpeg = async (url: string, base: string, width: number) => {
  try {
    const res = await fetch(new URL(url, base), { signal: AbortSignal.timeout(10000) });
    if (!res.ok) return null;
    const jpeg = await sharp(Buffer.from(await res.arrayBuffer())).rotate().resize({ width, withoutEnlargement: true }).jpeg({ quality: 78, mozjpeg: true }).toBuffer();
    return `data:image/jpeg;base64,${jpeg.toString("base64")}`;
  } catch {
    return null;
  }
};

/** GET /property-sheet/<slug>.pdf?lang=es → branded A4 sheet of a published property. */
export async function GET(request: Request, { params }: { params: Promise<{ file: string }> }) {
  const { file } = await params;
  const slug = file.replace(/\.pdf$/i, "");
  const langParam = new URL(request.url).searchParams.get("lang") ?? "en";
  const lang: Locale = isLocale(langParam) ? langParam : "en";
  if (!/^[a-z0-9-]+$/.test(slug)) return new Response("Not found", { status: 404 });

  const data = await fetchProperty(slug, lang);
  if (!data) return new Response("Not found", { status: 404 });
  const { property } = data;

  const logoPng = await readFile(path.join(process.cwd(), "public/brand/png/logo-horizontal-dark.png"));
  const [hero, ...gallery] = await Promise.all([
    property.images[0] ? toJpeg(property.images[0].url, request.url, 1600) : null,
    ...property.images.slice(1, 4).map((img) => toJpeg(img.url, request.url, 700)),
  ]);

  const pdf = await renderToBuffer(
    <PropertySheet
      property={property}
      lang={lang}
      copy={getPropertyCopy(lang)}
      images={{ logo: `data:image/png;base64,${logoPng.toString("base64")}`, hero, gallery: gallery.filter((g): g is string => !!g) }}
      pageUrl={`${siteUrl}${localizedPath(lang, `/properties/${property.slug}`)}`}
    />,
  );

  const name = `Alterra-${property.referenceCode}-${property.slug}.pdf`;
  return new Response(new Uint8Array(pdf), {
    headers: {
      "Content-Type": "application/pdf",
      "Content-Disposition": `inline; filename="${name}"`,
      "Cache-Control": "public, max-age=300",
    },
  });
}
