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

import type { Output, RequestStatusEnum, STATUS_CODE } from "@/types/index";
import { useConfig } from "@hooks/useConfig";
import { bungeeApiFetcher } from "@utils/fetcher";
import type { RequestType } from "../common/quote/types";

export const useAutoStatus = ({
	requestHash,
	requestType,
}: { requestHash: string; requestType: RequestType }) => {
	const { apiKey, baseUrl } = useConfig();
	const shouldFetch = Boolean(requestHash && requestType);

	// biome-ignore format:
	const query = `${baseUrl}/bungee-auto/request-status?requestHash=${requestHash}&requestType=${requestType}`;

	const { data, isLoading, refetch } = useQuery({
		queryKey: ["bungee-auto-status", apiKey, requestHash],
		queryFn: () => bungeeApiFetcher(query, apiKey),
		enabled: shouldFetch,
		refetchOnWindowFocus: false,
		retry: 2,
		refetchInterval: 10000,
	});

	return {
		data: data?.result as AutoStatus,
		isLoading,
		refetch,
	};
};

export interface AutoStatus {
	status: keyof typeof RequestStatusEnum;
	statusCode: STATUS_CODE;
	srcTimestamp?: number; // will receive after extraction
	output: Output[];
	destTimestamp?: number;
}
