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

const MIME_TYPES:Record<string,string>={".webp":"image/webp",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".ico":"image/x-icon"};

export async function GET(_request:Request,{params}:{params:Promise<{path:string[]}>}){
  const segments=(await params).path;
  if(!segments?.length||segments.some(segment=>!segment||segment==="."||segment===".."||segment.includes("/")||segment.includes("\\")))return new NextResponse("Arquivo inválido",{status:400});
  const uploadsRoot=path.resolve(process.cwd(),"public","uploads");
  const filePath=path.resolve(uploadsRoot,...segments);
  if(!filePath.startsWith(uploadsRoot+path.sep))return new NextResponse("Arquivo inválido",{status:400});
  try{const bytes=await readFile(filePath);const contentType=MIME_TYPES[path.extname(filePath).toLowerCase()]??"application/octet-stream";return new NextResponse(bytes,{headers:{"Content-Type":contentType,"Cache-Control":"public, max-age=31536000, immutable","X-Content-Type-Options":"nosniff"}})}catch{return new NextResponse("Imagem não encontrada",{status:404})}
}
