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

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const url = searchParams.get("url");

  if (!url) {
    return NextResponse.json(
      { error: "Missing URL parameter" },
      { status: 400 },
    );
  }

  try {
    // Try global fetch first, fall back to node-fetch if necessary
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    let response: any;
    try {
      if (
        typeof (globalThis as unknown as { fetch: unknown }).fetch ===
        "function"
      ) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        response = await (globalThis as unknown as { fetch: any }).fetch(url);
      }
    } catch (_e) {
      response = undefined;
    }

    if (!response || typeof response.ok === "undefined" || !response.ok) {
      try {
        const mod = await import("node-fetch");
        const nodeFetch = (mod as { default: unknown }).default ?? mod;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        response = await (nodeFetch as any)(url);
      } catch (err) {
        console.error("Failed to fetch image:", err);
        return NextResponse.json(
          { error: "Failed to fetch image" },
          { status: 500 },
        );
      }
    }

    if (!response || !response.ok) {
      throw new Error(
        `Failed to fetch image: ${response?.statusText ?? "no response"}`,
      );
    }

    const contentType = response.headers.get("content-type");
    const buffer = await response.arrayBuffer();

    return new NextResponse(buffer, {
      headers: {
        "Content-Type": contentType || "application/octet-stream",
      },
    });
  } catch (error) {
    console.error("Failed to fetch image:", error);
    return NextResponse.json(
      { error: "Failed to fetch image" },
      { status: 500 },
    );
  }
}
