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

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

  try {
    const payload = (await request.json()) as FileTreeDeletePreflightPayload;
    const workspaceId = trimOrNull(payload.workspaceId);
    const normalizedPayload = {
      workspaceId,
      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.delete.preflight",
      payload: normalizedPayload,
      context,
      target: {
        workspaceId,
      },
      reason: "filetree-delete-preflight tree.filetree.delete.preflight",
      refs: ["file-tree-shell"],
    });
    const plan = await resolveRustBridgeCommandPlan({
      context,
      envelope,
    });

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