import type { GraphMeta, SelectionQueryMeta } from "./types";

export async function fetchSelectionQueries(signal?: AbortSignal): Promise<SelectionQueryMeta[]> {
  const res = await fetch("/api/selection_queries", { signal });
  if (!res.ok) throw new Error(`GET /api/selection_queries failed: ${res.status}`);
  const data = await res.json();
  return Array.isArray(data) ? (data as SelectionQueryMeta[]) : [];
}

export async function runSelectionQuery(
  queryId: string,
  selectedIds: number[],
  graphMeta: GraphMeta | null,
  signal: AbortSignal
): Promise<number[]> {
  const body = {
    query_id: queryId,
    selected_ids: selectedIds,
    node_limit: typeof graphMeta?.node_limit === "number" ? graphMeta.node_limit : undefined,
    edge_limit: typeof graphMeta?.edge_limit === "number" ? graphMeta.edge_limit : undefined,
    graph_query_id: typeof graphMeta?.graph_query_id === "string" ? graphMeta.graph_query_id : undefined,
  };

  const res = await fetch("/api/selection_query", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body),
    signal,
  });
  if (!res.ok) throw new Error(`POST /api/selection_query failed: ${res.status}`);
  const data = await res.json();
  const ids: unknown = data?.neighbor_ids;
  if (!Array.isArray(ids)) return [];
  const out: number[] = [];
  for (const id of ids) if (typeof id === "number") out.push(id);
  return out;
}
