/**
 * useUser Hook
 * Action 4.1.1.1: Create React Query hook for user
 *
 * Provides user data via React Query, replacing direct access to authStore.user
 * This hook uses React Query's built-in caching and deduplication.
 */

import { useQuery } from '@tanstack/react-query';
import { getMe } from '@/services/api/auth';
import { useAuthStore } from '../store/authStore';
import type { User } from '@/types';

/**
 * React Query hook for fetching current user data
 *
 * @returns User data, loading state, and error state
 *
 * @example
 * ```tsx
 * const { data: user, isLoading, error } = useUser();
 *
 * if (isLoading) return <Loading />;
 * if (error) return <Error />;
 * if (!user) return <NotAuthenticated />;
 *
 * return <div>Hello {user.username}</div>;
 * ```
 */
export function useUser() {
  const { isAuthenticated } = useAuthStore();

  return useQuery<User>({
    queryKey: ['user', 'me'],
    queryFn: getMe,
    enabled: isAuthenticated, // Only fetch if authenticated
    retry: false, // Don't retry on auth errors
    staleTime: 5 * 60 * 1000, // Consider data fresh for 5 minutes
    gcTime: 10 * 60 * 1000, // Keep in cache for 10 minutes (formerly cacheTime)
  });
}
