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

type FileTreePastePreflightPayload = {
  workspaceId?: string | null;
  targetDocumentId?: string | null;
  focusedRowId?: string | null;
  activeDocumentId?: string | null;
  rowIds?: string[];
  rows?: unknown[];
};

function trimOrNull(value: unknown) {
  if (typeof value !== "string") return null;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : null;
}

function normalizeStringArray(value: unknown): string[] {
  if (!Array.isArray(value)) return [];
  return value.map((item) => (typeof item === "string" ? item : "")).filter(Boolean);
}

function readFileTreePastePlan(plan: Awaited<ReturnType<typeof resolveRustBridgeCommandPlan>>) {
  const value = plan.argsJson.fileTreePastePlan;
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error("Rust runtime 未返回 fileTreePastePlan");
  }
  return value;
}

export async function POST(request: Request) {
  if (!isConvexEnabled()) {
    return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
  }

  try {
    const payload = (await request.json()) as FileTreePastePreflightPayload;
    const workspaceId = trimOrNull(payload.workspaceId);
    const normalizedPayload = {
      workspaceId,
      targetDocumentId: trimOrNull(payload.targetDocumentId),
      focusedRowId: trimOrNull(payload.focusedRowId),
      activeDocumentId: trimOrNull(payload.activeDocumentId),
      rowIds: normalizeStringArray(payload.rowIds),
      rows: Array.isArray(payload.rows) ? payload.rows : [],
    };
    const context = await buildDocumentBridgeContext({
      request,
      workspaceId,
      validateOnly: true,
      dryRun: true,
    });
    const envelope = buildDocumentCommandEnvelope({
      name: "tree.filetree.paste.preflight",
      payload: normalizedPayload,
      context,
      target: {
        workspaceId,
        pageId: normalizedPayload.targetDocumentId ?? undefined,
      },
      reason: "filetree-paste-preflight tree.filetree.paste.preflight",
      refs: ["file-tree-shell"],
    });
    const plan = await resolveRustBridgeCommandPlan({
      context,
      envelope,
    });

    return NextResponse.json({
      requestId: context.requestId,
      traceId: context.traceId,
      plan: readFileTreePastePlan(plan),
    });
  } catch (error) {
    return documentBridgeErrorResponse(error);
  }
}
