import { useSwitchChain } from "wagmi";

import { useToast } from "@providers/ToastProvider";
import { useConfig } from "./useConfig";
import { USER_OPERATIONS, useLogError } from "./useLogError";

export const useChainSwitcher = () => {
	const { switchChainAsync } = useSwitchChain();
	const { eventHandlers } = useConfig();
	const { showToast } = useToast();
	const { logError } = useLogError();

	const switchToChain = async (
		targetChainId: number,
		currentChainId?: number,
	) => {
		if (currentChainId === targetChainId) return true;

		try {
			await switchChainAsync({ chainId: targetChainId });
			return true;
		} catch (err) {
			const _toastTitle = "Chain switch cancelled";
			const _toastMsg = "Please switch chain manually in the wallet to continue";

			showToast(_toastTitle, _toastMsg, "warning");

			if (eventHandlers?.onEvent) {
				eventHandlers.onEvent("warning", {
					title: _toastTitle,
					message: _toastMsg,
					action: "TRANSACTION",
				});
			}

			logError(err, {
				operation: USER_OPERATIONS.CHAIN_SWITCH,
				currentChainId,
				targetChainId,
			});

			return false;
		}
	};

	return { switchToChain };
};
