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

export const dynamic = "force-dynamic";

type CopyTreeItem = {
  documentId: string;
  recursive: boolean;
};

type CopyTreePayload = {
  items: CopyTreeItem[];
  targetParentId: string | null;
};

export async function POST(request: Request) {
  if (isConvexEnabled()) {
    try {
      const { client } = await getAuthedConvexClient();
      const payload = (await request.json()) as CopyTreePayload;
      const normalizedItems = (payload.items ?? [])
        .filter((item) => item?.documentId)
        .map((item) => ({
          documentId: assertDocumentId(item.documentId),
          recursive: Boolean(item.recursive),
        }));

      if (normalizedItems.length === 0) {
        return NextResponse.json({ error: "items 为空" }, { status: 400 });
      }

      const normalizedTargetParentId = payload.targetParentId?.trim() || null;
      let workspaceId: string | null = null;

      if (normalizedTargetParentId) {
        const targetDoc = await client.query(api.documents.getMeta, { id: normalizedTargetParentId });
        if (!targetDoc) {
          return NextResponse.json({ error: "目标页面不存在或无权限" }, { status: 404 });
        }
        workspaceId = targetDoc.workspace_id?.trim() || null;
      } else {
        const firstDoc = await client.query(api.documents.getMeta, { id: normalizedItems[0].documentId });
        if (!firstDoc) {
          return NextResponse.json({ error: "源页面不存在或无权限" }, { status: 404 });
        }
        workspaceId = firstDoc.workspace_id?.trim() || null;
      }

      if (!workspaceId) {
        return NextResponse.json({ error: "缺少目标工作空间" }, { status: 400 });
      }

      const bridgeContext = await buildDocumentBridgeContext({
        request,
        workspaceId,
      });
      const result = await executePageLifecycleBridgeCommand<
        DocumentCopyTreePayload,
        {
          items: Array<{
            oldId: string;
            newId: string;
            title?: string | null;
          }>;
        }
      >({
        context: bridgeContext,
        envelope: buildDocumentCommandEnvelope({
          name: "documents.copy_tree",
          payload: {
            workspaceId,
            targetParentId: normalizedTargetParentId,
            items: normalizedItems,
          },
          context: bridgeContext,
          target: {
            workspaceId,
            pageId: normalizedTargetParentId,
          },
        }),
      });

      await Promise.all(
        result.result.items.map(async (item) => {
          await ensureDocumentScaffold(item.newId, item.title ?? "无标题");
          await copyMindmapFilesIfExists(item.oldId, item.newId);
        }),
      );

      return NextResponse.json({
        items: result.result.items.map((item) => ({
          oldId: item.oldId,
          newId: item.newId,
        })),
        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";
