/**
 * @ai-summary Hook for managing saved stations with caching
 */

import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useIsAuthInitialized } from '../../../core/auth/auth-gate';
import { stationsApi } from '../api/stations.api';
import { SavedStation } from '../types/stations.types';

const SAVED_STATIONS_QUERY_KEY = ['stations', 'saved'];

interface UseSavedStationsOptions {
  /** Auto-refetch when window regains focus */
  refetchOnWindowFocus?: boolean;
  /** Cache time in milliseconds (default: 5 minutes) */
  staleTime?: number;
}

/**
 * Query hook for user's saved stations
 * Caches results and auto-refetches on window focus
 *
 * @example
 * ```tsx
 * const { data: savedStations, isPending, error } = useSavedStations();
 *
 * return (
 *   <div>
 *     {savedStations?.map(station => (
 *       <StationCard key={station.placeId} station={station} />
 *     ))}
 *   </div>
 * );
 * ```
 */
export function useSavedStations(options?: UseSavedStationsOptions) {
  const isAuthInitialized = useIsAuthInitialized();

  console.log('[DEBUG useSavedStations] Hook called, isAuthInitialized:', isAuthInitialized);

  return useQuery({
    queryKey: SAVED_STATIONS_QUERY_KEY,
    queryFn: async () => {
      console.log('[DEBUG useSavedStations] Query function executing');
      const result = await stationsApi.getSavedStations();
      console.log('[DEBUG useSavedStations] Query result:', result);
      return result;
    },
    staleTime: options?.staleTime ?? 5 * 60 * 1000, // 5 minutes default
    refetchOnWindowFocus: options?.refetchOnWindowFocus ?? true,
    refetchOnMount: true,
    enabled: isAuthInitialized, // Only fetch once auth is initialized
    retry: 1,
    retryDelay: 1000
  });
}

/**
 * Get query client utility for manual cache management
 */
export function useSavedStationsQueryKey() {
  return SAVED_STATIONS_QUERY_KEY;
}

/**
 * Invalidate saved stations cache
 * Call after mutations that affect saved stations
 */
export function useInvalidateSavedStations() {
  const queryClient = useQueryClient();

  return () => {
    queryClient.invalidateQueries({
      queryKey: SAVED_STATIONS_QUERY_KEY
    });
  };
}

/**
 * Update saved stations cache with optimistic update
 * @param updater Function to update the cache data
 */
export function useUpdateSavedStationsCache() {
  const queryClient = useQueryClient();

  return (updater: (old: SavedStation[] | undefined) => SavedStation[]) => {
    queryClient.setQueryData(SAVED_STATIONS_QUERY_KEY, updater);
  };
}
