import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import {
  assertDocumentId,
  buildDocumentBridgeContext,
  buildDocumentQueryEnvelope,
  documentBridgeErrorResponse,
} from "@/lib/documents/bridge";
import type { PageSubtreeProjection } from "@/lib/documents/page-subtree";
import { normalizeDocumentContentResponse } from "@/lib/documents/page-subtree-response";
import {
  executeRustBridgeQueryTransport,
  resolveRustBridgeQueryPlan,
} from "@/lib/documents/rust-runtime";

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 { client } = await getAuthedConvexClient();
      const bridgeContext = await buildDocumentBridgeContext({ request, workspaceId });
      const envelope = buildDocumentQueryEnvelope({
        name: "documents.content.get",
        payload: { documentId, workspaceId },
      });
      const plan = await resolveRustBridgeQueryPlan({
        context: bridgeContext,
        envelope,
      });
      const result = await executeRustBridgeQueryTransport<{
        content?: unknown;
        revision?: number | null;
        conflict_detection_key?: string | null;
        title?: string | null;
        page_subtree?: PageSubtreeProjection | null;
      } | null>({
        client,
        plan,
      });

      if (!result) {
        return NextResponse.json(
          {
            error: "页面不存在",
            meta: {
              requestId: bridgeContext.requestId,
              traceId: bridgeContext.traceId,
              queryName: envelope.name,
            },
          },
          { status: 404 },
        );
      }

      const normalized = normalizeDocumentContentResponse({
        documentId,
        title: typeof result.title === "string" && result.title.trim() ? result.title : null,
        payload: result,
      });

      return NextResponse.json({
        content: normalized.content,
        revision: normalized.revision,
        conflictDetectionKey: normalized.conflictDetectionKey,
        pageSubtree: normalized.pageSubtree,
        meta: {
          requestId: bridgeContext.requestId,
          traceId: bridgeContext.traceId,
          queryName: envelope.name,
        },
      });
    } catch (error) {
      return documentBridgeErrorResponse(error);
    }
  }

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