import { useQuery } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { queryKeys } from '@/lib/queryKeys';

/**
 * Hook for global search across parks, rides, and companies
 * Searches in parallel and caches results
 */
export function useGlobalSearch(query: string) {
  return useQuery({
    queryKey: queryKeys.search.global(query.toLowerCase()),
    queryFn: async () => {
      if (query.length < 2) {
        return { parks: [], rides: [], companies: [] };
      }

      const searchTerm = `%${query.toLowerCase()}%`;

      // Run all 3 queries in parallel
      const [parksResult, ridesResult, companiesResult] = await Promise.all([
        supabase
          .from('parks')
          .select(`*, location:locations(*)`)
          .or(`name.ilike.${searchTerm},description.ilike.${searchTerm}`)
          .limit(5),
        supabase
          .from('rides')
          .select(`*, park:parks!inner(name, slug)`)
          .or(`name.ilike.${searchTerm},description.ilike.${searchTerm}`)
          .limit(5),
        supabase
          .from('companies')
          .select('id, name, slug, description, company_type, logo_url, average_rating, review_count')
          .or(`name.ilike.${searchTerm},description.ilike.${searchTerm}`)
          .limit(3),
      ]);

      if (parksResult.error) throw parksResult.error;
      if (ridesResult.error) throw ridesResult.error;
      if (companiesResult.error) throw companiesResult.error;

      return {
        parks: parksResult.data || [],
        rides: ridesResult.data || [],
        companies: companiesResult.data || [],
      };
    },
    enabled: query.length >= 2,
    staleTime: 2 * 60 * 1000, // 2 minutes - search results fairly stable
    gcTime: 5 * 60 * 1000,
    refetchOnWindowFocus: false,
  });
}
