import { NextResponse } from "next/server";
import { documentBridgeErrorResponse } from "@/lib/documents/bridge";
import { prepareOnlyOfficeProxyRequest } from "@/lib/onlyoffice/rust-adapter";
import { getMnoteRuntimeConfig } from "@/lib/runtime-config";

export const dynamic = "force-dynamic";

const toHeaders = (items: Array<{ name: string; value: string }>) => {
  const headers = new Headers();
  for (const item of items) {
    if (!item.name || !item.value) continue;
    headers.set(item.name, item.value);
  }
  return headers;
};

const handle = async (request: Request, method: "GET" | "HEAD") => {
  try {
    const { searchParams } = new URL(request.url);
    const encodedUrl = String(searchParams.get("u") || "").trim();
    if (!encodedUrl) {
      return NextResponse.json({ error: "缺少 u" }, { status: 400 });
    }

    const prepared = await prepareOnlyOfficeProxyRequest({
      request,
      encodedUrl,
      method,
      range: request.headers.get("range"),
      runtimeConfig: getMnoteRuntimeConfig(),
    });

    const upstream = await fetch(prepared.targetUrl, {
      method,
      headers: toHeaders(prepared.forwardHeaders),
      redirect: "follow",
    });

    const headers = new Headers(upstream.headers);
    headers.delete("set-cookie");

    if (method === "HEAD") {
      return new Response(null, {
        status: upstream.status,
        statusText: upstream.statusText,
        headers,
      });
    }

    return new Response(upstream.body, {
      status: upstream.status,
      statusText: upstream.statusText,
      headers,
    });
  } catch (error) {
    return documentBridgeErrorResponse(error);
  }
};

export async function GET(request: Request) {
  return await handle(request, "GET");
}

export async function HEAD(request: Request) {
  return await handle(request, "HEAD");
}
