const path = require('path');
const {pathToFileURL} = require('url');

/**
 * @param Encore
 * @param [options={}] - aliases and sassFilesToOverride parameters availables
 * @return {}
 */
module.exports = (Encore, options = {}) => {
  Encore
    .setOutputPath('public/build/dedi')
    .setPublicPath('/build/dedi')
    .addEntry('dedi', `${__dirname}/assets`)
    .addEntry('collection_form', `${__dirname}/assets/js/collection_form`)
    .addEntry('design-system', `${__dirname}/assets/js/design-system`)
    .addStyleEntry('styleguide', `${__dirname}/assets/scss/pages/styleguide.scss`)
    .addStyleEntry('homepage', `${__dirname}/assets/scss/pages/homepage.scss`)
    .addStyleEntry('account', `${__dirname}/assets/scss/pages/account.scss`)
    .addStyleEntry('shop', `${__dirname}/assets/scss/pages/shop.scss`)
    .addStyleEntry('process', `${__dirname}/assets/scss/pages/process.scss`)
    .addAliases(Object.assign({
      vendor: path.resolve(__dirname, 'node_modules'),
      fonts: path.resolve(__dirname, 'assets/fonts'),
      media: path.resolve(__dirname, 'assets/media'),
    }, options.aliases || {}))
    .autoProvidejQuery()
    .autoProvideVariables({
      popper: 'popper.js/dist/popper.min',
      lightbox: 'lightbox2/dist/js/lightbox.min',
      bootstrap: 'bootstrap/dist/js/bootstrap.min',
    })
    .copyFiles({
      from: `${__dirname}/assets/media`,
      to: 'images/[path][name].[ext]',
    })
    .copyFiles({
      from: `${__dirname}/assets/fonts`,
      to: 'fonts/[path][name].[ext]',
    })
    .disableSingleRuntimeChunk()
    .cleanupOutputBeforeBuild()
    /** Override sass file if option exists, else keep dedi theme file **/
    .enableSassLoader((opt) => {
      opt.api = 'modern';
      opt.sassOptions = Object.assign(opt.sassOptions || {}, {
        importers: [{
          findFileUrl(url) {
            if (url.startsWith('~')) {
              return new URL(url.substring(1), pathToFileURL(`${__dirname}/node_modules/`));
            }

            url = url.replace('deditheme/', '');

            if (options.sassFilesToOverride) {
              if (options.sassFilesToOverride[url]) {
                const path = options.sassFilesToOverride[url].replace('.scss', '').replace(url, '');
                return new URL(url, pathToFileURL(path));
              }
            }

            return new URL(url, pathToFileURL(`${__dirname}/assets/scss/`));
          }
        }]
      });

      return opt;
    })
    .enableSourceMaps(!Encore.isProduction())
    .enableVersioning(Encore.isProduction());

  const config = Encore.getWebpackConfig();
  config.name = 'dedi';

  return config;
};
