import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";

type TreeMoveResponse = {
  requestId?: string;
  traceId?: string;
  result?: {
    documentId?: string;
    parentId?: string | null;
    sortOrder?: number | null;
  } | null;
};

type MovePayload = {
  documentId?: string | null;
  parentId?: string | null;
  position?: number | null;
  workspaceId?: string | null;
};

export async function POST(request: Request) {
  if (!isConvexEnabled()) {
    return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
  }

  try {
    const { documentId, parentId = null, position, workspaceId }: MovePayload = await request.json();
    const normalizedDocumentId = typeof documentId === "string" ? documentId.trim() : "";
    if (!normalizedDocumentId) {
      return NextResponse.json({ error: "缺少 documentId" }, { status: 400 });
    }

    const upstreamUrl = new URL("/api/tree/commands", request.url);
    const response = await fetch(upstreamUrl.toString(), {
      method: "POST",
      headers: new Headers({
        "content-type": "application/json",
      }),
      body: JSON.stringify({
        action: "move",
        documentId: normalizedDocumentId,
        parentId: typeof parentId === "string" ? parentId.trim() || null : null,
        sortOrder: typeof position === "number" && Number.isFinite(position) ? Math.floor(position) : 0,
        workspaceId: typeof workspaceId === "string" ? workspaceId.trim() || null : null,
      }),
    });

    const payload = (await response.json().catch(() => null)) as TreeMoveResponse | { error?: string } | null;
    if (!response.ok) {
      return NextResponse.json(
        {
          error:
            payload && typeof payload === "object" && "error" in payload && typeof payload.error === "string"
              ? payload.error
              : "移动失败，请稍后再试",
        },
        { status: response.status },
      );
    }

    return NextResponse.json({
      ok: true,
      meta: {
        requestId: payload?.requestId,
        traceId: payload?.traceId,
        commandName: "tree.subtree.move",
      },
    });
  } catch (error) {
    return NextResponse.json(
      {
        error: error instanceof Error ? error.message : "移动失败，请稍后再试",
      },
      { status: 500 },
    );
  }
}

export const runtime = "nodejs";
