import { NextRequest, NextResponse } from "next/server";
import { readFile } from "fs/promises";
import path from "path";

// Der Next.js-Prozess (Turbopack) merkt sich den Inhalt von public/ beim
// Start und erkennt danach hochgeladene Dateien (Portfolio/SEO/Testimonials/
// Blog/Conventions) sonst erst nach einem Neustart — Bilder, die nach dem
// letzten Deploy hochgeladen wurden, waren dadurch als kaputtes Bild
// sichtbar. Diese Route liest bei jedem Aufruf live vom Dateisystem und
// umgeht das Problem vollständig, siehe next.config.ts rewrites (beforeFiles),
// die /uploads/... hierher umleiten statt Next's public/-Static-Serving zu nutzen.
const ALLOWED_CATEGORIES = ["portfolio", "seo", "testimonials", "blog", "conventions"] as const;

const CONTENT_TYPES: Record<string, string> = {
  ".webp": "image/webp",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".png": "image/png",
};

export async function GET(_req: NextRequest, { params }: { params: Promise<{ category: string; filename: string }> }) {
  const { category, filename } = await params;
  if (!ALLOWED_CATEGORIES.includes(category as (typeof ALLOWED_CATEGORIES)[number])) {
    return new NextResponse("Not found", { status: 404 });
  }
  // Kein Pfad-Traversal — nur ein einzelner Dateiname ohne Verzeichniswechsel.
  if (filename.includes("/") || filename.includes("..")) {
    return new NextResponse("Not found", { status: 404 });
  }

  const filePath = path.join(process.cwd(), "public", "uploads", category, filename);
  let buffer: Buffer;
  try {
    buffer = await readFile(filePath);
  } catch {
    return new NextResponse("Not found", { status: 404 });
  }

  const ext = path.extname(filename).toLowerCase();
  const contentType = CONTENT_TYPES[ext] || "application/octet-stream";

  return new NextResponse(new Uint8Array(buffer), {
    headers: {
      "Content-Type": contentType,
      // Dateinamen enthalten schon einen Zeitstempel/UUID (siehe
      // lib/uploads.ts) — derselbe Name bekommt nie neuen Inhalt, daher
      // langfristig + immutable cachebar.
      "Cache-Control": "public, max-age=31536000, immutable",
    },
  });
}
