import { promises as fs } from "fs";
import path from "path";
import { NextResponse } from "next/server";

const MEDIA_DIR = path.join(process.cwd(), "data", "media");

const MIME: Record<string, string> = {
  svg: "image/svg+xml",
  png: "image/png",
  jpg: "image/jpeg",
  jpeg: "image/jpeg",
  webp: "image/webp",
  mp4: "video/mp4",
};

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ filename: string }> },
) {
  const { filename } = await params;
  const safe = path.basename(filename);
  if (!safe || safe !== filename || safe.includes("..")) {
    return NextResponse.json({ error: "Invalid file" }, { status: 400 });
  }

  const filePath = path.join(MEDIA_DIR, safe);
  try {
    const data = await fs.readFile(filePath);
    const ext = safe.split(".").pop()?.toLowerCase() ?? "bin";
    return new NextResponse(data, {
      headers: {
        "Content-Type": MIME[ext] ?? "application/octet-stream",
        "Cache-Control": "no-store, no-cache, must-revalidate, max-age=0",
        Pragma: "no-cache",
      },
    });
  } catch {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
}
