// src/hooks/queries/useAuthProfileQuery.ts
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { getAuthenticatedUserProfile } from '../../services/apiClient';
import { getToken } from '../../services/tokenStorage';
import { queryKeys, queryKeyBases } from '../../config/queryKeys';
import type { UserProfile } from '../../types';

/**
 * Query key for the authenticated user's profile.
 * Exported for cache invalidation purposes.
 * @deprecated Use queryKeys.authProfile() from '../../config/queryKeys' instead
 */
export const AUTH_PROFILE_QUERY_KEY = queryKeys.authProfile();

/**
 * Query hook for fetching the authenticated user's profile.
 *
 * This query is used to validate the current auth token and retrieve
 * the user's profile data. It only runs when a token exists.
 *
 * @param enabled - Whether the query should run (default: true when token exists)
 * @returns TanStack Query result with UserProfile data
 *
 * @example
 * ```tsx
 * const { data: profile, isLoading, error } = useAuthProfileQuery();
 * ```
 */
export const useAuthProfileQuery = (enabled: boolean = true) => {
  const hasToken = !!getToken();

  return useQuery({
    queryKey: queryKeys.authProfile(),
    queryFn: async (): Promise<UserProfile> => {
      const response = await getAuthenticatedUserProfile();

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

      return response.json();
    },
    enabled: enabled && hasToken,
    staleTime: 1000 * 60 * 5, // 5 minutes
    retry: false, // Don't retry auth failures - they usually mean invalid token
  });
};

/**
 * Hook to manually invalidate the auth profile cache.
 * Useful after login or profile updates.
 */
export const useInvalidateAuthProfile = () => {
  const queryClient = useQueryClient();

  return () => {
    queryClient.invalidateQueries({ queryKey: queryKeyBases.authProfile });
  };
};
