import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import {
  assertDocumentId,
  assertTitle,
  buildDocumentBridgeContext,
  buildDocumentCommandEnvelope,
  documentBridgeErrorResponse,
} from "@/lib/documents/bridge";
import {
  type DocumentTitleUpdatePayload,
} from "@/lib/documents/metadata-command-adapter";
import { executePageWriteBridgeCommand } from "@/lib/documents/page-write-command-adapter";
import { PAGE_COMMAND_NAMES } from "@/lib/documents/page-command-contract";

interface RenamePayload {
  documentId: string;
  workspaceId?: string | null;
  title: string;
  commandName?: string | null;
}

type TreeRenameResponse = {
  requestId?: string;
  traceId?: string;
};

export async function POST(request: Request) {
  if (isConvexEnabled()) {
    try {
      const { documentId, workspaceId, title, commandName }: RenamePayload = await request.json();
      const normalizedDocumentId = assertDocumentId(documentId);
      const normalizedTitle = assertTitle(title);
      const normalizedWorkspaceId = workspaceId?.trim() || null;

      if (commandName !== PAGE_COMMAND_NAMES.updateTitle) {
        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: "rename",
            documentId: normalizedDocumentId,
            workspaceId: normalizedWorkspaceId,
            title: normalizedTitle,
          }),
        });

        const payload = (await response.json().catch(() => null)) as TreeRenameResponse | { 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.node.rename",
          },
        });
      }

      const bridgeContext = await buildDocumentBridgeContext({ request, workspaceId: normalizedWorkspaceId });
      const envelope = buildDocumentCommandEnvelope({
        name: PAGE_COMMAND_NAMES.updateTitle,
        payload: {
          documentId: normalizedDocumentId,
          workspaceId: normalizedWorkspaceId,
          title: normalizedTitle,
        } satisfies DocumentTitleUpdatePayload,
        context: bridgeContext,
        target: {
          workspaceId: normalizedWorkspaceId,
          pageId: normalizedDocumentId,
        },
      });
      const result = await executePageWriteBridgeCommand({
        context: bridgeContext,
        envelope,
      });

      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 });
}

export const runtime = "nodejs";
