const nodeExternals = require('webpack-node-externals');
const merge = require('webpack-merge');
const WebpackBar = require('webpackbar');

// local
const parts = require('../parts');
const commonConfig = require('../common');
const paths = require('../../paths');

const createConfig = config => {
  // const isProduction = config.mode === 'production';
  const isDevelopment = config.mode === 'development';

  return merge([
    {
      mode: config.mode,
      name: 'server',
      entry: {
        server: [paths.server],
      },
      target: 'node',
      // in prod we need the packages
      externals: config.prod ? [] : [nodeExternals({})],
    },
    parts.outputPath({
      path: paths.serverBuild,
      filename: 'server.js',
    }),
    // investigate why adding prod true destory ssr in prod
    parts.loadJavaScript(),
    // need css loader to not fail building
    parts.loadCSS(),
    parts.setVariables({
      __LOCALE__: isDevelopment,
      __DEV__: !config.prod,
      __STAGING__: config.staging || false,
      __BROWSER__: false,
      __SSR__: true,
      __TEST__: false,
    }),
    {
      plugins: [
        new WebpackBar({
          name: 'server',
          color: 'orange',
        }),
      ],
    },
  ]);
};

module.exports = env => {
  const config = createConfig({
    mode: env && env.prod ? 'production' : 'development',
    ...env,
  });
  // need common (images, font) to not fail the building process
  // mode : Possible values for mode are: none, development or production(default).
  return merge(config, commonConfig);
};
