/**
 * Test Wrapper Providers
 *
 * Wrapper components for testing React components with required context providers.
 */

import { type ReactNode, type FC } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

export interface TestWrapperOptions {
  /** Custom QueryClient instance */
  queryClient?: QueryClient
  /** Additional providers to wrap around children */
  additionalProviders?: FC<{ children: ReactNode }>[]
}

/**
 * Create a default QueryClient for testing
 */
export function createTestQueryClient(): QueryClient {
  return new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
        gcTime: 0,
        staleTime: 0,
      },
      mutations: {
        retry: false,
      },
    },
  })
}

/**
 * Create a QueryClient wrapper for testing React Query hooks
 */
export function createQueryClientWrapper(
  queryClient?: QueryClient
): FC<{ children: ReactNode }> {
  const client = queryClient || createTestQueryClient()

  return function QueryClientWrapper({ children }: { children: ReactNode }) {
    return <QueryClientProvider client={client}>{children}</QueryClientProvider>
  }
}

/**
 * Create a test wrapper with all common providers
 */
export function createTestWrapper(options: TestWrapperOptions = {}): FC<{ children: ReactNode }> {
  const { queryClient, additionalProviders = [] } = options
  const QueryWrapper = createQueryClientWrapper(queryClient)

  return function TestWrapper({ children }: { children: ReactNode }) {
    let content = children

    // Wrap with additional providers (innermost first)
    for (let i = additionalProviders.length - 1; i >= 0; i--) {
      const Provider = additionalProviders[i]
      content = <Provider>{content}</Provider>
    }

    // Wrap with QueryClient (outermost)
    return <QueryWrapper>{content}</QueryWrapper>
  }
}
