/**
 * @ai-summary Hook for deleting saved stations
 */

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { stationsApi } from '../api/stations.api';
import { SavedStation, ApiError } from '../types/stations.types';
import { useSavedStationsQueryKey, useUpdateSavedStationsCache } from './useSavedStations';
import { resolveSavedStationPlaceId } from '../utils/savedStations';

interface UseDeleteStationOptions {
  onSuccess?: (placeId: string) => void;
  onError?: (error: ApiError) => void;
}

/**
 * Mutation hook for deleting a saved station
 * Includes optimistic removal from cache
 *
 * @example
 * ```tsx
 * const { mutate: deleteStation, isPending } = useDeleteStation();
 *
 * const handleDelete = (placeId: string) => {
 *   deleteStation(placeId);
 * };
 * ```
 */
export function useDeleteStation(options?: UseDeleteStationOptions) {
  const updateCache = useUpdateSavedStationsCache();
  const queryClient = useQueryClient();
  const savedStationsKey = useSavedStationsQueryKey();

  return useMutation({
    mutationFn: async (placeId: string) => {
      await stationsApi.deleteSavedStation(placeId);
      return placeId;
    },
    onMutate: async (placeId) => {
      // Save previous state for rollback
      let previousStations: SavedStation[] | undefined;

      // Optimistic update: remove station immediately
      updateCache((old) => {
        previousStations = old;
        if (!old) return [];
        return old.filter((station) => {
          const stationPlaceId = resolveSavedStationPlaceId(station);
          return stationPlaceId !== placeId;
        });
      });

      return { previousStations, placeId };
    },
    onSuccess: (placeId) => {
      queryClient.invalidateQueries({
        queryKey: savedStationsKey
      });
      options?.onSuccess?.(placeId);
    },
    onError: (error, _placeId, context) => {
      // Rollback optimistic update on error
      if (context?.previousStations) {
        updateCache(() => context.previousStations || []);
      }

      options?.onError?.(error as ApiError);
    }
  });
}
