import { useQuery } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { queryKeys } from '@/lib/queryKeys';
import type { GrowthTrendDataPoint, GranularityType } from '@/types/database-analytics';

export function useGrowthTrends(daysBack: number = 90, granularity: GranularityType = 'daily') {
  return useQuery({
    queryKey: queryKeys.analytics.growthTrends(daysBack, granularity),
    queryFn: async () => {
      const { data, error } = await supabase.rpc('get_entity_growth_trends', {
        days_back: daysBack,
        granularity: granularity,
      });

      if (error) {
        throw error;
      }

      return data as GrowthTrendDataPoint[];
    },
    staleTime: 10 * 60 * 1000, // 10 minutes
    refetchInterval: 5 * 60 * 1000, // Auto-refetch every 5 minutes
  });
}
