/**
 * @ai-summary Hook for updating saved station metadata
 */

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

interface UpdateSavedStationVariables {
  placeId: string;
  data: Partial<SaveStationData>;
}

interface UseUpdateSavedStationOptions {
  onSuccess?: (station: SavedStation) => void;
  onError?: (error: ApiError) => void;
}

/**
 * Mutation hook to update saved station metadata (octane flags, nickname, etc.)
 */
export function useUpdateSavedStation(options?: UseUpdateSavedStationOptions) {
  const updateCache = useUpdateSavedStationsCache();

  return useMutation({
    mutationFn: async ({ placeId, data }: UpdateSavedStationVariables) => {
      return stationsApi.updateSavedStation(placeId, data);
    },
    onMutate: async ({ placeId, data }) => {
      let previousStations: SavedStation[] | undefined;

      updateCache((old) => {
        previousStations = old;
        if (!old) return [];

        return old.map((station) => {
          const stationPlaceId = resolveSavedStationPlaceId(station);
          if (stationPlaceId !== placeId) {
            return station;
          }

          return {
            ...station,
            ...data,
            has93Octane:
              data.has93Octane !== undefined ? data.has93Octane : station.has93Octane,
            has93OctaneEthanolFree:
              data.has93OctaneEthanolFree !== undefined
                ? data.has93OctaneEthanolFree
                : station.has93OctaneEthanolFree
          };
        });
      });

      return { previousStations };
    },
    onSuccess: (station) => {
      options?.onSuccess?.(station);
    },
    onError: (error, _variables, context) => {
      if (context?.previousStations) {
        updateCache(() => context.previousStations || []);
      }

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