import path from 'path';
import TerserPlugin from 'terser-webpack-plugin';

/**@type {import('webpack').Configuration} */
export default {
  mode: 'none', // this leaves the source code as close as possible to the original (when packaging we set this to 'production')
  context: import.meta.dirname,
  target: ['web', 'es2020'],
  entry: './src/panel/chat/chat.tsx',
  experiments: { outputModule: true },
  output: {
    path: path.resolve(import.meta.dirname, 'out'),
    filename: 'media/chat.js',
    libraryTarget: 'module',
    chunkFormat: 'module',
  },
  resolve: {
    mainFields: ['module', 'main'],
    extensions: ['.ts', '.js', '.tsx', '.jsx'],
    alias: {
      react: path.resolve(import.meta.dirname, './node_modules/react'),
      'react-dom': path.resolve(
        import.meta.dirname,
        './node_modules/react-dom',
      ),
      '@exa/design-system/src': path.resolve(
        import.meta.dirname,
        './node_modules/@exa/design-system/dist',
      ),
      '@exa/api-server-connect-ts/src': path.resolve(
        import.meta.dirname,
        './node_modules/@exa/api-server-connect-ts/dist',
      ),
    },
    fallback: {
      tty: false,
    },
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: [
            '@babel/preset-env',
            ['@babel/preset-react', { runtime: 'automatic' }],
            '@babel/preset-typescript',
          ],
        },
      },
      {
        test: /\.css$/i,
        exclude: [/node_modules/],
        include: path.resolve(import.meta.dirname, 'src/panel/chat'),
        use: ['style-loader', 'css-loader', 'postcss-loader'],
      },
    ],
  },
  optimization: {
    sideEffects: false,

    // This will be enabled when building in `production`, making the minimizer effective.
    minimize: false,
    minimizer: [
      new TerserPlugin({
        parallel: true,
      }),
    ],
  },
  performance: {
    maxEntrypointSize: 15728640, // 15MB in bytes (increased from 10MB)
    maxAssetSize: 15728640, // 15MB in bytes (increased from 10MB)
  },
  // generate source maps for Sentry
  devtool: 'source-map',
};
