import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import {
  documentBridgeErrorResponse,
  executeBlockGetQuery,
} from "@/lib/blocks/block-command-adapter";

export async function GET(request: Request) {
  const url = new URL(request.url);
  const sourceDocumentId = url.searchParams.get("sourceDocumentId") || "";
  const blockId = url.searchParams.get("blockId") || "";

  if (!sourceDocumentId || !blockId) {
    return NextResponse.json({ error: "缺少参数" }, { status: 400 });
  }

  if (isConvexEnabled()) {
    try {
      const result = await executeBlockGetQuery({
        request,
        sourceDocumentId,
        blockId,
      });
      return NextResponse.json({ ok: true, block: result.block, meta: result.meta });
    } catch (error) {
      return documentBridgeErrorResponse(error);
    }
  }

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

  /*
  const supabase = await createSupabaseRouteClient();
  const {
    data: { session },
  } = await supabase.auth.getSession();
  if (!session) return NextResponse.json({ error: "未登录" }, { status: 401 });

  const { data: doc } = await supabase
    .from("documents")
    .select("id,content,user_id")
    .eq("id", sourceDocumentId)
    .eq("user_id", session.user.id)
    .single();
  if (!doc) return NextResponse.json({ error: "页面不存在或无权限" }, { status: 404 });

  const blocks = getBlocksFromDocumentContent(doc.content);
  const hit = findBlockInTree(blocks, blockId);
  if (!hit) return NextResponse.json({ error: "块不存在或无权限" }, { status: 404 });

  return NextResponse.json({ ok: true, block: hit.block });
  */
}

export const runtime = "nodejs";
