import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import { api } from "@/lib/convex/api";
import {
  assertDocumentId,
  buildDocumentBridgeContext,
  buildDocumentQueryEnvelope,
  documentBridgeErrorResponse,
} from "@/lib/documents/bridge";

export const dynamic = "force-dynamic";

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.meta.get",
        payload: { documentId, workspaceId },
      });

      const doc = await client.query(api.documents.getMeta, { id: documentId });

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

      return NextResponse.json({
        doc,
        meta: {
          requestId: bridgeContext.requestId,
          traceId: bridgeContext.traceId,
          queryName: envelope.name,
        },
      });
    } catch (error) {
      return documentBridgeErrorResponse(error);
    }
  }

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