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 FileTreeUploadTargetPreflightPayload = {
  workspaceId?: string | null;
  targetDocumentId?: string | null;
  targetRowId?: string | null;
  focusedRowId?: string | null;
  activeDocumentId?: string | null;
  rows?: unknown[];
  documentWorkspaces?: Array<{ documentId?: string | null; workspaceId?: string | null }>;
};

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

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

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

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

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