// 업로드 이미지 서빙 — /data_storage/uploads/* 정적 스트림
// (운영 컨테이너의 nextjs uid 가 /data_storage 소유라 권한 안전)
import { NextRequest, NextResponse } from "next/server";
import { readFile } from "node:fs/promises";
import path from "node:path";

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

export async function GET(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) {
  const { path: parts } = await ctx.params;
  if (!parts || parts.length === 0) {
    return NextResponse.json({ error: "missing path" }, { status: 400 });
  }
  // path traversal 방지
  if (parts.some((p) => p.includes("..") || p.includes("\\"))) {
    return NextResponse.json({ error: "invalid path" }, { status: 400 });
  }
  const fullPath = path.join(ROOT, ...parts);
  if (!fullPath.startsWith(ROOT)) {
    return NextResponse.json({ error: "invalid path" }, { status: 400 });
  }
  try {
    const buf = await readFile(fullPath);
    const ext = path.extname(fullPath).toLowerCase();
    const ctype = MIME[ext] ?? "application/octet-stream";
    return new NextResponse(new Uint8Array(buf), {
      headers: {
        "Content-Type": ctype,
        "Cache-Control": "public, max-age=31536000, immutable",
      },
    });
  } catch {
    return NextResponse.json({ error: "not found" }, { status: 404 });
  }
}
