// src/hooks/queries/useUserProfileDataQuery.ts
import { useQuery } from '@tanstack/react-query';
import { getAuthenticatedUserProfile, getUserAchievements } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { UserProfile, Achievement, UserAchievement } from '../../types';

interface UserProfileData {
  profile: UserProfile;
  achievements: (UserAchievement & Achievement)[];
}

/**
 * Query hook for fetching the authenticated user's profile and achievements.
 *
 * This combines two API calls (profile + achievements) into a single query
 * for efficient fetching and caching.
 *
 * @param enabled - Whether the query should run (default: true)
 * @returns TanStack Query result with UserProfileData
 *
 * @example
 * ```tsx
 * const { data, isLoading, error } = useUserProfileDataQuery();
 * const profile = data?.profile;
 * const achievements = data?.achievements ?? [];
 * ```
 */
export const useUserProfileDataQuery = (enabled: boolean = true) => {
  return useQuery({
    queryKey: queryKeys.userProfileData(),
    queryFn: async (): Promise<UserProfileData> => {
      const [profileRes, achievementsRes] = await Promise.all([
        getAuthenticatedUserProfile(),
        getUserAchievements(),
      ]);

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

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

      const profile: UserProfile = await profileRes.json();
      const achievements: (UserAchievement & Achievement)[] = await achievementsRes.json();

      return {
        profile,
        achievements: achievements || [],
      };
    },
    enabled,
    staleTime: 1000 * 60 * 5, // 5 minutes
  });
};
