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

/**
 * GET /api/proxy
 * Proxies cross-origin URLs to enforce a 'Save As' download in the browser.
 * 
 * Query parameters:
 *  - url: The remote URL target (e.g. googlevideo.com mp4 link)
 *  - filename: The desired file name for the downloaded file
 */
export async function GET(request: NextRequest): Promise<NextResponse> {
  const { searchParams } = new URL(request.url);
  const url = searchParams.get("url");
  let filename = searchParams.get("filename") || "download";

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

  // Ensure safe filenames
  filename = encodeURIComponent(filename).replace(/['()]/g, escape).replace(/\*/g, '%2A');

  try {
    const requestHeaders: Record<string, string> = {
      // Some servers like YT check User-Agent.
      "User-Agent": request.headers.get("User-Agent") || "Mozilla/5.0",
    };

    // Forward the Range header if the browser sends it for pausing/resuming
    if (request.headers.has("range")) {
      requestHeaders["Range"] = request.headers.get("range")!;
    }

    const remoteResponse = await fetch(url, {
      method: "GET",
      headers: requestHeaders,
    });

    if (!remoteResponse.ok && remoteResponse.status !== 206) {
      throw new Error(`Failed to fetch remote resource: ${remoteResponse.status}`);
    }

    // Forward the content type or fallback
    const contentType = remoteResponse.headers.get("Content-Type") || "application/octet-stream";
    const contentLength = remoteResponse.headers.get("Content-Length");
    const acceptRanges = remoteResponse.headers.get("Accept-Ranges");
    const contentRange = remoteResponse.headers.get("Content-Range");

    // Prepare headers for the proxied response to enforce download
    const responseHeaders = new Headers();
    responseHeaders.set("Content-Type", contentType);
    // Explicitly set Content-Disposition to attachment so the browser downloads the file
    responseHeaders.set("Content-Disposition", `attachment; filename*=UTF-8''${filename}`);
    
    // Transfer content headers if known, useful for download progress bars and resuming
    if (contentLength) responseHeaders.set("Content-Length", contentLength);
    if (acceptRanges) responseHeaders.set("Accept-Ranges", acceptRanges);
    if (contentRange) responseHeaders.set("Content-Range", contentRange);

    // Next.js (Edge/App Router) stream support
    return new NextResponse(remoteResponse.body, {
      status: remoteResponse.status,
      headers: responseHeaders,
    });
    
  } catch (error) {
    console.error("[PROXY API] Proxy download failed:", error);
    return NextResponse.json(
      { error: "Target file could not be proxied for download" },
      { status: 500 }
    );
  }
}
