const Encore = require("@symfony/webpack-encore");
const webpack = require("webpack");
const dotenv = require("dotenv").config();
const path = require("path");
const glob = require("glob-all");
const PurgeCssPlugin = require("purgecss-webpack-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const zlib = require("zlib");
const fs = require("fs");

process.env = process.env || {};
process.env.NODE_ENV = Encore.isProduction() ? "production" : "development";

Encore.setOutputPath("public/build/admin")
    .setPublicPath("/build/admin")
    .addEntry("serenity", [
        "./vendor/cpcreation/serenity-admin-bundle/assets/index.js",
        "./vendor/cpcreation/serenity-core-bundle/assets/index.js",
        "./assets/js/admin.js",
        "./assets/js/common.js",
    ])
    .enableStimulusBridge(
        "./assets/controllers.json",
    )
    .cleanupOutputBeforeBuild()
    .enableSassLoader()
    .enableSingleRuntimeChunk()
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction())
    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = "usage";
        config.corejs = 3;
    })
    .enablePostCssLoader((options) => {
        options.postcssOptions = {
            config: "./vendor/cpcreation/serenity-admin-bundle/postcss.admin.config.js",
        };
    });
if (!Encore.isProduction()) {
    Encore.configureDevServerOptions((options) => {
        options.server = {
            type: "https",
            options: {
                key: fs.readFileSync("/app/docker/tls/localhost-key.pem"),
                cert: fs.readFileSync("/app/docker/tls/localhost.pem"),
            },
        };
        options.allowedHosts = "all";
        options.host = "0.0.0.0";
        options.hot = false;
        options.liveReload = false;
        options.port = 8080;
        options.headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
            'Access-Control-Allow-Headers': 'X-Requested-With, content-type, x-window-id'
        };
    }).configureWatchOptions((watchOptions) => {
        watchOptions.ignored = [
            '**/node_modules/**',
            '**/public/build/**',
            '**/.git/**',
        ];
        watchOptions.poll = 250; // check for changes every 250 milliseconds
    });
}

let config = Encore.getWebpackConfig();

config.plugins.push(
    new webpack.DefinePlugin({
        "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
    }),
);

if (Encore.isProduction()) {
    /*Encore.addPlugin(
      new PurgeCssPlugin({
        paths: glob.sync([]),
        defaultExtractor: (content) => {
          return content.match(/[\w-/:]+(?<!:)/g) || [];
        },
      }),
    );*/
    config.optimization = {
        minimize: true,
        minimizer: [
            new TerserPlugin(),
            new CssMinimizerPlugin({minimizerOptions: {preset: ["default"]}}),
        ],
    };
    config.plugins.push(
        new CompressionPlugin({
            filename: "[path][base].gz",
            algorithm: "gzip",
            test: /\.(js|css|html|svg)$/,
            threshold: 10240,
            minRatio: 0.8,
        }),
        new CompressionPlugin({
            filename: "[path][base].br",
            algorithm: "brotliCompress",
            test: /\.(js|css|html|svg)$/,
            compressionOptions: {
                params: {
                    [zlib.constants.BROTLI_PARAM_QUALITY]: 11,
                },
            },
            threshold: 10240,
            minRatio: 0.8,
            deleteOriginalAssets: false,
        }),
    );
}

module.exports = config;
