const path = require('path');
const { merge } = require('webpack-merge');
const commonConfiguration = require('./webpack.common.js');
const ip = require('ip');
const portFinderSync = require('portfinder-sync');
const fs = require("fs");

const infoColor = (_message) => {
  return `\u001b[1m\u001b[34m${_message}\u001b[39m\u001b[22m`;
};

module.exports = (env) => {
  return merge(
    commonConfiguration(env),
    {
      devtool: 'source-map',
      stats: 'errors-warnings',
      mode: 'development',
      infrastructureLogging:
      {
        level: 'warn',
      },
      snapshot: { managedPaths: [] },
      devServer:
      {
        // host: 'local-ip',
        port: portFinderSync.getPort(3000),
        open: true,
        https: false,
        allowedHosts: 'all',
        hot: false,
        //watchFiles: ['./',],
        client:
        {
          logging: 'none',
          overlay: true,
          progress: false,
        },
        setupMiddlewares: function (middlewares, devServer) {
          const port = devServer.options.port;
          const https = devServer.options.https ? 's' : '';
          const localIp = ip.address();
          const domain1 = `http${https}://${localIp}:${port}`;
          const domain2 = `http${https}://localhost:${port}`;

          console.log(`Project running at:\n  - ${infoColor(domain1)}\n  - ${infoColor(domain2)}`);

          return middlewares;
        },
        proxy: { // used to be able to send cookies via fetch
          "/proxy": {
            target: "https://dev.popiplay.dev",
            changeOrigin: true,
            secure: false,
            pathRewrite: { "^/proxy": "" }, // removes "/proxy" before redirection
            cookieDomainRewrite: "localhost",
            
            // dynamic replace
            router: (req) => {
              const cookieHeader = req.headers.cookie || "";
              const match = cookieHeader.match(/proxy_target=([^;]+)/);
              const target = match ? ("https://" + decodeURIComponent(match[1])) : "https://dev.popiplay.dev";
              // console.error(`[proxy][router] ${req.method} ${req.url} -> ${target}`);
              // console.error(`[proxy][router] ${target}`);
              return target;
            },
          },
        },
      },
    },
  );
}
