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

export async function POST(request: Request) {
  if (isConvexEnabled()) {
    try {
      const body = await request.json() as Partial<DocumentSavePayload> & { content?: unknown };
      const normalizedDocumentId = assertDocumentId(body.documentId);
      const payload = buildDocumentSavePayload({
        documentId: normalizedDocumentId,
        workspaceId: body.workspaceId,
        revision: body.revision,
        editorDocument: body.editorDocument,
        content: body.content as DocumentSavePayload["content"] | undefined,
        tiptapDocument: body.tiptapDocument,
        conflictDetectionKey: body.conflictDetectionKey,
        snapshotCapturedAt: body.snapshotCapturedAt,
        blockCount: body.blockCount,
      });
      const normalizedWorkspaceId = payload.workspaceId;
      const bridgeContext = await buildDocumentBridgeContext({ request, workspaceId: normalizedWorkspaceId });
      const envelope = buildDocumentCommandEnvelope({
        name: PAGE_COMMAND_NAMES.saveBody,
        payload: payload satisfies DocumentSavePayload,
        context: bridgeContext,
        target: {
          workspaceId: normalizedWorkspaceId,
          pageId: normalizedDocumentId,
        },
      });
      const result = await executePageWriteBridgeCommand({
        context: bridgeContext,
        envelope,
      });

      return NextResponse.json({
        ok: true,
        revision: result.revision,
        conflictDetectionKey: result.conflictDetectionKey,
        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";
