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

/**
 * Hook to fetch ride detail with park, manufacturer, and designer
 */
export function useRideDetail(parkSlug: string | undefined, rideSlug: string | undefined, enabled = true) {
  return useQuery({
    queryKey: queryKeys.rides.detail(parkSlug || '', rideSlug || ''),
    queryFn: async () => {
      if (!parkSlug || !rideSlug) throw new Error('Both park and ride slugs are required');

      // First get park to find park_id
      const { data: parkData, error: parkError } = await supabase
        .from('parks')
        .select('id')
        .eq('slug', parkSlug)
        .maybeSingle();

      if (parkError) throw parkError;
      if (!parkData) return null;

      // Then get ride details
      const { data: rideData, error: rideError } = await supabase
        .from('rides')
        .select(`
          *, 
          park:parks!inner(id, name, slug, location:locations(*)),
          manufacturer:companies!rides_manufacturer_id_fkey(*),
          designer:companies!rides_designer_id_fkey(*)
        `)
        .eq('park_id', parkData.id)
        .eq('slug', rideSlug)
        .maybeSingle();

      if (rideError) throw rideError;
      
      // Add currentParkId for easier access
      if (rideData) {
        return { ...rideData, currentParkId: parkData.id };
      }
      
      return rideData;
    },
    enabled: enabled && !!parkSlug && !!rideSlug,
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 15 * 60 * 1000, // 15 minutes
    refetchOnWindowFocus: false,
  });
}
