import { NextResponse } from "next/server";
import { promises as fs } from "fs";
import path from "path";

const ROOT = path.resolve(process.cwd(), process.env.LOCAL_STORAGE_DIR ?? "./storage/uploads");
const TYPES: Record<string, string> = { jpg: "image/jpeg", png: "image/png", webp: "image/webp", avif: "image/avif", mp4: "video/mp4", webm: "video/webm" };

/** Serves locally stored uploads. In production with STORAGE_DRIVER=s3 this route is unused. */
export async function GET(_: Request, { params }: { params: Promise<{ path: string[] }> }) {
  const parts = (await params).path;
  const full = path.resolve(ROOT, ...parts);
  if (!full.startsWith(ROOT + path.sep)) return new NextResponse("Not found", { status: 404 });
  const type = TYPES[path.extname(full).slice(1).toLowerCase()];
  if (!type) return new NextResponse("Not found", { status: 404 });
  try {
    const data = await fs.readFile(full);
    return new NextResponse(new Uint8Array(data), { headers: { "Content-Type": type, "Cache-Control": "public, max-age=31536000, immutable", "X-Content-Type-Options": "nosniff" } });
  } catch { return new NextResponse("Not found", { status: 404 }); }
}
