import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import type { DocumentStats } from "@/types/page-options";
import {
  assertDocumentId,
  assertStats,
  buildDocumentBridgeContext,
  buildDocumentCommandEnvelope,
  documentBridgeErrorResponse,
} from "@/lib/documents/bridge";
import {
  executeMetadataBridgeCommand,
  type DocumentStatsUpdatePayload,
} from "@/lib/documents/metadata-command-adapter";

interface StatsPayload {
  documentId: string;
  workspaceId?: string | null;
  stats: DocumentStats;
}

export async function POST(request: Request) {
  if (isConvexEnabled()) {
    try {
      const { documentId, workspaceId, stats }: StatsPayload = await request.json();
      const normalizedDocumentId = assertDocumentId(documentId);
      assertStats(stats);
      const normalizedWorkspaceId = workspaceId?.trim() || null;
      const bridgeContext = await buildDocumentBridgeContext({
        request,
        workspaceId: normalizedWorkspaceId,
      });
      const envelope = buildDocumentCommandEnvelope({
        name: "documents.stats.update",
        payload: {
          documentId: normalizedDocumentId,
          workspaceId: normalizedWorkspaceId,
          stats,
        } satisfies DocumentStatsUpdatePayload,
        context: bridgeContext,
        target: {
          workspaceId: normalizedWorkspaceId,
          pageId: normalizedDocumentId,
        },
      });
      const result = await executeMetadataBridgeCommand({
        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 });
}
