const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCSSExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const webpack = require('webpack');

module.exports = (env) => {
  // Корневая директория проекта
  const rootDir = path.resolve(__dirname, '../');

  return {
    context: path.resolve(process.cwd()), // Корень проекта
    entry: './src/index.js', // Относительный путь от контекста
    output: {
      hashFunction: 'xxhash64',
      filename: 'bundle.js',
      path: path.resolve(process.cwd(), 'dist')
    },
    resolve: {
      extensions: ['.js', '.ts'],
      symlinks: true, // Включает поддержку символических ссылок
      alias: {
        services: path.resolve(process.cwd(), 'services'),
        utils: path.resolve(process.cwd(), 'utils'),
        extensions:  path.resolve(process.cwd(), 'extensions'),
        decorators: path.resolve(process.cwd(), 'decorators'),
        base: path.resolve(process.cwd(), 'base')
      },
      modules: [
        path.resolve(rootDir), // Убедитесь, что пути абсолютные
        'node_modules',
      ],
    },
    plugins: [
      new CopyWebpackPlugin({
        patterns: [
          { from: path.resolve(process.cwd(), 'src/assets') },
          { from: path.resolve(process.cwd(), 'public/imgs') },
          { from: path.resolve(__dirname, '../assets')},
        ],
      }),
      new HtmlWebpackPlugin({
        template: path.resolve(process.cwd(), 'public/index.html'),
        minify: true
      }),
      new MiniCSSExtractPlugin(),
      new webpack.DefinePlugin({
        __VERSION: JSON.stringify(require(path.resolve(process.cwd(), 'package.json')).version),
        __STORAGE_ID: JSON.stringify(require(path.resolve(process.cwd(), 'package.json')).storageId),
      }),
    ],
    module: {
      rules: [
        {
          test: /\.css$/i,
          use: ['style-loader', 'css-loader'],
        },
        // JS
        {
          test: /\.js$|\.jsx$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/env', '@babel/react'],
            },
          },
        },
        // Images
        {
          test: /\.(jpg|png|webp|gif|svg|mp3)$/,
          type: 'asset/resource',
          generator: {
            filename: 'assets/images/[hash][ext]',
          },
        },
        // Sounds
        {
          test: /\.(mp3|ogg)$/,
          type: 'asset/resource',
          generator: {
            filename: 'assets/sounds/[hash][ext]',
          },
        },
        // Fonts
        {
          test: /\.(ttf|eot|woff|woff2|otf)$/,
          type: 'asset/resource',
          generator: {
            filename: 'assets/fonts/[hash][ext]',
          },
        },
      ],
    },
    optimization: {
      splitChunks: {
        chunks: 'async',
        minSize: 20000,
        minRemainingSize: 0,
        minChunks: 1,
        maxAsyncRequests: 30,
        maxInitialRequests: 30,
        enforceSizeThreshold: 50000,
        cacheGroups: {
          defaultVendors: {
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
            reuseExistingChunk: true,
          },
          default: {
            minChunks: 2,
            priority: -20,
            reuseExistingChunk: true,
          },
        },
      },
    },
  };
};
