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

export function useHomepageClosingSoonParks(enabled = true) {
  return useQuery({
    queryKey: queryKeys.homepage.closingSoonParks(),
    queryFn: async () => {
      const today = new Date();
      const sixMonthsFromNow = new Date();
      sixMonthsFromNow.setMonth(sixMonthsFromNow.getMonth() + 6);

      const { data, error } = await supabase
        .from('parks')
        .select(`*, location:locations(*), operator:companies!parks_operator_id_fkey(*)`)
        .gte('closing_date', today.toISOString())
        .lte('closing_date', sixMonthsFromNow.toISOString())
        .order('closing_date', { ascending: true })
        .limit(12);
      
      if (error) throw error;
      return data || [];
    },
    enabled,
    staleTime: 5 * 60 * 1000,
    gcTime: 15 * 60 * 1000,
    refetchOnWindowFocus: false,
  });
}

export function useHomepageClosingSoonRides(enabled = true) {
  return useQuery({
    queryKey: queryKeys.homepage.closingSoonRides(),
    queryFn: async () => {
      const today = new Date();
      const sixMonthsFromNow = new Date();
      sixMonthsFromNow.setMonth(sixMonthsFromNow.getMonth() + 6);

      const { data, error } = await supabase
        .from('rides')
        .select(`
          *, 
          park:parks(*, location:locations(*)),
          manufacturer:companies!rides_manufacturer_id_fkey(*),
          designer:companies!rides_designer_id_fkey(*)
        `)
        .gte('closing_date', today.toISOString())
        .lte('closing_date', sixMonthsFromNow.toISOString())
        .order('closing_date', { ascending: true })
        .limit(12);
      
      if (error) throw error;
      return data || [];
    },
    enabled,
    staleTime: 5 * 60 * 1000,
    gcTime: 15 * 60 * 1000,
    refetchOnWindowFocus: false,
  });
}
