/**
 * سرو عکس‌های آپلودشده وقتی STORAGE_DRIVER=local است: GET /media/products/13/abc-800.webp
 * فقط فایل‌های webp داخل UPLOAD_DIR خوانده می‌شوند و مسیر در برابر ../ محافظت شده است.
 */
import { readFile } from "node:fs/promises";
import { env } from "@/lib/env";
import { localFilePath } from "@/integrations/storage/local";

export async function GET(_req: Request, { params }: { params: Promise<{ path: string[] }> }) {
  const key = (await params).path.join("/");
  const file = key.endsWith(".webp") ? localFilePath(env().UPLOAD_DIR, key) : undefined;
  if (!file) return new Response("Not found", { status: 404 });
  try {
    const body = await readFile(file);
    return new Response(new Uint8Array(body), {
      headers: {
        "Content-Type": "image/webp",
        // نام فایل‌ها یکتا و تغییرناپذیرند
        "Cache-Control": "public, max-age=31536000, immutable",
        "X-Content-Type-Options": "nosniff",
      },
    });
  } catch {
    return new Response("Not found", { status: 404 });
  }
}
