const { DefinePlugin } = require('@umijs/bundler-webpack/compiled/webpack');
const ENV_SHOULD_PASS = ['NODE_ENV', 'HMR', 'SOCKET_SERVER', 'ERROR_OVERLAY'];
const prefixRE = /^PANDA_APP_/;

function resolveDefine(opts) {
  const env = {};
  Object.keys(process.env).forEach(key => {
    if (prefixRE.test(key) || ENV_SHOULD_PASS.includes(key)) {
      env[key] = process.env[key];
    }
  });

  for (const key in env) {
    env[key] = JSON.stringify(env[key]);
  }

  const define = {};
  if (opts.define) {
    for (const key in opts.define) {
      define[key] = JSON.stringify(opts.define[key]);
    }
  }

  return {
    'process.env': env,
    ...define,
  };
}

async function addDefinePlugin(opts) {
  const { config, userConfig } = opts;
  config.plugin('define').use(DefinePlugin, [
    resolveDefine({
      define: userConfig.define || {},
    }),
  ]);
}

module.exports = {
  resolveDefine,
  addDefinePlugin,
};