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

/**
 * Hook to fetch reviews for a specific entity (park or ride)
 */
export function useEntityReviews(entityType: 'park' | 'ride', entityId: string | undefined, enabled = true) {
  return useQuery({
    queryKey: queryKeys.reviews.entity(entityType, entityId || ''),
    queryFn: async () => {
      if (!entityId) return [];

      const query = supabase
        .from('reviews')
        .select(`
          *,
          profiles!reviews_user_id_fkey(username, avatar_url, display_name)
        `)
        .eq('moderation_status', 'approved')
        .order('created_at', { ascending: false });

      if (entityType === 'park') {
        query.eq('park_id', entityId);
      } else {
        query.eq('ride_id', entityId);
      }

      const { data, error } = await query;
      if (error) throw error;
      return data || [];
    },
    enabled: enabled && !!entityId,
    staleTime: 3 * 60 * 1000, // 3 minutes
    gcTime: 10 * 60 * 1000,
    refetchOnWindowFocus: false,
  });
}
