import apiFetch from '@wordpress/api-fetch';

const base = () => window.edfwData?.restUrl?.replace( /\/$/, '' ) || '';

// Ensure the nonce header is sent.
apiFetch.use( apiFetch.createNonceMiddleware( window.edfwData?.nonce || '' ) );

export function getSettings() {
	return apiFetch( { url: `${ base() }/settings`, method: 'GET' } );
}

export function saveSettings( settings, rules ) {
	return apiFetch( {
		url: `${ base() }/settings`,
		method: 'POST',
		data: { settings, rules },
	} );
}

export function preview( settings, context = 'product' ) {
	return apiFetch( {
		url: `${ base() }/preview`,
		method: 'POST',
		data: { settings, context },
	} );
}

// Paginated search for rule condition values — loads pages on demand so a large
// catalog is never fetched all at once.
export function search( type, q = '', page = 1 ) {
	const params = new URLSearchParams( { type, q, page: String( page ) } );
	return apiFetch( { url: `${ base() }/search?${ params.toString() }`, method: 'GET' } );
}

// Resolve saved values (product IDs / term slugs) to labels for showing chips.
export function resolveValues( type, ids ) {
	if ( ! ids || ! ids.length ) {
		return Promise.resolve( { results: [] } );
	}
	const params = new URLSearchParams( { type, ids: ids.join( ',' ) } );
	return apiFetch( { url: `${ base() }/search?${ params.toString() }`, method: 'GET' } );
}
