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

/**
 * Hook to fetch all reviews by a specific user
 */
export function useUserReviews(
  userId: string | undefined,
  filter: 'all' | 'parks' | 'rides',
  sortBy: 'date' | 'rating',
  enabled = true
) {
  return useQuery({
    queryKey: queryKeys.reviews.user(userId || '', filter, sortBy),
    queryFn: async () => {
      if (!userId) return [];

      let query = supabase
        .from('reviews')
        .select(`
          id,
          rating,
          title,
          content,
          visit_date,
          wait_time_minutes,
          helpful_votes,
          moderation_status,
          created_at,
          parks:park_id (id, name, slug),
          rides:ride_id (
            id,
            name,
            slug,
            parks:park_id (name, slug)
          )
        `)
        .eq('user_id', userId);

      if (filter === 'parks') {
        query = query.not('park_id', 'is', null);
      } else if (filter === 'rides') {
        query = query.not('ride_id', 'is', null);
      }

      query = query.order(
        sortBy === 'date' ? 'created_at' : 'rating',
        { ascending: false }
      );

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