const webpack = require("webpack");

const { griddoComponentsLibAliases } = require("../config/griddo-config");

const createConfig = ({ input, output }) => ({
	entry: input,
	output: {
		...output,
		library: "griddo",
		libraryTarget: "commonjs2",
	},
	resolve: {
		alias: {
			...griddoComponentsLibAliases,
		},
	},
	plugins: [new webpack.ProgressPlugin()],
	module: {
		rules: [
			{
				test: /\.m?[tj]s$/,
				resolve: { extensions: [".ts", ".js"] },
				exclude: /(node_modules|bower_components)/,
				use: {
					loader: "babel-loader",
					options: {
						presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-typescript"],
						plugins: ["@babel/plugin-transform-optional-chaining"],
					},
				},
			},

			// This is for ignoring images defined in the schemas in order to prevent
			// API crashing (it hasn't webpack)
			{
				test: /\.(png|jpe?g|gif)$/i,
				use: [{ loader: "ignore-loader" }],
			},
		],
	},
});

module.exports = (withExternalConfig) => {
	const config = createConfig(withExternalConfig);

	const compiler = webpack(config);

	return new Promise((resolve, reject) => {
		compiler.run((err, stats) => {
			if (err) {
				console.log(err);
				return reject(err);
			}

			if (stats.compilation.errors && stats.compilation.errors.length) {
				return reject(stats.compilation.errors[0]);
			}

			return resolve({
				stats,
			});
		});
	});
};
