import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { findMatches, getMatchById, getTopMatches, updateMatchStatus, type FindMatchesQuery, } from '@/services/matching-api'; /** * Query key factory for matches */ export const matchingKeys = { all: ['matches'] as const, byResource: (resourceId: string, query?: FindMatchesQuery) => [...matchingKeys.all, 'resource', resourceId, query] as const, top: (limit?: number) => [...matchingKeys.all, 'top', limit] as const, detail: (matchId: string) => [...matchingKeys.all, 'detail', matchId] as const, }; /** * Hook to find matches for a resource * Returns empty array immediately to prevent blocking render */ export function useFindMatches(resourceId: string | null | undefined, query?: FindMatchesQuery) { return useQuery({ queryKey: matchingKeys.byResource(resourceId!, query), queryFn: () => findMatches(resourceId!, query), enabled: !!resourceId, placeholderData: { matches: [] }, // Render immediately with empty array }); } /** * Hook to get top matches across the platform */ export function useTopMatches(limit?: number) { return useQuery({ queryKey: matchingKeys.top(limit), queryFn: () => getTopMatches(limit), placeholderData: { matches: [] }, // Render immediately with empty array }); } /** * Hook to get a single match by ID */ export function useMatch(matchId: string | null | undefined) { return useQuery({ queryKey: matchingKeys.detail(matchId!), queryFn: () => getMatchById(matchId!), enabled: !!matchId, }); } /** * Hook to update match status */ export function useUpdateMatchStatus() { const queryClient = useQueryClient(); return useMutation({ mutationFn: ({ matchId, status, actor, notes, }: { matchId: string; status: string; actor: string; notes?: string; }) => updateMatchStatus(matchId, status, actor, notes), onSuccess: (_, { matchId }) => { // Invalidate the specific match and related queries queryClient.invalidateQueries({ queryKey: matchingKeys.detail(matchId) }); queryClient.invalidateQueries({ queryKey: matchingKeys.top() }); }, }); }