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

type PatchPayload = {
  sourceDocumentId: string;
  workspaceId?: string | null;
  blockId: string;
  nextBlock: unknown;
};

export async function POST(request: Request) {
  if (isConvexEnabled()) {
    try {
      const { sourceDocumentId, workspaceId, blockId, nextBlock }: PatchPayload = await request.json();
      const result = await executeBlockPatchCommand({
        request,
        sourceDocumentId,
        workspaceId,
        blockId,
        nextBlock,
      });
      return NextResponse.json({
        ok: true,
        meta: {
          requestId: result.requestId,
          traceId: result.traceId,
          commandId: result.commandId,
          commandName: result.commandName,
        },
      });
    } 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 replaced = replaceBlockInTree(blocks, blockId, nextBlock as any);
  if (!replaced.ok) return NextResponse.json({ error: "块不存在或无权限" }, { status: 404 });

  const payload = withBlocksWrittenBack(doc.content, replaced.nextBlocks);
  const { error } = await supabase
    .from("documents")
    .update({ content: payload })
    .eq("id", sourceDocumentId)
    .eq("user_id", session.user.id);
  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

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

export const runtime = "nodejs";
