/* global __dirname, require, module*/

const path = require('path');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const pkg = require('./package.json');

const banner = ` ${pkg.name} \n @version ${pkg.version}`;
const libraryName = 'watchtogether-sdk';

module.exports = (env, argv) => {
  const mode = argv.mode || 'development';
  const outputFile = mode === 'production' ? `${libraryName}.min.js` : `${libraryName}.js`;

  return {
    mode,
    entry: './src/index.js',
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: outputFile,
      library: {
        type: 'module'
      },
      module: true,
      environment: { module: true },
      globalObject: "typeof self !== 'undefined' ? self : this",
      publicPath: '',
    },
    experiments: {
      outputModule: true,
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader'
          }
        },
        {
          test: /\.worker\.js$/,
          use: [
            { loader: 'worker-loader', options: { inline: 'no-fallback' } },
          ]
        }
      ]
    },
    plugins: [
      new webpack.BannerPlugin(banner),
      new webpack.ProvidePlugin({
        process: 'process/browser',
        Buffer: ['buffer', 'Buffer'],
      }),
      new webpack.DefinePlugin({
        'typeof window': JSON.stringify('object'),
        'window': 'self',
      }),
    ],
    optimization: {
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            output: {
              comments: /@version/i
            }
          },
          extractComments: false
        })
      ]
    },
    resolve: {
      modules: ['node_modules', path.resolve('./src')],
      extensions: ['.js', '.json'],
      fallback: {
        "util": require.resolve("util/"),
        "stream": require.resolve("stream-browserify"),
        "buffer": require.resolve("buffer/"),
        "crypto": require.resolve("crypto-browserify"),
        "process": require.resolve("process/browser"),
      }
    },
    devtool: mode === 'development' ? 'source-map' : false,
  };
};
