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

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

export const useSubmit = ({
	signature,
	requestData,
}: { signature: string; requestData: string }) => {
	const { apiKey, baseUrl } = useConfig();
	const { logError } = useLogError();
	const shouldFetch = !!(signature && requestData);

	// biome-ignore format:
	const query = `${baseUrl}/bungee/submit`

	const { data, isLoading, isError, error } = useQuery({
		queryKey: ["bungee-submit-api", apiKey, signature, requestData],
		queryFn: () => bungeeApiFetcher(query, apiKey, requestData, "POST"),
		enabled: shouldFetch,
		refetchOnWindowFocus: false,
		refetchOnMount: false,
		retry: 1,
	});

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

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

export type SubmitResponse = {
	requestHash: string;
	// currently im not using the submit data anywhere
};
