/**
 * 法币提现管理 Hooks
 * 使用 React Query 进行数据获取和缓存管理
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { withdrawalService } from '@/services/withdrawalService';
import type {
  QueryFiatWithdrawalsParams,
  ReviewFiatWithdrawalRequest,
  StartPaymentRequest,
  CompletePaymentRequest,
  FiatWithdrawalStatus,
} from '@/types/withdrawal.types';

/** Query Keys */
export const withdrawalKeys = {
  all: ['fiatWithdrawals'] as const,
  pendingReview: (params: QueryFiatWithdrawalsParams) =>
    [...withdrawalKeys.all, 'pendingReview', params] as const,
  pendingPayment: (params: QueryFiatWithdrawalsParams) =>
    [...withdrawalKeys.all, 'pendingPayment', params] as const,
  byStatus: (status: FiatWithdrawalStatus, params: QueryFiatWithdrawalsParams) =>
    [...withdrawalKeys.all, 'byStatus', status, params] as const,
};

/**
 * 获取待审核的提现订单
 */
export function usePendingReviewWithdrawals(params: QueryFiatWithdrawalsParams = {}) {
  return useQuery({
    queryKey: withdrawalKeys.pendingReview(params),
    queryFn: () => withdrawalService.getPendingReview(params),
    staleTime: 30 * 1000, // 30秒后标记为过期
    gcTime: 5 * 60 * 1000, // 5分钟后垃圾回收
  });
}

/**
 * 获取待打款的提现订单
 */
export function usePendingPaymentWithdrawals(params: QueryFiatWithdrawalsParams = {}) {
  return useQuery({
    queryKey: withdrawalKeys.pendingPayment(params),
    queryFn: () => withdrawalService.getPendingPayment(params),
    staleTime: 30 * 1000,
    gcTime: 5 * 60 * 1000,
  });
}

/**
 * 按状态获取提现订单
 */
export function useWithdrawalsByStatus(
  status: FiatWithdrawalStatus,
  params: QueryFiatWithdrawalsParams = {}
) {
  return useQuery({
    queryKey: withdrawalKeys.byStatus(status, params),
    queryFn: () => withdrawalService.getByStatus(status, params),
    staleTime: 30 * 1000,
    gcTime: 5 * 60 * 1000,
  });
}

/**
 * 审核提现订单
 */
export function useReviewWithdrawal() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ orderNo, data }: { orderNo: string; data: ReviewFiatWithdrawalRequest }) =>
      withdrawalService.review(orderNo, data),
    onSuccess: () => {
      // 审核成功后刷新所有相关列表
      queryClient.invalidateQueries({ queryKey: withdrawalKeys.all });
    },
  });
}

/**
 * 开始打款
 */
export function useStartPayment() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ orderNo, data }: { orderNo: string; data?: StartPaymentRequest }) =>
      withdrawalService.startPayment(orderNo, data || {}),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: withdrawalKeys.all });
    },
  });
}

/**
 * 完成打款
 */
export function useCompletePayment() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ orderNo, data }: { orderNo: string; data?: CompletePaymentRequest }) =>
      withdrawalService.completePayment(orderNo, data || {}),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: withdrawalKeys.all });
    },
  });
}
