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

// Prevent access to cloud metadata services
function isBlockedHost(hostname: string): boolean {
  const lower = hostname.toLowerCase();
  // AWS / GCP / Azure metadata endpoint
  if (lower === "169.254.169.254") return true;
  return false;
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const targetUrl = searchParams.get("url");
    const rawFileName = searchParams.get("filename") || "recording.mp4";

    if (!targetUrl) {
      return new NextResponse("Missing 'url' query parameter", { status: 400 });
    }

    let parsedUrl: URL;
    try {
      parsedUrl = new URL(targetUrl);
    } catch {
      return new NextResponse("Invalid URL", { status: 400 });
    }

    if (!["http:", "https:"].includes(parsedUrl.protocol)) {
      return new NextResponse("Invalid protocol", { status: 400 });
    }

    if (isBlockedHost(parsedUrl.hostname)) {
      return new NextResponse("Access to host forbidden", { status: 403 });
    }

    // Clean filename — remove invalid filename characters
    const safeFileName = rawFileName
      .replace(/[/\\?%*:|"<>]/g, "_")
      .trim() || "recording.mp4";

    // Fetch the file server-side (Node.js does not enforce browser CORS restrictions)
    const upstreamRes = await fetch(targetUrl, {
      headers: {
        "User-Agent": "IIH-Notetaker-Downloader/1.0",
      },
    });

    if (!upstreamRes.ok) {
      console.error(
        `[Download Proxy] Upstream fetch failed: ${upstreamRes.status} ${upstreamRes.statusText} for URL: ${targetUrl}`
      );
      return new NextResponse(
        `Upstream server returned ${upstreamRes.status}: ${upstreamRes.statusText}`,
        { status: upstreamRes.status }
      );
    }

    if (!upstreamRes.body) {
      return new NextResponse("Empty response from upstream", { status: 502 });
    }

    const contentType = upstreamRes.headers.get("content-type") || "application/octet-stream";
    const contentLength = upstreamRes.headers.get("content-length");

    const headers: Record<string, string> = {
      "Content-Type": contentType,
      "Content-Disposition": `attachment; filename="${safeFileName}"; filename*=UTF-8''${encodeURIComponent(safeFileName)}`,
      "Cache-Control": "no-cache, no-store, must-revalidate",
    };

    if (contentLength) {
      headers["Content-Length"] = contentLength;
    }

    // Stream the body chunk-by-chunk directly to the client
    return new Response(upstreamRes.body, {
      status: 200,
      headers,
    });
  } catch (error) {
    console.error("[Download Proxy Error]:", error);
    return new NextResponse("Internal Server Error while streaming download", { status: 500 });
  }
}
