/**
 * @ai-summary Hook for saving stations to favorites
 */

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

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

/**
 * Mutation hook for saving a station to favorites
 * Includes optimistic updates to saved stations cache
 *
 * @example
 * ```tsx
 * const { mutate: saveStation, isPending } = useSaveStation();
 *
 * const handleSave = (placeId: string) => {
 *   saveStation({
 *     placeId,
 *     nickname: 'My Station',
 *     isFavorite: true
 *   });
 * };
 * ```
 */
export function useSaveStation(options?: UseSaveStationOptions) {
  const queryClient = useQueryClient();
  const savedStationsKey = useSavedStationsQueryKey();
  const updateCache = useUpdateSavedStationsCache();

  return useMutation({
    mutationFn: async ({
      placeId,
      data
    }: {
      placeId: string;
      data: SaveStationData;
    }) => {
      return stationsApi.saveStation(placeId, data);
    },
    onMutate: async ({ placeId, data }) => {
      // Optimistic update: add station to cache immediately
      updateCache((old) => {
        if (!old) return [];

        const exists = old.some((s) => s.placeId === placeId);
        if (exists) return old;

        // Create optimistic station entry
        const optimisticStation: SavedStation = {
          id: `temp-${placeId}`,
          savedStationId: `temp-${placeId}`,
          placeId,
          name: data.nickname || 'New Station',
          address: '',
          latitude: 0,
          longitude: 0,
          rating: 0,
          userId: '', // Will be filled by server
          nickname: data.nickname,
          notes: data.notes,
          isFavorite: data.isFavorite ?? false,
          has93Octane: data.has93Octane ?? false,
          has93OctaneEthanolFree: data.has93OctaneEthanolFree ?? false,
          createdAt: new Date(),
          updatedAt: new Date()
        };

        return [...old, optimisticStation];
      });

      // Return context for rollback
      return { placeId };
    },
    onSuccess: (station) => {
      // Invalidate query to fetch fresh data
      queryClient.invalidateQueries({
        queryKey: savedStationsKey
      });

      options?.onSuccess?.(station);
    },
    onError: (error, _variables, context) => {
      // Rollback optimistic update on error
      if (context?.placeId) {
        updateCache((old) => {
          if (!old) return [];
          return old.filter(
            (s) => s.placeId !== context.placeId || !s.id.startsWith('temp-')
          );
        });
      }

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