import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import { api } from "@/lib/convex/api";
import {
  assertDocumentId,
  buildDocumentBridgeContext,
  buildDocumentCommandEnvelope,
  documentBridgeErrorResponse,
} from "@/lib/documents/bridge";
import {
  executePageLifecycleBridgeCommand,
  type DocumentDuplicatePayload,
} from "@/lib/documents/page-command-adapter";
import {
  copyMindmapFilesIfExists,
  ensureDocumentScaffold,
} from "@/lib/documents/page-lifecycle-side-effects";

interface DuplicatePayload {
  documentId: string;
}

export async function POST(request: Request) {
  if (isConvexEnabled()) {
    try {
      const { client } = await getAuthedConvexClient();
      const { documentId }: DuplicatePayload = await request.json();
      const normalizedDocumentId = assertDocumentId(documentId);

      const sourceDoc = await client.query(api.documents.getMeta, { id: normalizedDocumentId });
      if (!sourceDoc) {
        return NextResponse.json({ error: "页面不存在或无权访问" }, { status: 404 });
      }

      const fallbackTitle =
        sourceDoc.title?.trim() && sourceDoc.title.trim().length > 0 ? sourceDoc.title.trim() : "无标题";
      const duplicatedTitle = `${fallbackTitle} 副本`;
      const newId =
        typeof crypto.randomUUID === "function"
          ? crypto.randomUUID()
          : `${Date.now()}_${Math.random().toString(16).slice(2)}`;
      const normalizedWorkspaceId = sourceDoc.workspace_id?.trim() || null;
      const bridgeContext = await buildDocumentBridgeContext({
        request,
        workspaceId: normalizedWorkspaceId,
      });
      const result = await executePageLifecycleBridgeCommand<
        DocumentDuplicatePayload,
        {
          id: string;
          title?: string | null;
          parent_id?: string | null;
          sort_order?: number | null;
        }
      >({
        context: bridgeContext,
        envelope: buildDocumentCommandEnvelope({
          name: "documents.duplicate",
          payload: {
            sourceDocumentId: normalizedDocumentId,
            newDocumentId: newId,
            workspaceId: normalizedWorkspaceId,
            title: duplicatedTitle,
          },
          context: bridgeContext,
          target: {
            workspaceId: normalizedWorkspaceId,
            pageId: newId,
          },
        }),
      });

      await ensureDocumentScaffold(result.result.id, result.result.title ?? duplicatedTitle);
      await copyMindmapFilesIfExists(normalizedDocumentId, result.result.id);

      return NextResponse.json({
        id: result.result.id,
        title: result.result.title ?? duplicatedTitle,
        parent_id: result.result.parent_id ?? null,
        sort_order: result.result.sort_order ?? null,
        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";
