'use strict';
const path = require('path');
const utils = require('./utils');
const webpack = require('webpack');
const config = require('../config');
const { merge } = require('webpack-merge');
const baseWebpackConfig = require('./webpack.base.conf');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const { outputDir = 'dist', productionGzip = false } = config;

const webpackConfig = merge(baseWebpackConfig, {
  mode: 'production',
  devtool: false,
  optimization: {
    minimizer: [
      '...',
      new CssMinimizerPlugin(),
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'css/[name].[contenthash].css',
    }),
    new webpack.ids.HashedModuleIdsPlugin(),
  ],
});

const staticPath = path.resolve(__dirname, '../static');
if (utils.hasFile(staticPath)) {
  webpackConfig.plugins.push(
    new CopyWebpackPlugin({
      patterns: [
        {
          from: staticPath,
          to: path.resolve(__dirname, '..', outputDir, 'static'),
          info: { minimized: true },
          globOptions: {
            ignore: ['.*'],
          },
        },
      ],
    }),
  );
}

if (productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin');

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      filename: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
      threshold: 10240,
      minRatio: 0.8,
    }),
  );
}

if (process.env.npm_config_report) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}

module.exports = webpackConfig;
