/**
 * This file can be edited to customize webpack configuration.
 * To reset delete this file and rerun theia build again.
 */
// @ts-check
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const configs = require('./gen-webpack.config.js');
const nodeConfig = require('./gen-webpack.node.config.js');
const webpack = require('webpack');

/**
 * Expose bundled modules on window.theia.moduleName namespace, e.g.
 * window['theia']['@theia/core/lib/common/uri'].
 * Such syntax can be used by external code, for instance, for testing.
 */
configs[0].module.rules.push({
    test: /\.js$/,
    loader: require.resolve('@theia/application-manager/lib/expose-loader')
});

/**
 * Inject environment variables into the browser bundle
 * These are needed by ai-ide preferences to read default values
 */
configs[0].plugins.push(
    new webpack.DefinePlugin({
        'process.env.GITEA_API_URL': JSON.stringify(process.env.GITEA_API_URL || ''),
        'process.env.GITEA_API_TOKEN': JSON.stringify(process.env.GITEA_API_TOKEN || ''),
        'process.env.GITEA_USERNAME': JSON.stringify(process.env.GITEA_USERNAME || ''),
        'process.env.COOLIFY_API_URL': JSON.stringify(process.env.COOLIFY_API_URL || ''),
        'process.env.COOLIFY_API_TOKEN': JSON.stringify(process.env.COOLIFY_API_TOKEN || ''),
        'process.env.GOOGLE_API_KEY': JSON.stringify(process.env.GOOGLE_API_KEY || ''),
    })
);

// Copy vibn.css and the customised index.html into lib/frontend/ on every build
configs[0].plugins.push(
    new CopyWebpackPlugin({
        patterns: [
            {
                from: path.resolve(__dirname, 'vibn.css'),
                to: path.resolve(__dirname, 'lib', 'frontend', 'vibn.css'),
            },
            {
                from: path.resolve(__dirname, 'src-gen/frontend/index.html'),
                to: path.resolve(__dirname, 'lib', 'frontend', 'index.html'),
            },
        ]
    })
);

// Disable source maps and compression to keep memory under 2GB for local builds
// Source maps alone can double webpack's peak memory usage
if (process.env.THEIA_LOCAL_BUILD) {
    configs[0].devtool = false;
    configs[0].cache = false;
    // Remove CompressionPlugin — it holds all output in memory to gzip it
    configs[0].plugins = configs[0].plugins.filter(
        p => p.constructor.name !== 'CompressionPlugin'
    );
}

module.exports = [
    ...configs,
    nodeConfig.config
];
