import {
  StylableWebpackPlugin,
  applyWebpackConfigStylableExcludes,
} from '@stylable/webpack-plugin';
import { StylableOptimizer } from '@stylable/optimizer';
import { Configuration } from 'webpack';

const stylableOptimizer = new StylableOptimizer();
const packages = [
  '@wix/design-system',
  '@wix/patterns',
  '@wix/wix-style-react-incubator',
];

type ExternalItemFunctionDataFn = Extract<
  Configuration['externals'],
  (data: any) => any
>;

export const decorateNextJsWebpackConfig = (
  config: Configuration,
  { isServer }: { isServer: boolean },
) => {
  // causes provided packages to be bundled (not external)
  if (isServer && Array.isArray(config.externals)) {
    const nextExternals = config.externals[0] as ExternalItemFunctionDataFn;

    config.externals = [
      async (ctx) => {
        for (const pack of packages) {
          if (ctx.request?.startsWith(pack)) {
            return false;
          }
        }

        return nextExternals(ctx);
      },
    ] as ExternalItemFunctionDataFn[];
  }

  // excludes other configs from attempting to handle stylable files
  applyWebpackConfigStylableExcludes(config);

  config.plugins = config.plugins ?? [];

  config.plugins.push(
    new StylableWebpackPlugin({
      assetFilter: () => false,
      filename: 'static/css/stylable.[contenthash].css',
      optimizer: stylableOptimizer,
    }),
  );

  return config;
};
