/**
 * apiFetch helper that keeps admin REST responses in the current user locale.
 *
 * @package RawTypeOE
 */

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

const PLUGIN_REST_PREFIX = '/rawtype_oe/v1/';

export function withUserLocale( path ) {
	if ( 'string' !== typeof path || ! path.startsWith( PLUGIN_REST_PREFIX ) ) {
		return path;
	}

	const [ pathname, search = '' ] = path.split( '?' );
	const params = new URLSearchParams( search );

	if ( 'user' !== params.get( '_locale' ) ) {
		params.set( '_locale', 'user' );
	}

	const query = params.toString();

	return query ? `${ pathname }?${ query }` : pathname;
}

export default function apiFetchUserLocale( options ) {
	if ( ! options || 'object' !== typeof options || ! options.path ) {
		return apiFetch( options );
	}

	return apiFetch( {
		...options,
		path: withUserLocale( options.path ),
	} );
}
