// Stateless inventory/host lookups for the filter UI (class autocomplete, host
// search, entry->host resolution): transient reads, so plain functions not thunks.

import Api from '@northern.tech/store/api/general-api';

import { formEncoded } from '@/utils/api';
import { jqueryParam } from './utils/jqueryParam';
import type { HostEntry } from './types';

const CLASS_SUGGESTIONS_PER_PAGE = 20;

export interface HostSearchResult {
  data: HostEntry[];
  meta: { rowCount: number };
}

// Class name autocomplete. The endpoint returns each class as a tuple array
// with the class name at index 0.
export const fetchClasses = async (query: string, page = 1): Promise<string[]> => {
  const { data } = await Api.get<unknown[][]>(`/widget/allclasses/${page}/${encodeURIComponent(query)}/${CLASS_SUGGESTIONS_PER_PAGE}`);
  return (data ?? []).map(item => String(item?.[0] ?? '')).filter(Boolean);
};

// Free-text / IP / hostname / MAC host search used by the selection modal.
export const searchHostsByInventory = async (
  query: string,
  limit = 8,
  offset = 0,
  queryIsIpMask = false
): Promise<HostSearchResult> => {
  const { data } = await Api.get<HostSearchResult>('/host/searchHostsByInventory', {
    params: { query, limit, offset, ip_mask: queryIsIpMask }
  });
  return data;
};

// Resolve a set of entries (grouped by type) to concrete host rows. `filter`
// is an inventory-filter object keyed by attribute -> { operator: values }.
export const getHostsByInventory = async (filter: Record<string, Record<string, string[]>>): Promise<HostEntry[]> => {
  const { data } = await Api.post<{ data: HostEntry[] }>('/host/hostsByInventoryFilter', jqueryParam({ filter }), formEncoded);
  return data?.data ?? [];
};
