const webpack = require('webpack');
const WorkBoxPlugin = require('workbox-webpack-plugin');

// NOTE on Astryx + StyleX custom styling (xstyle / stylex.create()):
// @stylexjs/babel-plugin alone only transforms the JS call sites — it does
// NOT inject the generated CSS. That requires a matching bundler plugin
// (@stylexjs/webpack-plugin), which is stuck at 0.11.1 and pins its own
// internal @stylexjs/babel-plugin@0.11.1 — two majors behind the 0.19.x
// core that this Astryx version requires, so the two would hash class
// names differently and produce the exact same "styled but invisible"
// bug either way. Until StyleX's webpack tooling catches up (or we write
// a custom metadata-collecting loader), custom Astryx styling is limited
// to component props; anything a prop can't express uses a plain native
// element with an inline `style` (StyleX-free, so it isn't affected).
// See themes/astryx.js and pages/nearle/login.js.

module.exports = function override(config) {
  // @astryxdesign/core ships as ESM with relative imports missing extensions
  // (e.g. '../Tooltip/Tooltip'), which webpack 5 rejects under strict ESM
  // resolution. Relax it for this package only rather than globally.
  config.module.rules.push({
    test: /\.m?js$/,
    include: /node_modules[\\/]@astryxdesign/,
    resolve: { fullySpecified: false }
  });

  config.resolve.fallback = {
    process: require.resolve('process/browser'),
    // zlib: require.resolve('browserify-zlib'),
    stream: require.resolve('stream-browserify'),
    crypto: require.resolve('crypto-browserify'),
    util: require.resolve('util'),
    buffer: require.resolve('buffer')
    // asset: require.resolve('assert')
  };

  // https://stackoverflow.com/questions/69135310/workaround-for-cache-size-limit-in-create-react-app-pwa-service-worker
  config.plugins.forEach((plugin) => {
    if (plugin instanceof WorkBoxPlugin.InjectManifest) {
      plugin.config.maximumFileSizeToCacheInBytes = 50 * 1024 * 1024;
    }
  });

  config.plugins = [
    ...config.plugins,
    new webpack.ProvidePlugin({
      process: 'process/browser.js',
      Buffer: ['buffer', 'Buffer']
    })
  ];
  config.watchOptions = {
    ignored: /node_modules/, // Ignore node_modules
    aggregateTimeout: 300,
    poll: 1000 // Enable polling for changes
  };
  config.devServer = {
    ...config.devServer,
    hot: true, // Enable hot reload explicitly
    watchFiles: ['src/**/*'] // Make sure Webpack watches all files
  };

  return config;
};
