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

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

const SAFE_FILE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;

export async function GET(_request: Request, { params }: { params: Promise<{ file: string }> }) {
  const { file } = await params;
  if (!SAFE_FILE.test(file) || file.includes("..")) {
    return new NextResponse("Not found", { status: 404 });
  }

  const type = TYPES[path.extname(file).toLowerCase()];
  if (!type) return new NextResponse("Not found", { status: 404 });

  const directory = path.join(process.cwd(), "public", "uploads");
  const target = path.join(directory, file);
  if (!target.startsWith(`${directory}${path.sep}`)) {
    return new NextResponse("Not found", { status: 404 });
  }

  try {
    const bytes = await readFile(target);
    return new NextResponse(new Uint8Array(bytes), {
      headers: {
        "Content-Type": type,
        "Cache-Control": "public, max-age=31536000, immutable",
        "X-Content-Type-Options": "nosniff",
      },
    });
  } catch {
    return new NextResponse("Not found", { status: 404 });
  }
}
