import apiFetch from '@wordpress/api-fetch';
import { serialize as objectToFormData } from 'object-to-formdata';
import memoize from 'fast-memoize';
import AwesomeDebouncePromise from 'awesome-debounce-promise';

export function adminAjaxFetch< T >( body: { [ param: string ]: any } ) {
	return apiFetch< T >( {
		url: window.GPEB.ajaxUrl,
		method: 'POST',
		body: objectToFormData(
			{
				blockEditorXHRNonce: window.GPEB.blockEditorXHRNonce,
				...body,
			},
			{
				booleansAsIntegers: true,
			}
		),
	} );
}

export const adminAjaxFetchMemoized = memoize( adminAjaxFetch );
export const adminAjaxFetchDebounced = AwesomeDebouncePromise( adminAjaxFetchMemoized, 75 );
