use-suggest-contacts.ts1.3 KBView on GitHub
import { useQuery } from '@tanstack/react-query';
import { useTRPC } from '@/providers/query-provider';

/**
 * Channel-aware contact autosuggest (design: contact-model-three-layer.md Phase 7). Replaces the
 * misuse of useContacts()/listContacts({limit:1000}) as an autosuggest source: this hits the
 * dedicated per-user, deduped-by-person crm.suggestContacts endpoint and returns only what an
 * autosuggest needs. The result is adapted to the `{ person: { email, name, currentRole } }` shape
 * the existing autosuggest components consume, so callers swap one hook and nothing else.
 *
 * @param channel - which address book to draw from (email | whatsapp | linkedin). Default: email.
 * @param enabled - lazy-load switch (default true).
 */
export type SuggestChannel = 'email' | 'whatsapp' | 'linkedin';

export function useSuggestContacts(channel: SuggestChannel = 'email', enabled = true) {
  const trpc = useTRPC();

  const result = useQuery({
    ...trpc.crm.suggestContacts.queryOptions({ channel }),
    enabled,
    staleTime: 5 * 60 * 1000, // Cache for 5 minutes
    gcTime: Infinity,
  });

  const contacts = (result.data ?? []).map((c) => ({
    person: { email: c.address, name: c.name, currentRole: c.currentRole },
  }));

  return { ...result, contacts, total: contacts.length };
}