import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import * as api from '../api/paperTrades';
import type { ExitPolicy } from '../lib/types';
import { useToast } from '../components/ui/Toast';

export function usePaperTrades(status?: 'open' | 'closed') {
  return useQuery({
    queryKey: ['paper-trades', status ?? 'all'],
    queryFn: () => api.listPaperTrades(status),
    refetchInterval: 60_000,
  });
}

export function useExitPolicy() {
  return useQuery({
    queryKey: ['paper-trades', 'exit-policy'],
    queryFn: () => api.getExitPolicy(),
    staleTime: 5 * 60 * 1000,
  });
}

export function useUpdateExitPolicy() {
  const qc = useQueryClient();
  const { addToast } = useToast();
  return useMutation({
    mutationFn: (body: Partial<ExitPolicy>) => api.updateExitPolicy(body),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['paper-trades'] });
      addToast('success', 'Exit policy updated.');
    },
    onError: (e: Error) => addToast('error', e.message || 'Failed to update exit policy'),
  });
}

export function useCreatePaperTrade() {
  const qc = useQueryClient();
  const { addToast } = useToast();
  return useMutation({
    mutationFn: (body: api.CreatePaperTradeBody) => api.createPaperTrade(body),
    onSuccess: (t) => {
      qc.invalidateQueries({ queryKey: ['paper-trades'] });
      addToast('success', `Taken: ${t.shares} ${t.symbol} ${t.direction.toUpperCase()} @ ${t.entry_price}`);
    },
    onError: (e: Error) => addToast('error', e.message || 'Failed to take trade'),
  });
}

export function useClosePaperTrade() {
  const qc = useQueryClient();
  const { addToast } = useToast();
  return useMutation({
    mutationFn: ({ id, closePrice }: { id: number; closePrice?: number }) =>
      api.closePaperTrade(id, closePrice),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['paper-trades'] });
      addToast('success', 'Trade closed.');
    },
    onError: (e: Error) => addToast('error', e.message || 'Failed to close trade'),
  });
}
