/* eslint-disable @typescript-eslint/no-var-requires, no-undef, @typescript-eslint/no-explicit-any */
const { createProxyMiddleware } = require('http-proxy-middleware');
const http = require('http');

module.exports = function(app) {
  const base = process.env.PUBLIC_URL || '';
  console.log(`http-proxy-middleware ${base}`);

  // Keep-alive agent for websocket target to reduce connection churn
  const keepAliveAgent = new http.Agent({ keepAlive: true });

  app.use(createProxyMiddleware(
    `${base}/api/v1/games/ws`, {
      ws: true,
      target: 'ws://pok-server:8930',
      changeOrigin: true,
      // use a persistent agent so the proxy reuses sockets for upstream
      agent: keepAliveAgent,
      // disable proxy timeouts in dev so intermediate proxies don't drop idle WS
      proxyTimeout: 0,
      timeout: 0,
      pathRewrite: { [`^${base}`]: '' },
  }));

  app.use(createProxyMiddleware(
    `${base}/api`, {
      target: 'http://pok-server:8930',
      changeOrigin: true,
      // give HTTP API calls a longer timeout in dev
      proxyTimeout: 120000,
      timeout: 120000,
      pathRewrite: { [`^${base}`]: '' },
  }));
};
