import { useQuery } from "@tanstack/react-query";

import { useConfig } from "@hooks/useConfig";
import { bungeeApiFetcher } from "@utils/fetcher";

export const useTokenSearch = ({
	keyword,
	address,
	enabled = true,
}: {
	keyword: string;
	address: string;
	enabled?: boolean;
}) => {
	const { baseUrl, apiKey, affiliateId } = useConfig();
	const query = `${baseUrl}/tokens/search?q=${keyword}&address=${address}`;

	const { data, isLoading } = useQuery({
		queryKey: ["token-search", query, apiKey],
		queryFn: () =>
			bungeeApiFetcher({
				query,
				apiKey,
				affiliateId,
			}),
		refetchOnWindowFocus: false,
		refetchOnMount: false,
		retry: 2,
		staleTime: 300000, // 5 minutes
		enabled: keyword?.length > 1 && enabled,
	});

	return { data: data?.result.tokens, isLoading };
};
