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

/**
 * Query hook for fetching a user's address by ID.
 *
 * @param addressId - The ID of the address to fetch, or null/undefined if not available
 * @param enabled - Whether the query should run (default: true when addressId is provided)
 * @returns TanStack Query result with Address data
 *
 * @example
 * ```tsx
 * const { data: address, isLoading, error } = useUserAddressQuery(userProfile?.address_id);
 * ```
 */
export const useUserAddressQuery = (
  addressId: number | null | undefined,
  enabled: boolean = true,
) => {
  return useQuery({
    queryKey: queryKeys.userAddress(addressId ?? null),
    queryFn: async (): Promise<Address> => {
      if (!addressId) {
        throw new Error('Address ID is required');
      }

      const response = await getUserAddress(addressId);

      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 address');
      }

      return response.json();
    },
    enabled: enabled && !!addressId,
    staleTime: 1000 * 60 * 5, // 5 minutes - address data doesn't change frequently
  });
};
