import { NextRequest, NextResponse } from "next/server";
import { getBuffer } from "@/lib/storage";
import { requireApiAuth, handleApiError } from "@/lib/api-auth";

const EXT_TO_CONTENT_TYPE: Record<string, string> = {
  jpg: "image/jpeg",
  jpeg: "image/jpeg",
  png: "image/png",
  webp: "image/webp",
  gif: "image/gif",
  pdf: "application/pdf",
};

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  try {
    await requireApiAuth();
    const { path: pathSegments } = await params;
    const key = pathSegments.join("/");

    if (!key) {
      return NextResponse.json({ error: "Missing path" }, { status: 400 });
    }

    const ext = key.split(".").pop()?.toLowerCase() ?? "";
    const contentType = EXT_TO_CONTENT_TYPE[ext] || "application/octet-stream";

    const buffer = await getBuffer(key);

    return new NextResponse(new Uint8Array(buffer), {
      headers: {
        "Content-Type": contentType,
        "Cache-Control": "private, max-age=3600",
      },
    });
  } catch (error) {
    return handleApiError(error);
  }
}
