/**
 * 系统账户划转管理 Hooks
 * [2026-01-06] 新增
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { systemWithdrawalService } from '@/services/systemWithdrawalService';
import type {
  SystemWithdrawalQueryParams,
  SystemWithdrawalRequest,
} from '@/types/system-withdrawal.types';

/** Query Keys */
export const systemWithdrawalKeys = {
  all: ['systemWithdrawals'] as const,
  accounts: () => [...systemWithdrawalKeys.all, 'accounts'] as const,
  orders: (params: SystemWithdrawalQueryParams) => [...systemWithdrawalKeys.all, 'orders', params] as const,
  accountName: (accountSequence: string) => [...systemWithdrawalKeys.all, 'accountName', accountSequence] as const,
};

/**
 * 获取可划转的系统账户列表
 */
export function useSystemWithdrawalAccounts() {
  return useQuery({
    queryKey: systemWithdrawalKeys.accounts(),
    queryFn: () => systemWithdrawalService.getAccounts(),
    staleTime: 5 * 60 * 1000, // 5分钟
    gcTime: 10 * 60 * 1000,
  });
}

/**
 * 获取划转订单列表
 */
export function useSystemWithdrawalOrders(params: SystemWithdrawalQueryParams = {}) {
  return useQuery({
    queryKey: systemWithdrawalKeys.orders(params),
    queryFn: () => systemWithdrawalService.getOrders(params),
    staleTime: 30 * 1000, // 30秒
    gcTime: 5 * 60 * 1000,
  });
}

/**
 * 获取账户名称
 */
export function useAccountName(accountSequence: string) {
  return useQuery({
    queryKey: systemWithdrawalKeys.accountName(accountSequence),
    queryFn: () => systemWithdrawalService.getAccountName(accountSequence),
    enabled: !!accountSequence && accountSequence.length > 0,
    staleTime: 10 * 60 * 1000, // 10分钟
    gcTime: 30 * 60 * 1000,
  });
}

/**
 * 发起划转请求
 */
export function useRequestSystemWithdrawal() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: SystemWithdrawalRequest) => systemWithdrawalService.request(data),
    onSuccess: () => {
      // 成功后刷新账户列表和订单列表
      queryClient.invalidateQueries({ queryKey: systemWithdrawalKeys.all });
    },
  });
}
