import { NextRequest, NextResponse } from "next/server";

// Serves blog images through this site's own URL (/api/blog-image/<file>) so the
// admin panel's host is never exposed in public pages. Only plain file names
// under the admin's storage/images folder can be requested.
const ADMIN_BASE = (
  process.env.ADMIN_IMAGE_SITE_URL || "https://dev-admin.astrology.togwe.com"
).replace(/\/+$/, "");

const SAFE_NAME = /^[\w.-]+\.(png|jpe?g|webp|gif|avif)$/i;

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

  if (!SAFE_NAME.test(file) || file.includes("..")) {
    return new NextResponse("Not found", { status: 404 });
  }

  try {
    const upstream = await fetch(`${ADMIN_BASE}/storage/images/${file}`, {
      next: { revalidate: 3600 },
    });

    const type = upstream.headers.get("content-type") ?? "";

    if (!upstream.ok || !type.startsWith("image/")) {
      return new NextResponse("Not found", { status: 404 });
    }

    return new NextResponse(upstream.body, {
      headers: {
        "Content-Type": type,
        "Cache-Control": "public, max-age=86400, stale-while-revalidate=604800",
      },
    });
  } catch {
    return new NextResponse("Bad gateway", { status: 502 });
  }
}
