import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactNode } from 'react';
import { vi } from 'vitest';

/**
 * 创建测试用的QueryClient（带默认配置）
 */
export function createTestQueryClient(options = {}) {
  return new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
        gcTime: 0,
        staleTime: 0,
      },
      mutations: {
        retry: false,
      },
    },
    ...options
  });
}

/**
 * QueryProvider包装组件
 */
export function TestQueryProvider({
  children,
  client
}: {
  children: ReactNode;
  client?: QueryClient
}) {
  const queryClient = client || createTestQueryClient();

  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  );
}

/**
 * Mock查询Hook
 */
export function mockUseQuery(data: any, isLoading = false, error: any = null) {
  return vi.fn().mockReturnValue({
    data,
    isLoading,
    isError: !!error,
    error,
    isSuccess: !isLoading && !error,
    refetch: vi.fn(),
  });
}

/**
 * Mock变更Hook
 */
export function mockUseMutation() {
  return vi.fn().mockReturnValue({
    mutate: vi.fn(),
    mutateAsync: vi.fn().mockResolvedValue({}),
    isLoading: false,
    isError: false,
    error: null,
    isSuccess: false,
    reset: vi.fn(),
  });
}

/**
 * 等待查询完成
 */
export async function waitForQueryToFinish(delay = 100) {
  await new Promise(resolve => setTimeout(resolve, delay));
}

/**
 * 模拟网络错误
 */
export function mockNetworkError() {
  return new Error('Network error');
}

/**
 * 模拟服务器错误
 */
export function mockServerError() {
  return new Error('Server error');
}