import { NextResponse } from "next/server";
import { resolveMnoteWebInternalUrl } from "@/lib/mnote-web/internal-url";
import { buildForwardHeaders } from "@/lib/server/forward-headers";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

const stripHopByHopHeaders = (headers: Headers) => {
  // 说明：代理响应不应继续透传 hop-by-hop headers，避免浏览器拿到无效连接语义。
  const hopByHopHeaders = [
    "connection",
    "keep-alive",
    "proxy-authenticate",
    "proxy-authorization",
    "te",
    "trailer",
    "transfer-encoding",
    "upgrade",
    "content-length",
  ];
  hopByHopHeaders.forEach((name) => headers.delete(name));
};

export async function GET(request: Request) {
  try {
    const requestUrl = new URL(request.url);
    const internalBaseUrl = await resolveMnoteWebInternalUrl();
    const targetUrl = new URL("/tree", `${internalBaseUrl}/`);
    targetUrl.search = requestUrl.search;

    const headers = await buildForwardHeaders(request);
    headers.set("accept", "text/html,application/xhtml+xml");
    headers.set("x-mnote-source-channel", "next_tree_shell_proxy");
    headers.set("x-mnote-source-client", "wolai-frontend");

    const workspaceId = requestUrl.searchParams.get("workspaceId")?.trim();
    if (workspaceId && !headers.has("x-mnote-workspace-id")) {
      headers.set("x-mnote-workspace-id", workspaceId);
    }

    const upstream = await fetch(targetUrl.toString(), {
      method: "GET",
      headers,
      cache: "no-store",
      redirect: "manual",
    });
    const body = await upstream.arrayBuffer();
    const responseHeaders = new Headers(upstream.headers);
    stripHopByHopHeaders(responseHeaders);
    responseHeaders.delete("set-cookie");
    responseHeaders.set("cache-control", "no-store");

    return new NextResponse(body, {
      status: upstream.status,
      statusText: upstream.statusText,
      headers: responseHeaders,
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : "tree shell 代理失败";
    return NextResponse.json(
      {
        error: message,
      },
      { status: 502 },
    );
  }
}
