import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import {
  assertDocumentId,
  documentBridgeErrorResponse,
} from "@/lib/documents/bridge";
import { loadPageAggregate } from "@/lib/documents/page-aggregate-loader";

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

export async function GET(request: Request) {
  if (isConvexEnabled()) {
    try {
      const url = new URL(request.url);
      const documentId = assertDocumentId(url.searchParams.get("documentId"));
      const workspaceId = url.searchParams.get("workspaceId")?.trim() || null;
      const loaded = await loadPageAggregate({
        request,
        documentId,
        workspaceId,
      });

      if (!loaded) {
        return NextResponse.json(
          {
            error: "页面不存在",
            meta: {
              requestId: "unknown",
              traceId: "unknown",
              queryName: "documents.page.get",
            },
          },
          { status: 404 },
        );
      }

      return NextResponse.json({
        page: loaded.page,
        meta: loaded.bridge,
      });
    } catch (error) {
      return documentBridgeErrorResponse(error);
    }
  }

  return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
}
