const path = require('path');
const webpack = require('webpack');
const ESLintPlugin = require('eslint-webpack-plugin');
const dotenv = require('dotenv');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const packageJson = require('./package.json');

const env = dotenv.config().parsed;
const isDevelopment = env.NODE_ENV === 'development';

module.exports = {
  target: 'web',
  mode: isDevelopment ? 'development' : 'production',
  devtool: 'source-map',
  entry: {
    adalongWidget: {
      import: path.resolve(__dirname, 'src/adalongWidget.tsx'),
      filename: 'adalongWidget.js',
      library: {
        name: 'AdalongWidget',
        type: 'umd',
      },
    },
    adalongTrack: {
      import: path.resolve(__dirname, 'src/adalongTrack.ts'),
      filename: 'adalongTrack.js',
      library: {
        name: 'AdalongTrack',
        type: 'umd',
      },
    },
  },

  output: {
    path: path.resolve(__dirname, 'dist'),
    umdNamedDefine: true,
    globalObject: 'this', // Ensures it works in all environments
  },

  resolve: {
    modules: [path.resolve('./node_modules')],
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
    mainFields: ['browser', 'module', 'main'],
  },

  module: {
    rules: [
      {
        test: /\.ts(x?)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'ts-loader',
          },
        ],
      },
      // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'source-map-loader',
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },

  plugins: [
    new webpack.DefinePlugin({
      ENV: JSON.stringify({
        API_URL: env.API_URL,

      }),
      __WIDGET_VERSION__: JSON.stringify(packageJson.version),
    }),
    new ESLintPlugin(),
    ...(isDevelopment ? [new BundleAnalyzerPlugin()] : []),
  ],

  devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
    },
    hot: true,
    port: 9800,
  },
};
