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

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

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

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

  if (sourceDocumentId === targetDocumentId) {
    return NextResponse.json({ error: "禁止嵌入到当前页面" }, { status: 400 });
  }

  if (isConvexEnabled()) {
    try {
      const result = await executeBlockEmbedCommand({
        request,
        sourceDocumentId,
        blockId,
        targetDocumentId,
      });
      return NextResponse.json({
        ok: true,
        ...(result.result && typeof result.result === "object" ? result.result : {}),
        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);
  if (!findBlockInTree(sourceBlocks, blockId)) {
    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 referenceBlock = {
    id: randomUUID(),
    type: "blockReference",
    props: {
      sourceDocumentId,
      targetBlockId: blockId,
      display: "embed",
    },
    content: [],
    children: [],
  };

  const nextBlocks = [...targetBlocks, referenceBlock];
  const payload = withBlocksWrittenBack(targetDoc.content, nextBlocks);

  const { error } = await supabase
    .from("documents")
    .update({ content: payload })
    .eq("id", targetDocumentId)
    .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";
