const merge = require('webpack-merge');
const WebpackBar = require('webpackbar');
const slsw = require('serverless-webpack');
const path = require('path');

// local
const CopyPlugin = require('copy-webpack-plugin');
const parts = require('../parts');
const commonConfig = require('../common');

const isLocal = slsw.lib.webpack.isLocal;
const stage = slsw.lib.options.stage;
const paths = require('../../paths');

// Parent package
const package = require('../../../../package.json');

let frontendUrl;
if (stage === 'production') {
  frontendUrl = package.deploy.production.frontendUrl;
} else if (stage === 'staging') {
  frontendUrl = package.deploy.staging.frontendUrl;
} else if (stage === 'dev') {
  frontendUrl = package.deploy.dev.frontendUrl;
} else {
  frontendUrl = package.deploy.locale.frontendUrl;
}

const createConfig = () =>
  merge([
    parts.clean(paths.slsServerBuild, paths.slsBuild),
    {
      mode: isLocal ? 'development' : 'production',
      // name: 'server',
      entry: slsw.lib.entries,
      target: 'node',
      // in prod we need the packages
      // externals: [nodeExternals()],
      output: {
        libraryTarget: 'commonjs2',
        path: paths.slsServerBuild,
        publicPath: frontendUrl || '/',
        //  path: path.join(__dirname, '.webpack'),
        filename: '[name].js',
      },
    },
    parts.loadJavaScript(),
    // need css loader to not fail building
    parts.loadCSS(),
    parts.setVariables({
      __LOCALE__: isLocal,
      __DEV__: stage === 'dev',
      __STAGING__: stage === 'staging',
      __BROWSER__: false,
      __SSR__: true,
      __TEST__: false,
    }),
    {
      plugins: [
        new CopyPlugin({
          patterns: [
            {
              from: path.join(paths.slsClientBuild, 'loadable-stats.json'),
              to: './loadable-stats-client.json',
              noErrorOnMissing: true,
            },
          ],
        }),
        new WebpackBar({
          name: 'server',
          color: 'orange',
        }),
      ],
    },
    {
      optimization: {
        minimize: false, // <---- disables uglify.
        nodeEnv: stage,
      },
    },
  ]);

// need common (images, font) to not fail the building process
const config = merge(createConfig(), commonConfig);

// Module export cannot be a function
module.exports = config;
