/**
 * useWithdraw Hook
 * TanStack Query hooks for withdrawal operations
 * Epic: OQI-004 Cuentas de Inversion
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  getWithdrawals,
  createWithdrawal,
  type Withdrawal,
} from '../../../services/investment.service';
import { investmentAccountKeys } from './useInvestmentAccounts';

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

export const withdrawalKeys = {
  all: ['withdrawals'] as const,
  lists: () => [...withdrawalKeys.all, 'list'] as const,
  listByStatus: (status: string) =>
    [...withdrawalKeys.all, 'list', { status }] as const,
};

// ============================================================================
// Types
// ============================================================================

export interface WithdrawParams {
  accountId: string;
  amount: number;
  bankInfo?: {
    bankName: string;
    accountNumber: string;
    routingNumber: string;
  };
  cryptoInfo?: {
    network: string;
    address: string;
  };
}

// ============================================================================
// Hooks
// ============================================================================

/**
 * Hook to fetch all user withdrawals
 */
export function useWithdrawals(status?: string) {
  return useQuery<Withdrawal[], Error>({
    queryKey: status
      ? withdrawalKeys.listByStatus(status)
      : withdrawalKeys.lists(),
    queryFn: () => getWithdrawals(status),
    staleTime: 30 * 1000, // 30 seconds
  });
}

/**
 * Hook to create a withdrawal request
 * Invalidates account and withdrawal queries on success
 */
export function useWithdraw() {
  const queryClient = useQueryClient();

  return useMutation<Withdrawal, Error, WithdrawParams>({
    mutationFn: ({ accountId, amount, bankInfo, cryptoInfo }) =>
      createWithdrawal(accountId, amount, { bankInfo, cryptoInfo }),
    onSuccess: (_, { accountId }) => {
      // Invalidate withdrawals list
      queryClient.invalidateQueries({ queryKey: withdrawalKeys.all });
      // Invalidate accounts to update available balance
      queryClient.invalidateQueries({ queryKey: investmentAccountKeys.lists() });
      queryClient.invalidateQueries({ queryKey: investmentAccountKeys.summary() });
      queryClient.invalidateQueries({
        queryKey: investmentAccountKeys.detail(accountId),
      });
    },
  });
}

export default useWithdraw;
