import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import {
  buildDocumentBridgeContextWithActor,
  buildDocumentCommandEnvelope,
  documentBridgeErrorResponse,
} from "@/lib/documents/bridge";
import {
  executeRustBridgeMutationTransport,
  resolveRustBridgeCommandPlan,
} from "@/lib/documents/rust-runtime";

export const dynamic = "force-dynamic";

interface EmptyTrashPayload {
  workspaceId?: string;
}

export async function POST(request: Request) {
  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();
    const { workspaceId }: EmptyTrashPayload = await request.json().catch(() => ({}));
    if (!workspaceId) {
      return NextResponse.json({ error: "缺少 workspaceId" }, { status: 400 });
    }

    try {
      const context = buildDocumentBridgeContextWithActor({
        request,
        actor: {
          actorType: "user",
          actorId: auth.userId,
          sessionId: null,
        },
        workspaceId,
        source: {
          channel: "mindmap-trash-route",
          client: "wolai-frontend",
        },
      });
      const envelope = buildDocumentCommandEnvelope({
        name: "mindmaps.emptyTrashByWorkspace",
        payload: { workspaceId },
        context,
        target: {
          workspaceId,
        },
        reason: "mindmap-trash:empty",
        refs: ["task-047", "mindmap-trash"],
      });
      const plan = await resolveRustBridgeCommandPlan({ context, envelope });
      const result = await executeRustBridgeMutationTransport<{
        ok?: boolean;
        deletedCount?: number;
      }>({
        client,
        plan,
      });
      return NextResponse.json({ ok: true, removed: result?.deletedCount ?? 0 });
    } catch (error) {
      return documentBridgeErrorResponse(error);
    }
  }

  return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
}
