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

const upath = require( 'upath' );
const fs = require( 'fs/promises' );

const XMLNS_STRINGS = [
	'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"',
	'xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"',
	'xmlns:xhtml="http://www.w3.org/1999/xhtml"',
	'xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"',
	'xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"'
];

/**
 * Creates a sitemap.xml file and saves it to build directory.
 *
 * @param {Object} options
 * @param {String} options.buildPath Path to the build directory.
 * @param {String} options.hostname Hostname of the website where the documentation will be hosted.
 * @param {Array.<string>} options.sitemapPaths Paths to generated sitemap files.
 * @returns {Promise}
 */
module.exports = ( { buildPath, hostname, sitemapPaths } ) => {
	const sitemapPath = upath.resolve( upath.join( buildPath, 'sitemap.xml' ) );
	const sitemapIndexContent = [
		'<?xml version="1.0" encoding="UTF-8"?>',
		`<sitemapindex ${ XMLNS_STRINGS.join( ' ' ) }>`,

		...sitemapPaths.map( sitemapPath => {
			const relativePath = sitemapPath.split( buildPath ).pop().replace( /^\/+/, '' );
			const fullUrl = new URL( relativePath, hostname.endsWith( '/' ) ? hostname : hostname + '/' );

			return [
				'<sitemap>',
				`<loc>${ fullUrl.toString() }</loc>`,
				'</sitemap>'
			];
		} ),

		'</sitemapindex>'
	].flat().join( '' );

	return fs.writeFile( sitemapPath, sitemapIndexContent, 'utf8' );
};
