const path = require( 'path' );
const defaultConfig = require( '@wordpress/scripts/config/webpack.config' );
const DependencyExtractionWebpackPlugin = require( '@wordpress/dependency-extraction-webpack-plugin' );

const cliqUi = path.resolve( __dirname, 'vendor/cliqthemes/ui' );
const isFrontend = process.env.BUILD_TARGET === 'frontend';
const bundledPreactRequests = [
	'react',
	'react-dom',
	'react-dom/client',
	'react/jsx-runtime',
	'@wordpress/element',
];

const config = {
	...defaultConfig,
	resolve: {
		...( defaultConfig.resolve || {} ),
		modules: [ path.resolve( __dirname, 'node_modules' ), 'node_modules' ],
		alias: {
			...( defaultConfig.resolve?.alias || {} ),
			'@cliqui': path.join( cliqUi, 'resources' ),
		},
	},
};

if ( isFrontend ) {
	config.entry = {
		shared: path.resolve(
			__dirname,
			'resources/frontend/src/entries/shared.js'
		),
		locator: {
			import: path.resolve(
				__dirname,
				'resources/frontend/src/entries/locator.js'
			),
			dependOn: 'shared',
		},
	};
	config.output = {
		...( config.output || {} ),
		filename: '[name].js',
		chunkFilename: 'chunks/[name].[contenthash:8].js',
		clean: true,
	};
	config.resolve.alias = {
		...config.resolve.alias,
		react: 'preact/compat',
		'react-dom': 'preact/compat',
		'react-dom/client': 'preact/compat',
		'react/jsx-runtime': 'preact/jsx-runtime',
		'@wordpress/element': 'preact/compat',
	};
	config.plugins = [
		...defaultConfig.plugins.filter(
			( plugin ) =>
				! ( plugin instanceof DependencyExtractionWebpackPlugin )
		),
		new DependencyExtractionWebpackPlugin( {
			requestToExternal( request ) {
				return bundledPreactRequests.includes( request )
					? false
					: undefined;
			},
		} ),
	];
}

module.exports = config;
