'use strict';
process.env.NODE_ENV = 'development';
const utils = require('./utils');
const config = require('../config');
const { merge } = require('webpack-merge');
const path = require('path');
const baseWebpackConfig = require('./webpack.base.conf');
const FriendlyErrorsPlugin = require('@soda/friendly-errors-webpack-plugin');
const portfinder = require('portfinder');

const { port = '8080', publicPath = '/', devServerProxy } = config;

const devWebpackConfig = merge(baseWebpackConfig, {
  mode: 'development',
  devtool: 'eval-source-map',
  devServer: {
    client: {
      logging: 'warn',
      overlay: true,
      progress: true,
    },
    devMiddleware: {
      publicPath: publicPath,
    },
    onBeforeSetupMiddleware: function (devServer) {
      if (!devServer) {
        throw new Error('webpack-dev-server is not defined');
      }
      devServer.app.get('/', function (req, res) {
        res.redirect(publicPath);
      });
    },
    static: {
      directory: path.join(__dirname, '../static'),
      publicPath: path.posix.join(publicPath, 'static'),
    },
    historyApiFallback: {
      rewrites: [{ from: /.*/, to: path.posix.join(publicPath, 'index.html') }],
    },
    host: 'localhost',
    port: port,
    open: false,
    proxy: devServerProxy,
    watchFiles: {
      options: {
        usePolling: false,
      },
    },
  },
});

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = port;
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err);
    } else {
      devWebpackConfig.devServer.port = port;

      devWebpackConfig.plugins.push(
        new FriendlyErrorsPlugin({
          compilationSuccessInfo: {
            messages: [`Your application is running here: http://localhost:${port}`],
          },
          onErrors: utils.createNotifierCallback(),
        }),
      );

      resolve(devWebpackConfig);
    }
  });
});
