import { createReadStream, existsSync, statSync } from "fs";
import type { NextRequest } from "next/server";
import path from "path";
import { isSafeFilename, resolveUploadPath } from "@/server/uploads/paths";

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

  if (!isSafeFilename(filename)) {
    return new Response("Invalid filename", { status: 400 });
  }

  let filePath: string;
  try {
    filePath = resolveUploadPath(filename);
  } catch {
    return new Response("Invalid filename", { status: 400 });
  }

  if (!existsSync(filePath)) {
    return new Response("File not found", { status: 404 });
  }

  // Infer content type from extension
  const ext = path.extname(filename).toLowerCase();
  let contentType = "application/octet-stream";
  if (ext === ".webp") contentType = "image/webp";
  else if (ext === ".jpg" || ext === ".jpeg") contentType = "image/jpeg";
  else if (ext === ".png") contentType = "image/png";
  else if (ext === ".gif") contentType = "image/gif";

  const stat = statSync(filePath);
  const stream = createReadStream(filePath);

  return new Response(stream as any, {
    status: 200,
    headers: {
      "Content-Type": contentType,
      "Content-Length": stat.size.toString(),
      "Cache-Control": "public, max-age=31536000, immutable",
    },
  });
}
