// src/hooks/queries/useApplicationStatsQuery.ts
import { useQuery } from '@tanstack/react-query';
import { getApplicationStats, AppStats } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';

/**
 * Query hook for fetching application-wide statistics (admin feature).
 *
 * Returns app-wide counts for:
 * - Flyers
 * - Users
 * - Flyer items
 * - Stores
 * - Pending corrections
 * - Recipes
 *
 * Uses TanStack Query for automatic caching and refetching (ADR-0005 Phase 5).
 *
 * @returns TanStack Query result with AppStats data
 */
export const useApplicationStatsQuery = () => {
  return useQuery({
    queryKey: queryKeys.applicationStats(),
    queryFn: async (): Promise<AppStats> => {
      const response = await getApplicationStats();

      if (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to fetch application stats');
      }

      return response.json();
    },
    staleTime: 1000 * 60 * 2, // 2 minutes - stats change moderately, not as frequently as activity log
  });
};
