import { useEffect } from "@wordpress/element";

export const useSibsCheckout = ({
	method,
	endpoint,
	eventRegistration,
	emitResponse,
	data,
	enabled = true,
	getPayload = () => ({}),
}) => {
	useEffect(() => {
		if (!enabled) return;

		const unsubscribe =
			eventRegistration.onPaymentProcessing(async () => {
				try {
					const res = await fetch(endpoint, {
						method: "POST",
						headers: {
							"Content-Type": "application/json",
							"X-WP-Nonce": data?.checkoutNonce,
						},
						body: JSON.stringify({
							method,
							...getPayload(),
						}),
					});

					const response = await res.json();

					if (!response?.redirect) {
						throw new Error("Invalid response from server");
					}

					return {
						type: emitResponse.responseTypes.SUCCESS,
						redirectUrl: response.redirect,
					};
				} catch (err) {
					return {
						type: emitResponse.responseTypes.ERROR,
						message: "Payment initialization failed. Please try again.",
					};
				}
			});

		return () => unsubscribe();
	}, []);
};