/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

'use strict';

module.exports = ( { fullText, variables, pagePath } = {} ) => {
	const macros = new Set( fullText.match( /\{%\s?[A-Z_0-9]+?\s?%\}/g ) );
	let outputText = fullText;
	if ( !macros.size ) {
		return fullText;
	}
	if ( !variables ) {
		console.log( 'hello' );
		throw new Error( `Variables are not defined in umberto config, however there was detected macro usage on page: ${ pagePath }` );
	}
	macros.forEach( macro => {
		const name = macro.match( /\{%\s?([A-Z_0-9]+)\s?%\}/ )[ 1 ];
		if ( variables[ name ] === undefined ) {
			throw new Error( `Macro "${ macro }" used on page: ${ pagePath } doesn't have corresponding variable in configuration.` );
		}
		outputText = outputText.replace( new RegExp( macro, 'g' ), variables[ name ] );
	} );
	return outputText;
};
