import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { loggerLink, httpBatchLink, createTRPCClient } from '@trpc/client';
import { TRPCProvider } from '@repo/client';
import { useMemo, useState } from 'react';
import superjson from 'superjson';
import { AppRouter } from '@repo/backend/trpc/index';

export default function QueryProvider({ children }) {
	// 将accessToken设置为空字符串
	const accessToken = '';

	// 使用Next.js环境变量
	const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';

	// Set the default query options including staleTime.
	const [queryClient] = useState(
		() =>
			new QueryClient({
				defaultOptions: {
					queries: {
						staleTime: 1000 * 60 * 5, // 5 minutes
					},
				},
			}),
	);

	const trpcClient = useMemo(() => {
		const headers = async () => ({
			...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
		});

		const links = [
			httpBatchLink({
				url: `${apiUrl}/trpc`,
				headers,
				transformer: superjson,
			}),
			loggerLink({
				enabled: (opts) =>
					(process.env.NODE_ENV === 'development' && typeof window !== 'undefined') ||
					(opts.direction === 'down' && opts.result instanceof Error),
			}),
		];

		return createTRPCClient<AppRouter>({
			links,
		});
	}, [accessToken, apiUrl]);

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