const path = require('path');
const webpack = require('webpack');
const loadEnv = require('./env-config');

module.exports = (env) => {
  console.log('env', env);
  const mode = env.WEBPACK_BUILD ? 'prod' : 'dev';
  const envVariables = loadEnv(mode);

  // Convert the environment variables to a format that webpack can use
  const envKeys = Object.keys(envVariables).reduce((prev, next) => {
    prev[`process.env.${next}`] = JSON.stringify(envVariables[next]);
    return prev;
  }, {});

  return {
    entry: './ui/index.tsx',
    output: {
      filename: 'js/bundle.js',
      path: path.resolve(__dirname, 'public'),
      publicPath: '/',
    },
    resolve: {
      extensions: ['.ts', '.tsx', '.js', '.jsx'],
      alias: {
        '@': path.resolve(__dirname, '.'),
      },
      fallback: {
        "os": false,
        "crypto": false,
        "fs": false,
        "path": false
      }
    },
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          use: 'ts-loader',
          exclude: /node_modules/,
        },
        {
          test: /\.css$/,
          use: ['style-loader', 'css-loader', 'postcss-loader'],
        },
        {
          test: /\.(png|svg|jpg|jpeg|gif|ico|woff|woff2|eot|ttf|otf)$/i,
          type: 'asset/resource',
          generator: {
            filename: (pathData) => {
              return pathData.filename.replace(/^public\//, '');
            }
          }
        },
      ],
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env': JSON.stringify(envVariables)
      }),
    ],
  };
};