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

// Sert les captures d'écran (uploadées à l'exécution depuis l'admin) depuis
// `data/captures/`. On ne peut pas les mettre dans `public/` parce que Next.js
// fige le manifest statique au build : tout fichier ajouté ensuite renvoie 404.
const CAPTURES_DIR = path.join(process.cwd(), "data", "captures");

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

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ filename: string }> },
) {
  const { filename } = await params;

  // Anti-traversal : on n'autorise qu'un nom de fichier simple.
  if (!/^[a-z0-9._-]+$/i.test(filename) || filename.startsWith(".")) {
    return new NextResponse("Bad request", { status: 400 });
  }

  const ext = path.extname(filename).toLowerCase();
  const mime = MIME[ext];
  if (!mime) return new NextResponse("Not found", { status: 404 });

  const fullPath = path.join(CAPTURES_DIR, filename);
  // Garde-fou : on s'assure de rester dans le dossier autorisé.
  if (!fullPath.startsWith(CAPTURES_DIR)) {
    return new NextResponse("Bad request", { status: 400 });
  }

  try {
    const data = await fs.readFile(fullPath);
    return new NextResponse(data as unknown as BodyInit, {
      status: 200,
      headers: {
        "Content-Type": mime,
        "Cache-Control": "public, max-age=60, must-revalidate",
      },
    });
  } catch {
    return new NextResponse("Not found", { status: 404 });
  }
}
