// src/hooks/queries/useCategoriesQuery.ts
import { useQuery } from '@tanstack/react-query';
import { fetchCategories } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { Category } from '../../types';

/**
 * Query hook for fetching all grocery categories.
 *
 * This is a public endpoint - no authentication required.
 *
 * Uses TanStack Query for automatic caching and refetching (ADR-0005 Phase 5).
 *
 * @returns TanStack Query result with Category[] data
 */
export const useCategoriesQuery = () => {
  return useQuery({
    queryKey: queryKeys.categories(),
    queryFn: async (): Promise<Category[]> => {
      const response = await fetchCategories();

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

      return response.json();
    },
    staleTime: 1000 * 60 * 60, // 1 hour - categories rarely change
  });
};
