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 FileTreeDropPreflightPayload = {
  workspaceId?: string | null;
  copy?: boolean;
  targetDocumentId?: string | null;
  targetRowId?: string | null;
  focusedRowId?: string | null;
  activeDocumentId?: string | null;
  rowIds?: string[];
  rows?: unknown[];
  documentParents?: Array<{ documentId?: string | null; parentId?: string | null }>;
};

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 readFileTreeDropPlan(plan: Awaited<ReturnType<typeof resolveRustBridgeCommandPlan>>) {
  const value = plan.argsJson.fileTreeDropPlan;
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error("Rust runtime 未返回 fileTreeDropPlan");
  }
  return value;
}

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

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

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