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

module.exports = (env, argv) => {
  const isProduction = argv.mode === 'production';

  return {
    entry: './src/index.tsx',
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'bundle.js',
      clean: true,

      // Empty string generates relative paths that work through proxies
      publicPath: '',
    },
    resolve: {
      extensions: ['.ts', '.tsx', '.js', '.jsx'],
    },
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          exclude: /node_modules/,
          use: 'ts-loader',
        },
        {
          test: /\.css$/,
          use: [
            isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
            'css-loader',
            'postcss-loader',
          ],
        },
      ],
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: './src/index.html',
      }),
      ...(isProduction ? [new MiniCssExtractPlugin()] : []),
    ],
    devServer: {
      port: 3000,
      allowedHosts: 'all',
      historyApiFallback: {
        index: 'index.html',
      },
      // Disable WebSocket-based HMR for proxy compatibility
      // VS Code web proxy sends WebSocket messages as Blobs which breaks HMR
      webSocketServer: false,
      hot: false,
      liveReload: false,
      proxy: [
        {
          context: ['/api'],
          target: 'http://localhost:8001',
        },
      ],
    },
  };
};
