const path = require('path');
const webpack = require('webpack');
const AssetsWebpackPlugin = require('assets-webpack-plugin');
const merge = require('webpack-merge').merge;
const wpConfig = require('./webpack.config.json');

let env = process.env.NODE_ENV || 'development';
const devMode = env === 'development';
const outputPath = path.join(__dirname, wpConfig.buildDir);
const publicPath = '/' + wpConfig.buildDir + '/';

const baseConfig = {
	entry: wpConfig.entry,
	mode: devMode ? 'development' : 'production',
	output: {
		path: outputPath,
		publicPath: publicPath
	},
	module: {
		rules: [
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader'],
			}, {
				test: /\.yml$/,
				use: ['json-loader', 'yaml-loader']
			}, {
				test: /\.xml$/,
				use: 'raw-loader'
			}, {
				test: /\.ttf$/,
				type: 'asset/resource'
			}, {
				test: /\.scss$/,
				use: [
					'style-loader',
					'css-loader',
					{
						loader: 'sass-loader',
						options: {
							sourceMap: true
						}
					}
				]
			}
		]
	},
	resolve: {
		modules: [
			__dirname +'/js',
			__dirname,
			'node_modules',
			'/usr/lib/node_modules'
		]
	},
	node: {
		__dirname: true
	},
	plugins: [
		new AssetsWebpackPlugin({
			path: outputPath
		}),
		new webpack.DefinePlugin({
			_DEV_MODE: devMode,
			_DEV_SERVER_PORT: wpConfig.devServerPort,
			_PUBLIC_PATH: JSON.stringify(publicPath)
		})
	],
	optimization: {
		runtimeChunk: true,
		splitChunks: {
			chunks: 'all',
		}
	},
	watchOptions: {
		ignored: /node_modules/
	}
};

const prodConfig = {
	output: {
		filename: '[name].[chunkhash].js',
		chunkFilename: 'chunk.[id].[chunkhash].js'
	},
	optimization: {
		moduleIds: 'deterministic'
	},
	devtool: 'source-map'
};

const devConfig = {
	output: {
		filename: '[name].js',
		chunkFilename: 'chunk.[id].js'
	},
	optimization: {
		moduleIds: 'named'
	},
	devServer: {
		host: '0.0.0.0',
		static: __dirname,
		port: wpConfig.devServerPort,
		headers: {'Access-Control-Allow-Origin': '*'},
		//stats: { chunks: false },
		proxy: {
			'/api': 'http://localhost:3000',
			'/': {
				target: 'http://localhost/projects/hedera-web',
				bypass: (req) => req.path !== '/' ? req.path : null
			}
		}
	},
	devtool: 'eval'
};

const mrgConfig = devMode ? devConfig : prodConfig;
module.exports = merge(baseConfig, mrgConfig);