// src/hooks/mutations/useGeocodeMutation.ts
import { useMutation } from '@tanstack/react-query';
import { geocodeAddress } from '../../services/apiClient';
import { notifyError } from '../../services/notificationService';

interface GeocodeResult {
  lat: number;
  lng: number;
}

/**
 * Mutation hook for geocoding an address string to coordinates.
 *
 * @returns TanStack Query mutation for geocoding
 *
 * @example
 * ```tsx
 * const geocodeMutation = useGeocodeMutation();
 *
 * const handleGeocode = async () => {
 *   const result = await geocodeMutation.mutateAsync('123 Main St, City, State');
 *   if (result) {
 *     console.log(result.lat, result.lng);
 *   }
 * };
 * ```
 */
export const useGeocodeMutation = () => {
  return useMutation({
    mutationFn: async (address: string): Promise<GeocodeResult> => {
      const response = await geocodeAddress(address);

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

      return response.json();
    },
    onError: (error: Error) => {
      notifyError(error.message || 'Failed to geocode address');
    },
  });
};
