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

import type {
	Input,
	Output,
	RequestStatusEnum,
	RouteDetails,
	STATUS_CODE,
} from "@/types/index";
import { useConfig } from "@hooks/useConfig";
import { useLogError } from "@hooks/useLogError";
import { bungeeApiFetcher } from "@utils/fetcher";
import { useEffect } from "react";

export const useStatus = ({
	requestHash,
	enabled = true,
}: {
	requestHash: string;
	enabled?: boolean;
}) => {
	const { apiKey, baseUrl } = useConfig();
	const { logError } = useLogError();
	const shouldFetch = Boolean(requestHash);

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

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

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

	return {
		data: data?.result?.[0] as StatusItem,
		isLoading,
		refetch,
	};
};

export interface StatusItem {
	hash: string;
	bungeeStatusCode: STATUS_CODE;
	routeDetails: RouteDetails;
	originData: OriginStatusData;
	destinationData: DestinationStatusData;
}

export interface OriginStatusData {
	input: Input[];
	originChainId: number;
	txHash: string | null;
	userAddress: string;
	status: keyof typeof RequestStatusEnum;
	timestamp: number | null;
}

export interface DestinationStatusData {
	output: Output[];
	destinationChainId: number;
	txHash: string | null;
	receiverAddress: string;
	status: keyof typeof RequestStatusEnum;
	timestamp: number | null;
}
