import { setIsInterruptable } from '@tec/tickets/seating/frontend/session';
import { ticketsBlockData } from '../localized-data';

const {
	ajaxUrl,
	ajaxNonce,
	ACTION_WOO_CART_UPDATE,
} = ticketsBlockData;

/**
 * Checkout handler for WooCommerce.
 *
 * @since 6.3.0
 *
 * @param {FormData} data The form data to send to the backend.
 */
export async function checkout(data){
	data.append( 'tribe_tickets_ar', '1' );
	data.append( 'tribe_tickets_provider', 'woo' );

	const requestUrl = new URL( ajaxUrl );
	requestUrl.searchParams.set( '_ajax_nonce', ajaxNonce );
	requestUrl.searchParams.set( 'action', ACTION_WOO_CART_UPDATE );

	// Call the backend to get the redirection URL with the cart data.
	const response = await fetch( requestUrl.toString() , {
		method: 'POST',
		body: data,
	});

	if ( !response.ok ) {
		// The server should reply with a redirect to the WooCommerce Checkout page.
		return false;
	}

	const result = await response.json();

	if ( !result || !result?.data?.url ) {
		return false;
	}

	// We're going to leave the page: this should not interrupt the timer and clear the session.
	setIsInterruptable(false);

	// We got a Checkout page URL back: redirect to it.
	window.location.href = result.data.url;

	// This return value might never be used, due to the previous redirection, but it's here to make the linter happy.
	return true;
}
