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

const { styleText } = require( 'util' );
const createSitemap = require( './create-sitemap' );
const createSitemapIndex = require( './create-sitemap-index' );

const BUILD_PATH = 'build/docs';

/**
 * This build step handles sitemap building.
 *
 * @param {Object} options
 * @param {Object} options.mainConfig
 * @param {Object} options.projectConfigs
 * @param {Object} options.verbose
 */
module.exports = async function createSitemapStep( { mainConfig, projectConfigs, verbose } ) {
	if ( mainConfig.isSingleProject ) {
		// If available, use sitemap config from umberto-main.json.
		// Use sitemap config from umberto.json otherwise.
		const config = projectConfigs && projectConfigs.length > 0 ? projectConfigs[ 0 ] : {};
		const sitemapConfig = mainConfig.sitemap ? mainConfig.sitemap : config.sitemap;

		if ( !sitemapConfig ) {
			return missingSitemapWarning( verbose );
		}

		if ( !sitemapConfig.enabled ) {
			if ( verbose ) {
				console.log(
					styleText( 'yellow', 'Warning: ' ),
					'To enable generating a sitemap.xml file, add the "enabled: true" property to "sitemap" configuration.'
				);
			}

			return;
		}

		return createSitemap( {
			buildPath: BUILD_PATH,
			projectSlug: config.slug,
			projectVersion: config.version,
			hostname: sitemapConfig.hostname,
			excluded: sitemapConfig.excluded || []
		} );
	}

	if ( !mainConfig.sitemap ) {
		return missingSitemapWarning( verbose );
	}

	const { hostname } = mainConfig.sitemap;

	const promises = projectConfigs.map( projectConfig => {
		const excluded = [];

		if ( mainConfig.sitemap?.excluded ) {
			excluded.push( ...mainConfig.sitemap.excluded );
		}

		if ( projectConfig.sitemap?.excluded ) {
			excluded.push( ...projectConfig.sitemap.excluded );
		}

		return createSitemap( {
			hostname,
			projectSlug: projectConfig.slug,
			projectVersion: projectConfig.version,
			buildPath: BUILD_PATH,
			excluded
		} );
	} );

	const sitemapPaths = await Promise.all( promises );

	// Generate the sitemap index only if all projects are being built.
	if ( !mainConfig.ignoredProjects.length ) {
		// To collect the HTML files from the build root directory.
		const rootSitemap = await createSitemap( {
			buildPath: BUILD_PATH,
			hostname,
			excluded: mainConfig.sitemap?.excluded || [],
			fileName: 'sitemap-root.xml'
		} );

		await createSitemapIndex( {
			buildPath: BUILD_PATH,
			hostname,
			sitemapPaths: [
				rootSitemap,
				...sitemapPaths
			]
		} );
	}
};

function missingSitemapWarning( verbose ) {
	if ( !verbose ) {
		return;
	}

	console.log( styleText( 'yellow', 'Warning: ' ), 'Not enough data to create a sitemap.xml file.' );
}
