import { ReactElement, ReactNode } from 'react';
import { render, renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { MemoryRouter } from 'react-router-dom';

export function makeClient(): QueryClient {
    return new QueryClient({
        defaultOptions: {
            queries: { retry: false },
            mutations: { retry: false },
        },
    });
}

export function Providers({
    children,
    client = makeClient(),
    route = '/admin/dashboard',
}: {
    children: ReactNode;
    client?: QueryClient;
    route?: string;
}) {
    return (
        <QueryClientProvider client={client}>
            <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>
        </QueryClientProvider>
    );
}

export function renderWithProviders(ui: ReactElement, opts?: { route?: string }) {
    const client = makeClient();
    return {
        client,
        ...render(ui, {
            wrapper: ({ children }) => (
                <Providers client={client} route={opts?.route}>
                    {children}
                </Providers>
            ),
        }),
    };
}

export function renderHookWithClient<T>(cb: () => T) {
    const client = makeClient();
    return renderHook(cb, {
        wrapper: ({ children }) => (
            <QueryClientProvider client={client}>{children}</QueryClientProvider>
        ),
    });
}
