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

import { useConfig } from "@hooks/useConfig";
import { useLogError } from "@hooks/useLogError";
import { bungeeApiFetcher } from "@utils/fetcher";
import type { ApprovalData, TxData } from "../common/quote/types";

export const useBuildTransaction = ({ routeId }: { routeId?: string }) => {
	const { apiKey, baseUrl } = useConfig();
	const { logError } = useLogError();

	// biome-ignore format:
	const query = `${baseUrl}/bungee/build-tx?quoteId=${routeId}`;

	const { data, isLoading, isError, error } = useQuery({
		queryKey: ["build-transaction", query],
		queryFn: () => bungeeApiFetcher(query, apiKey),
		refetchOnWindowFocus: false,
		refetchOnMount: false,
		retry: 2,
		staleTime: 60000,
		enabled: Boolean(routeId),
	});

	useEffect(() => {
		if (error && logError) {
			logError(error, { api: "build", query });
		}
	}, [error, query, logError]);

	return { data: data?.result as BuildTxData, isLoading, error, isError };
};

export interface BuildTxData {
	approvalData: ApprovalData;
	txData: TxData;
	userOp: "sign" | "tx";
}
