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

type MoveBlockPayload = {
  sourceDocumentId: string;
  blockId: string;
  targetDocumentId: string;
  position?: "end";
};

export async function POST(request: Request) {
  const { sourceDocumentId, blockId, targetDocumentId }: MoveBlockPayload = await request.json();

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

  if (sourceDocumentId === targetDocumentId) {
    // 说明：同页移动先不做“定位插入”，视为 no-op。
    return NextResponse.json({ ok: true, noop: true });
  }

  if (isConvexEnabled()) {
    try {
      const result = await executeBlockMoveCommand({
        request,
        sourceDocumentId,
        blockId,
        targetDocumentId,
      });
      const payload =
        result.result && typeof result.result === "object"
          ? (result.result as Record<string, unknown>)
          : {};
      return NextResponse.json({
        ...payload,
        ok: typeof payload.ok === "boolean" ? payload.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: sourceDoc } = await supabase
    .from("documents")
    .select("id,content,user_id")
    .eq("id", sourceDocumentId)
    .eq("user_id", session.user.id)
    .single();
  if (!sourceDoc) return NextResponse.json({ error: "源页面不存在或无权限" }, { status: 404 });

  const sourceBlocks = getBlocksFromDocumentContent(sourceDoc.content);
  const removedRes = removeBlockSubtree(sourceBlocks, blockId);
  if (!removedRes.removed) return NextResponse.json({ error: "源块不存在或无权限" }, { status: 404 });

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

  const targetBlocks = getBlocksFromDocumentContent(targetDoc.content);
  const nextSourcePayload = withBlocksWrittenBack(sourceDoc.content, removedRes.nextBlocks);
  const nextTargetPayload = withBlocksWrittenBack(targetDoc.content, [...targetBlocks, removedRes.removed]);

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

  const { error: tgtErr } = await supabase
    .from("documents")
    .update({ content: nextTargetPayload })
    .eq("id", targetDocumentId)
    .eq("user_id", session.user.id);
  if (tgtErr) return NextResponse.json({ error: tgtErr.message }, { status: 500 });

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

export const runtime = "nodejs";
