import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import * as watchlistApi from '../api/watchlist';
import { useToast } from '../components/ui/Toast';

export function useWatchlist() {
  return useQuery({
    queryKey: ['watchlist'],
    queryFn: () => watchlistApi.list(),
  });
}

export function useAddToWatchlist() {
  const qc = useQueryClient();
  const { addToast } = useToast();

  return useMutation({
    mutationFn: (symbol: string) => watchlistApi.add(symbol),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['watchlist'] });
    },
    onError: (error: Error) => {
      addToast('error', error.message || 'Failed to add to watchlist');
    },
  });
}

export function useRemoveFromWatchlist() {
  const qc = useQueryClient();
  const { addToast } = useToast();

  return useMutation({
    mutationFn: (symbol: string) => watchlistApi.remove(symbol),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['watchlist'] });
    },
    onError: (error: Error) => {
      addToast('error', error.message || 'Failed to remove from watchlist');
    },
  });
}
