import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import type { PageOptionsState } from "@/types/page-options";
import {
  assertDocumentId,
  assertOptionsPatch,
  buildDocumentBridgeContext,
  buildDocumentCommandEnvelope,
  documentBridgeErrorResponse,
} from "@/lib/documents/bridge";
import {
  type DocumentOptionsUpdatePayload,
} 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";

type OptionsPayload = {
  documentId: string;
  workspaceId?: string | null;
  options: Partial<PageOptionsState>;
};

export async function POST(request: Request) {
  if (isConvexEnabled()) {
    try {
      const { documentId, workspaceId, options }: OptionsPayload = await request.json();
      const normalizedDocumentId = assertDocumentId(documentId);
      assertOptionsPatch(options);
      const normalizedWorkspaceId = workspaceId?.trim() || null;
      const bridgeContext = await buildDocumentBridgeContext({
        request,
        workspaceId: normalizedWorkspaceId,
      });
      const envelope = buildDocumentCommandEnvelope({
        name: PAGE_COMMAND_NAMES.updateLayout,
        payload: {
          documentId: normalizedDocumentId,
          workspaceId: normalizedWorkspaceId,
          options,
        } satisfies DocumentOptionsUpdatePayload,
        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 });
}
