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

export function useTickers() {
  return useQuery({
    queryKey: ['tickers'],
    queryFn: () => tickersApi.list(),
  });
}

/** symbol (upper) → company name, from the tracked-ticker list. Shared lookup so
 *  any view can show the company behind a symbol without its own request. */
export function useTickerNames(): Map<string, string> {
  const { data } = useTickers();
  return useMemo(() => {
    const map = new Map<string, string>();
    for (const t of data ?? []) {
      if (t.name) map.set(t.symbol.toUpperCase(), t.name);
    }
    return map;
  }, [data]);
}

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

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

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

  return useMutation({
    mutationFn: (symbol: string) => tickersApi.deleteTicker(symbol),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['tickers'] });
    },
    onError: (error: Error) => {
      addToast('error', error.message || 'Failed to delete ticker');
    },
  });
}
