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

import { useConfig } from "@hooks/useConfig";
import type { Token } from "@providers/ConfigProvider";
import { bungeeApiFetcher } from "@utils/fetcher";
import type { RebateDetails, RequestType } from "./useFetchQuote";

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

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

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

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

export type StatusEndPoint = {
	token: Token;
	chainId: number;
	priceInUsd: number;
	amount?: string; // for source
	// below is only for destination endpoint
	minAmountOut: string;
	promisedAmount?: string;
	fulfilledAmount?: string;
	fulfilValueInUsd?: number;
	minAmountOutInUsd?: number;
};

export enum RequestStatusEnum {
	PENDING = 0,
	ASSIGNED = 1,
	EXTRACTED = 2,
	FULFILLED = 3,
	SETTLED = 4,
	EXPIRED = 5,
	CANCELLED = 6,
	REFUND_PENDING = 7,
	REFUNDE = 8,
}

export type STATUS_CODE = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;

export interface RequestStatus {
	requestType: RequestType;
	requestHash: string;
	status: keyof typeof RequestStatusEnum;
	statusCode: STATUS_CODE;
	sourceTransactionHash: string;
	destinationTransactionHash: string | null;
	input: StatusEndPoint[];
	output: StatusEndPoint[];
	sender: string;
	recipient: string;
	orderTimestamp: number;
	srcTimestamp: number;
	destTimestamp?: number | null;
	rebateDetails?: RebateDetails;
	quotedOutputAmount: string;
	quotedOutputInUsd: number;
}
