import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { updateApi } from '@/lib/api';
import type { UseQueryResult, UseMutationResult } from '@tanstack/react-query';

interface ActiveCommand {
  id: string;
  agent_id: string;
  agent_hostname: string;
  command_type: string;
  status: string;
  created_at: string;
  sent_at?: string;
  completed_at?: string;
  package_name: string;
  package_type: string;
}

export const useActiveCommands = (autoRefresh: boolean = true): UseQueryResult<{ commands: ActiveCommand[]; count: number }, Error> => {
  return useQuery({
    queryKey: ['activeCommands'],
    queryFn: () => updateApi.getActiveCommands(),
    refetchInterval: autoRefresh ? 5000 : false, // Auto-refresh every 5 seconds when enabled
    staleTime: 0, // Override global staleTime to allow refetchInterval to work
  });
};

export const useRecentCommands = (limit?: number): UseQueryResult<{ commands: ActiveCommand[]; count: number; limit: number }, Error> => {
  return useQuery({
    queryKey: ['recentCommands', limit],
    queryFn: () => updateApi.getRecentCommands(limit),
  });
};

export const useRetryCommand = (): UseMutationResult<{ message: string; command_id: string; new_id: string }, Error, string, unknown> => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: updateApi.retryCommand,
    onSuccess: () => {
      // Invalidate active and recent commands queries
      queryClient.invalidateQueries({ queryKey: ['activeCommands'] });
      queryClient.invalidateQueries({ queryKey: ['recentCommands'] });
    },
  });
};

export const useCancelCommand = (): UseMutationResult<{ message: string }, Error, string, unknown> => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: updateApi.cancelCommand,
    onSuccess: () => {
      // Invalidate active and recent commands queries
      queryClient.invalidateQueries({ queryKey: ['activeCommands'] });
      queryClient.invalidateQueries({ queryKey: ['recentCommands'] });
    },
  });
};

export const useClearFailedCommands = (): UseMutationResult<{ message: string; count: number; cheeky_warning?: string }, Error, {
  olderThanDays?: number;
  onlyRetried?: boolean;
  allFailed?: boolean;
} | undefined, unknown> => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: updateApi.clearFailedCommands,
    onSuccess: () => {
      // Invalidate active and recent commands queries to refresh the UI
      queryClient.invalidateQueries({ queryKey: ['activeCommands'] });
      queryClient.invalidateQueries({ queryKey: ['recentCommands'] });
    },
  });
};