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

'use strict';

const path = require( 'path' );
const webpack = require( 'webpack' );

module.exports = ( sourceFile, destinationFile, {
	minify = true,
	outputFileName = 'app.js',
	umbertoDir,
	version,
	basePath = '/docs'
} = {} ) => {
	const webpackConfig = {
		context: umbertoDir,

		mode: minify ? 'production' : 'development',

		entry: path.resolve( sourceFile ),

		output: {
			filename: outputFileName,
			path: path.resolve( destinationFile )
		},

		target: 'web',

		optimization: {
			minimize: minify
		},

		// Increased the size of the allowed assets two times to hide the warning in the console.
		performance: {
			hints: false,
			maxEntrypointSize: 500000,
			maxAssetSize: 500000
		},

		plugins: [
			new webpack.DefinePlugin( {
				VERSION: `"${ version }"`,
				BASE_PATH: JSON.stringify( basePath )
			} )
		],

		module: {
			rules: [
				{
					test: /\.js$/,
					use: {
						loader: 'babel-loader',
						options: {
							presets: [
								require.resolve( '@babel/preset-env' )
							]
						}
					}
				}
			]
		}
	};

	if ( !minify ) {
		webpackConfig.devtool = 'source-map';
	}

	return new Promise( ( resolve, reject ) => {
		console.log( `Running webpack for "${ outputFileName }"...` );

		webpack( webpackConfig, ( err, stats ) => {
			if ( err ) {
				reject( err );
			} else if ( stats.hasErrors() ) {
				reject( new Error( stats.toString() ) );
			} else {
				console.log( '[Webpack]', stats.toString( 'minimal' ) );

				resolve();
			}
		} );
	} );
};
