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 = ({ quoteId }: { quoteId?: string }) => {
	const { apiKey, baseUrl, affiliateId } = useConfig();
	const { logError } = useLogError();

	const query = `${baseUrl}/bungee/build-tx?quoteId=${quoteId}`;

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

	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";
}
