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

/**
 * Hook to fetch similar rides (same park and category)
 */
export function useSimilarRides(
  currentRideId: string | undefined,
  parkId: string | undefined,
  category: string | undefined,
  enabled = true
) {
  return useQuery({
    queryKey: queryKeys.rides.similar(parkId || '', category || '', currentRideId || ''),
    queryFn: async () => {
      if (!currentRideId || !parkId || !category) return [];

      const { data, error } = await supabase
        .from('rides')
        .select(`
          id,
          name,
          slug,
          image_url,
          average_rating,
          status,
          category,
          description,
          max_speed_kmh,
          max_height_meters,
          duration_seconds,
          review_count,
          park:parks!inner(name, slug)
        `)
        .eq('park_id', parkId)
        .eq('category', category)
        .neq('id', currentRideId)
        .order('average_rating', { ascending: false })
        .limit(4);

      if (error) throw error;
      return data || [];
    },
    enabled: enabled && !!currentRideId && !!parkId && !!category,
    staleTime: 10 * 60 * 1000, // 10 minutes - similar rides rarely change
    gcTime: 20 * 60 * 1000,
    refetchOnWindowFocus: false,
  });
}
