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

import { useConfig } from "@hooks/useConfig";
import { bungeeApiFetcher } from "@utils/fetcher";
import type {
	RequestStatusEnum,
	STATUS_CODE,
	StatusEndPoint,
} from "./useRequestStatus";

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

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

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

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

export type SubmitResponse = {
	basicReq: {
		originChainId: number;
		destinationChainId: number;
		deadline: string;
		nonce: number;
		sender: Address;
		receiver: Address;
		delegate: Address;
		bungeeGateway: Address;
		switchboardId: number;
		inputToken: Address;
		inputAmount: string;
		outputTokens: Array<Address>;
		minOutputAmounts: Array<string>;
	};
	swapOutputToken: Address;
	minSwapOutput: string;
	minDestGas: number;
	exclusiveTransmitters: Array<Address>;
	exclusiveRouters: Array<Address>;
	createdAt: string;
	inputTokens: StatusEndPoint[];
	outputTokens: StatusEndPoint[];
	requestHash: string;
	status: keyof typeof RequestStatusEnum;
	statusCode: STATUS_CODE;
	userSignature: string;
};
