/**
 * Thin API wrapper around wp.apiFetch.
 */
import apiFetch from '@wordpress/api-fetch';

const root = () =>
	( typeof jocbmAdmin !== 'undefined' && jocbmAdmin.restUrl ) ||
	'/wp-json/joc-blockora-morph/v1';

const ownerNs = () =>
	( typeof jocbmAdmin !== 'undefined' &&
		jocbmAdmin.ownerLibrary?.restBase ) ||
	( typeof jocbmPro !== 'undefined' &&
		jocbmPro.restBase ) ||
	'joc-blockora-morph-pro/v1';

const nonce = () =>
	( typeof jocbmAdmin !== 'undefined' && jocbmAdmin.nonce ) ||
	( typeof jocbmEditor !== 'undefined' && jocbmEditor.nonce ) ||
	'';

apiFetch.use( apiFetch.createNonceMiddleware( nonce() ) );

export const api = {
	get: ( path ) => apiFetch( { path: `/joc-blockora-morph/v1${ path }` } ),
	post: ( path, data ) =>
		apiFetch( { path: `/joc-blockora-morph/v1${ path }`, method: 'POST', data } ),
	put: ( path, data ) =>
		apiFetch( { path: `/joc-blockora-morph/v1${ path }`, method: 'PUT', data } ),
	del: ( path ) =>
		apiFetch( { path: `/joc-blockora-morph/v1${ path }`, method: 'DELETE' } ),
};

/** Owner Library REST (Pro namespace). */
export const ownerApi = {
	get: ( path ) => apiFetch( { path: `/${ ownerNs() }${ path }` } ),
	post: ( path, data ) =>
		apiFetch( {
			path: `/${ ownerNs() }${ path }`,
			method: 'POST',
			data,
		} ),
	put: ( path, data ) =>
		apiFetch( {
			path: `/${ ownerNs() }${ path }`,
			method: 'PUT',
			data,
		} ),
	del: ( path ) =>
		apiFetch( { path: `/${ ownerNs() }${ path }`, method: 'DELETE' } ),
};

export { root, ownerNs };
