const path = require('path')
const dotenv = require('dotenv')
const { merge } = require('webpack-merge')
const common = require('./webpack.common.js')

const envConfig = dotenv.config()

const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const webpack = require('webpack')

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 fs = require('fs')
const devConfig = require('../dev.config.js')
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 isProduction = argv.mode === 'production'
	const buildPath = process.env.BUILD_PATH || 'out_wc'
	const generateSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'

	const commonConfig = common(env, argv)

	return merge(commonConfig, {
		entry: path.resolve(__dirname, '..', 'src', 'index-wc.js'),

		output: {
			path: path.resolve(__dirname, '..', buildPath),
			filename: 'static/js/x-store.js',
			assetModuleFilename: 'static/media/[name].[hash][ext]',
			clean: true,
			publicPath: '/',
		},

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

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

			new MiniCssExtractPlugin({
				filename: 'static/css/x-store.css',
			}),

			new webpack.optimize.LimitChunkCountPlugin({
				maxChunks: 1,
			}),
		],

		optimization: {
			splitChunks: false,
		},

		devtool: isProduction
			? generateSourceMap
				? 'source-map'
				: false
			: 'eval-source-map',

		devServer: {
			historyApiFallback: true,
		},
	})
}
