import { config } from '../../../config';
import { Environment } from '@/environment';
import { MiddlewareConsumer, Module, NestMiddleware, NestModule } from '@nestjs/common';
import { createProxyMiddleware, RequestHandler } from 'http-proxy-middleware';

export class BaseAccMiddleware implements NestMiddleware {
  /**
   * 代理对象
   *
   * @author chitanda
   * @date 2021-12-10 19:12:38
   * @protected
   * @type {RequestHandler}
   */
  protected proxy?: RequestHandler;

  use(req: any, res: any, next: () => void): void {
    if (!this.proxy) {
      const pathKey = `^${Environment.BasePath}/`;
      const path = `/`;
      this.proxy = createProxyMiddleware({
        target: config.dynamic?.address,
        changeOrigin: true,
        pathRewrite: { [pathKey]: path },
      });
    }
    const url: string = req.originalUrl;
    const urls = url.split('/');
    const newUrls: string[] = [];
    urls.forEach((str, i) => {
      newUrls.push(str);
      if (i === 2) {
        newUrls.push('PSSYSAPPS');
        newUrls.push(config.dynamic?.appName);
      }
    });
    req.originalUrl = newUrls.join('/');
    this.proxy(req, res, next);
  }
}

@Module({})
export class DynamicModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(BaseAccMiddleware).forRoutes('dynamodel/(.*)');
  }
}
