import { TraceGraphNodeKind } from "./buildTraceGraphNodes";
import { TraceGraphLayoutNode } from "./traceGraphLayout";

const normalize = (value: string) => value.trim().toLowerCase();

const nodeSearchHaystack = (
  node: TraceGraphLayoutNode,
  kindLabel: string,
): string => {
  const parts: string[] = [
    node.title,
    node.subtitle,
    node.refCode ?? "",
    node.traceLotNo ?? "",
    node.traceItemCode ?? "",
    node.consoCode ?? "",
    node.meta ?? "",
    node.timestamp ?? "",
    node.categoryLabel ?? "",
    node.refType ?? "",
    node.warehouseCode ?? "",
    node.transferFromWarehouse ?? "",
    node.transferToWarehouse ?? "",
    kindLabel,
    node.qty != null ? String(node.qty) : "",
    ...node.details.flatMap((field) =>
      [field.label, field.value, field.linkCode ?? ""].filter(Boolean),
    ),
  ];
  return normalize(parts.join(" "));
};

export const searchTraceGraphNodes = (
  nodes: TraceGraphLayoutNode[],
  query: string,
  kindLabel: (kind: TraceGraphNodeKind) => string,
): string[] => {
  const normalizedQuery = normalize(query);
  if (!normalizedQuery) return [];

  return nodes
    .filter((node) =>
      nodeSearchHaystack(node, kindLabel(node.kind)).includes(normalizedQuery),
    )
    .sort((a, b) => a.sortKey - b.sortKey || a.sequenceIndex - b.sequenceIndex)
    .map((node) => node.id);
};
