const { merge } = require('webpack-merge')
const path = require('path')
const dotenv = require('dotenv')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const common = require('./webpack.common.js')
const production = require('./webpack.production.js')
const webcomponent = require('./webpack.webcomponent.js')

const envConfig = dotenv.config()
const fs = require('fs')
const devConfig = require('../dev.config.js')

let ASSET_PATH =
	envConfig.parsed?.REACT_APP_ASSET_PREFIX ||
	process.env.REACT_APP_ASSET_PREFIX ||
	'/'

const serverUrl = process.env.REACT_APP_USTORE_REMOTE_SERVER_URL || ''
const xmpieBuild = fs.existsSync(
	path.resolve(__dirname, '..', '..', 'config.json')
)
const themeConfig = require(xmpieBuild
	? path.resolve(__dirname, '..', '..', 'config.json')
	: path.resolve(
			__dirname, '..', 'src', devConfig.themes || 'AquaBlue', 'config.json'
	  ))
const buildVersion = themeConfig.uStoreVersion || Date.now()

module.exports = (env, argv) => {
	const isWebComponent = process.env.REACT_APP_WEB_COMPONENT === '1'
	const isProduction = argv.mode === 'production'

	let config

	if (isWebComponent) {
		config = webcomponent(env, argv)
	} else if (isProduction) {
		config = production(env, argv)
	} else {
		config = merge(common(env, argv), {
			entry: path.resolve(__dirname, '..', 'src', 'index.js'),

			output: {
				path: path.resolve(__dirname, '..', process.env.BUILD_PATH || 'out'),
				filename: 'static/js/[name].js',
				assetModuleFilename: 'static/media/[name].[hash][ext]',
				clean: true,
				publicPath: `${ASSET_PATH}${ASSET_PATH.endsWith('/') ? '' : '/'}`,
			},

			module: {
				rules: [
					{
						test: /\.css$/,
						use: ['style-loader', 'css-loader'],
					},
					{
						test: /\.s[ac]ss$/i,
						use: [
							'style-loader',
							'css-loader',
							{
								loader: 'sass-loader',
								options: {
									sassOptions: {
										loadPaths: devConfig.includeCssPaths,
									},
								},
							},
						],
					},
				],
			},

			plugins: [
				new HtmlWebpackPlugin({
					template: path.resolve(
						__dirname, '..', 'public', 'index.template.html'
					),
					filename: 'index.html',
					inject: true,
					templateParameters: {
						REACT_APP_ASSET_PREFIX: ASSET_PATH,
						REACT_APP_USTORE_REMOTE_SERVER_URL: serverUrl,
						buildVersion: buildVersion,
					},
				}),

				new CopyPlugin({
					patterns: [
						{
							from: path.resolve(
								__dirname, '..', 'src', 'ustore-internal', 'static'
							),
							to: 'static-internal',
						},
					],
				}),
			],

			devtool: 'eval-source-map',

			devServer: {
				historyApiFallback: false,
			},
		})
	}

	return config
}
