import { useQuery } from '@tanstack/react-query';
import { useLocation } from 'react-router-dom';
import { supabase } from '@/integrations/supabase/client';
import { queryKeys } from '@/lib/queryKeys';
import type { DatabaseStatistics } from '@/types/database-stats';

export function useAdminDatabaseStats() {
  const location = useLocation();
  const isAdminPage = location.pathname.startsWith('/admin');

  return useQuery({
    queryKey: queryKeys.admin.databaseStats(),
    queryFn: async () => {
      const { data, error } = await supabase.rpc('get_database_statistics');

      if (error) {
        throw error;
      }

      return data as unknown as DatabaseStatistics;
    },
    enabled: isAdminPage, // Only run query on admin pages
    staleTime: 5 * 60 * 1000, // 5 minutes
    refetchInterval: isAdminPage ? 60 * 1000 : false, // Only refetch on admin pages
  });
}
