import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import {
  DocumentBridgeError,
  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;
}

function assertPageHeadCommandName(commandName: string | null | undefined) {
  if (commandName !== PAGE_COMMAND_NAMES.updateTitle) {
    throw new DocumentBridgeError("标题保存仅支持 page.head.updateTitle", 400, "VALIDATION_ERROR", [
      {
        field: "commandName",
        reason: `expected ${PAGE_COMMAND_NAMES.updateTitle}`,
      },
    ]);
  }
}

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;
      assertPageHeadCommandName(commandName);

      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";
