import * as plugins from './plugins.js';

export class ProxyRouter {
  public reverseProxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];

  /**
   * sets a new set of reverse configs to be routed to
   * @param reverseCandidatesArg
   */
  public setNewProxyConfigs(reverseCandidatesArg: plugins.tsclass.network.IReverseProxyConfig[]) {
    this.reverseProxyConfigs = reverseCandidatesArg;
  }

  /**
   * routes a request
   */
  public routeReq(req: plugins.http.IncomingMessage): plugins.tsclass.network.IReverseProxyConfig {
    const originalHost = req.headers.host;
    if (!originalHost) {
      console.error('No host header found in request');
      return undefined;
    }
    // Strip port from host if present
    const hostWithoutPort = originalHost.split(':')[0];
    const correspodingReverseProxyConfig = this.reverseProxyConfigs.find((reverseConfig) => {
      return reverseConfig.hostName === hostWithoutPort;
    });
    if (!correspodingReverseProxyConfig) {
      console.error(`No config found for host: ${hostWithoutPort}`);
    }
    return correspodingReverseProxyConfig;
  }
}