import { NextRequest, NextResponse } from "next/server";
import fs from "fs/promises";
import { CURATED_FONTS, isCuratedFontKey, SYSTEM_FONT } from "@/lib/fonts";
import { resolveCuratedFontPath, resolveSystemFontPath } from "@/lib/fonts-server";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ key: string }> },
) {
  const { key } = await params;
  const fontPath =
    key === SYSTEM_FONT.key
      ? resolveSystemFontPath()
      : isCuratedFontKey(key)
        ? resolveCuratedFontPath(key)
        : null;
  if (!fontPath) {
    return NextResponse.json({ error: "Unknown font" }, { status: 404 });
  }

  try {
    const buf = await fs.readFile(fontPath);
    const fileName =
      key === SYSTEM_FONT.key
        ? SYSTEM_FONT.file
        : CURATED_FONTS.find((f) => f.key === key)!.file;
    return new NextResponse(buf, {
      headers: {
        "Content-Type": "font/ttf",
        "Content-Disposition": `inline; filename="${fileName}"`,
        "Cache-Control": "public, max-age=86400, immutable",
      },
    });
  } catch {
    return NextResponse.json({ error: "Font file not found" }, { status: 404 });
  }
}
