import { axiosInstance } from "@/axios";
import type {
	DjangoPaginated,
	OmTransaction,
	OmInitializationPayload as OmTransactionInitializationPayload,
	OmInitializationResponse as OmTransactionInitializationResponse,
	PaymentType,
	WaveInitializationPayload,
	WaveTransactionInitilizationResponse,
} from "./types";

export const getPaymentTypes = () => {
	return axiosInstance.get<DjangoPaginated<Record<string, PaymentType>>>("/operateur/");
};

// OM

export const omInitializeTransaction = (payload: OmTransactionInitializationPayload) => {
	return axiosInstance.post<OmTransactionInitializationResponse>("/transactions/", payload);
};

export const omVerifyTransactionState = (orderId: string) => {
	return axiosInstance.get<OmTransaction>(`/api/TransactionCheckStatus/${orderId}/`);
};

export const omVerifyTransactionStateWithTimeout = async (
	orderId: string,
	timeout: number,
	retryAfter = 5000,
) => {
	const sleep = (ms: number) => {
		return new Promise((resolve) => setTimeout(resolve, ms));
	};
	const now = Date.now();

	while (true) {
		const result = await omVerifyTransactionState(orderId);
		if (result.data.status !== "INITIATED") {
			return result;
		}

		if (Date.now() - now > timeout) {
			throw result;
		}

		await sleep(retryAfter);
	}
};

export const waveInitializeTransaction = (payload: WaveInitializationPayload) => {
	return axiosInstance.post<WaveTransactionInitilizationResponse>("/transactions/", payload);
};

export const waveGetTransactionStatus = (id: string) => {
	return axiosInstance.get<WaveTransactionInitilizationResponse>(`/wave-session/${id}/`);
};
