/**
 * useBots Hooks
 * =============
 * TanStack Query hooks for trading bots management
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  botsService,
  type TradingBot,
  type BotTemplate,
  type BotPerformance,
  type BotExecution,
  type CreateBotInput,
  type UpdateBotInput,
  type BotFilters,
} from '../../../services/bots.service';

// ============================================================================
// Query Keys
// ============================================================================

export const botQueryKeys = {
  all: ['bots'] as const,
  lists: () => [...botQueryKeys.all, 'list'] as const,
  list: (filters?: BotFilters) => [...botQueryKeys.lists(), filters] as const,
  details: () => [...botQueryKeys.all, 'detail'] as const,
  detail: (id: string) => [...botQueryKeys.details(), id] as const,
  performance: (id: string) => [...botQueryKeys.all, 'performance', id] as const,
  executions: (id: string) => [...botQueryKeys.all, 'executions', id] as const,
  templates: () => [...botQueryKeys.all, 'templates'] as const,
  template: (type: string) => [...botQueryKeys.templates(), type] as const,
};

// ============================================================================
// Query Hooks
// ============================================================================

/**
 * Hook to fetch all bots with optional filters
 */
export function useBots(filters?: BotFilters) {
  return useQuery({
    queryKey: botQueryKeys.list(filters),
    queryFn: () => botsService.getBots(filters),
    staleTime: 30_000, // 30 seconds
    refetchInterval: 60_000, // Refetch every minute for live status updates
  });
}

/**
 * Hook to fetch a single bot by ID
 */
export function useBot(botId: string, enabled = true) {
  return useQuery({
    queryKey: botQueryKeys.detail(botId),
    queryFn: () => botsService.getBotById(botId),
    enabled: enabled && !!botId,
    staleTime: 15_000, // 15 seconds
    refetchInterval: 30_000, // Refetch every 30 seconds for live updates
  });
}

/**
 * Hook to fetch bot performance metrics
 */
export function useBotPerformance(botId: string, enabled = true) {
  return useQuery({
    queryKey: botQueryKeys.performance(botId),
    queryFn: () => botsService.getBotPerformance(botId),
    enabled: enabled && !!botId,
    staleTime: 30_000,
  });
}

/**
 * Hook to fetch bot execution history
 */
export function useBotExecutions(
  botId: string,
  options?: { limit?: number; offset?: number },
  enabled = true
) {
  return useQuery({
    queryKey: [...botQueryKeys.executions(botId), options],
    queryFn: () => botsService.getBotExecutions(botId, options),
    enabled: enabled && !!botId,
    staleTime: 30_000,
  });
}

/**
 * Hook to fetch bot templates
 */
export function useBotTemplates() {
  return useQuery({
    queryKey: botQueryKeys.templates(),
    queryFn: () => botsService.getBotTemplates(),
    staleTime: 5 * 60 * 1000, // 5 minutes - templates rarely change
  });
}

/**
 * Hook to fetch a specific bot template
 */
export function useBotTemplate(type: string, enabled = true) {
  return useQuery({
    queryKey: botQueryKeys.template(type),
    queryFn: () => botsService.getBotTemplate(type as 'atlas' | 'orion' | 'nova' | 'custom'),
    enabled: enabled && !!type,
    staleTime: 5 * 60 * 1000,
  });
}

// ============================================================================
// Mutation Hooks
// ============================================================================

/**
 * Hook to create a new bot
 */
export function useCreateBot() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (input: CreateBotInput) => botsService.createBot(input),
    onSuccess: (newBot) => {
      // Invalidate bot list to refetch
      queryClient.invalidateQueries({ queryKey: botQueryKeys.lists() });
      // Optionally add the new bot to cache
      queryClient.setQueryData(botQueryKeys.detail(newBot.id), newBot);
    },
  });
}

/**
 * Hook to update a bot
 */
export function useUpdateBot() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ botId, input }: { botId: string; input: UpdateBotInput }) =>
      botsService.updateBot(botId, input),
    onSuccess: (updatedBot, { botId }) => {
      // Update the specific bot in cache
      queryClient.setQueryData(botQueryKeys.detail(botId), updatedBot);
      // Invalidate bot list
      queryClient.invalidateQueries({ queryKey: botQueryKeys.lists() });
    },
  });
}

/**
 * Hook to delete a bot
 */
export function useDeleteBot() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (botId: string) => botsService.deleteBot(botId),
    onSuccess: (_, botId) => {
      // Remove from cache
      queryClient.removeQueries({ queryKey: botQueryKeys.detail(botId) });
      // Invalidate bot list
      queryClient.invalidateQueries({ queryKey: botQueryKeys.lists() });
    },
  });
}

/**
 * Hook to start a bot
 */
export function useStartBot() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (botId: string) => botsService.startBot(botId),
    onSuccess: (updatedBot, botId) => {
      // Update the specific bot in cache
      queryClient.setQueryData(botQueryKeys.detail(botId), updatedBot);
      // Invalidate bot list to update status
      queryClient.invalidateQueries({ queryKey: botQueryKeys.lists() });
    },
  });
}

/**
 * Hook to stop a bot
 */
export function useStopBot() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (botId: string) => botsService.stopBot(botId),
    onSuccess: (updatedBot, botId) => {
      // Update the specific bot in cache
      queryClient.setQueryData(botQueryKeys.detail(botId), updatedBot);
      // Invalidate bot list to update status
      queryClient.invalidateQueries({ queryKey: botQueryKeys.lists() });
    },
  });
}
