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

'use strict';

const { getSnippetPlaceholder, getSnippetSourcePaths } = require( '../helpers/snippets' );

/**
 * Builds snippets based on collected data from Markdown files.
 *
 * All data are being gathered during conversion from Markdown to HTML (by Hexo).
 * See: `scripts/filter/after-post-render/snippets.js`.
 *
 * @param {Object} projectGlobals
 * @param {Object} projectGlobals.common
 * @param {Map<String, Set.<Snippet>>} projectGlobals.common._snippetsData
 * @param {Object} projectGlobals.common.snippetOptions
 * @returns {Promise}
 */
module.exports = function buildSnippets( projectGlobals ) {
	let promise = Promise.resolve();
	let hasErrors = false;

	for ( const [ projectName, snippetsCollection ] of projectGlobals.common._snippetsData ) {
		if ( !snippetsCollection.size ) {
			continue;
		}

		const snippetAdapter = projectGlobals[ projectName ].config.snippetAdapter;

		if ( !snippetAdapter ) {
			throw new Error( `Snippets for "${ projectName }" cannot be built because the "SnippetAdapter" has not been defined.` );
		}

		const umbertoHelpers = { getSnippetPlaceholder, getSnippetSourcePaths };

		promise = promise
			.then( () => {
				console.log( `Executing the snippet adapter for "${ projectName }".` );

				return snippetAdapter( snippetsCollection, projectGlobals.common.snippetOptions, umbertoHelpers );
			} )
			.catch( err => {
				console.error( err.stack );

				hasErrors = true;
				process.exitCode = 1;
			} );
	}

	return promise.then( () => {
		if ( hasErrors ) {
			throw new Error( 'Some error occurred during building snippets. Aborting.' );
		}
	} );
};
