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

'use strict';

const { styleText } = require( 'util' );
const fs = require( 'fs' );
const upath = require( 'upath' );
const getProjectConfig = require( './get-project-config' );

module.exports = async ( {
	mainConfig,
	rootPath,
	isSingleProject = false
} ) => {
	const configs = [];

	if ( isSingleProject ) {
		configs.push( await getProjectConfig( rootPath, { skipLiveSnippets: true } ) );
	} else {
		const promises = mainConfig.projects.map( projectPath => {
			return getProjectConfig( upath.join( rootPath, projectPath ), { skipLiveSnippets: true } );
		} );
		configs.push( ...await Promise.all( promises ) );
	}

	configs
		.filter( config => config.version !== 'latest' )
		.forEach( config => {
			createSymbolicLink( config );
		} );

	return Promise.resolve();

	function createSymbolicLink( { slug, name, version } ) {
		const destinationPath = upath.join( rootPath, 'build', 'docs', slug, 'latest' );

		if ( !fs.existsSync( destinationPath ) ) {
			// The 3rd argument to the fs.symlinkSync() method is the link type and it is only available
			// on Windows (it is ignored on other platforms). Creating a symlink to a directory with link
			// type = 'dir' requires admin privileges on Windows. The only way to create a directory symlink
			// without admin privileges on Windows is to use the 'junction' link type.
			fs.symlinkSync( version, destinationPath, 'junction' );
			console.log( `Symlink for ${ styleText( 'cyanBright', name ) } ${ styleText( 'magentaBright', './' + version ) } - created.` );
		}
	}
};
