import { Module } from '@nestjs/common';
import { AuthModule } from './module/auth/auth.module';
import { EurekaService, GatewayService, NacosService } from './service';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { getLocalIP } from './utils';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { notNilEmpty } from 'qx-util';
import {
  CodeListModule,
  DynamicModule,
  IBizConfigModule,
  IBizOUModule,
  IBizUAAModule,
  IBizUtilModule,
  R8RedirectModule,
  WorkflowModule,
} from './module';

/**
 * 核心模块
 *
 * @author chitanda
 * @date 2021-08-11 10:08:43
 * @export
 * @class CoreModule
 */
@Module({
  imports: [
    EventEmitterModule.forRoot({ maxListeners: 300 }),
    AuthModule,
    ConfigModule,
    CodeListModule,
    DynamicModule,
    IBizConfigModule,
    IBizOUModule,
    IBizUAAModule,
    IBizUtilModule,
    R8RedirectModule,
    WorkflowModule,
  ],
  exports: [
    EventEmitterModule,
    AuthModule,
    ConfigModule,
    CodeListModule,
    DynamicModule,
    IBizConfigModule,
    IBizOUModule,
    IBizUAAModule,
    IBizUtilModule,
    R8RedirectModule,
    WorkflowModule,
  ],
  providers: [
    {
      provide: 'GatewayRegisterCenterService',
      useFactory: async (configService: ConfigService) => {
        const gatewayMode: 'eureka' | 'nacos' | 'none' = configService.get('app.gatewayMode');
        if (gatewayMode === 'nacos') {
          const port = configService.get('app.port');
          const discoveryIp = configService.get('nacos.discoveryIp');
          const nacos = new NacosService(configService);
          await nacos.init();
          await nacos.registerInstance({
            ip: notNilEmpty(discoveryIp) ? discoveryIp : getLocalIP(),
            port: port,
          });
          GatewayService.getInstance().init(nacos);
          return nacos;
        } else if (gatewayMode === 'eureka') {
          const eureka = new EurekaService(configService);
          await eureka.start();
          GatewayService.getInstance().init(eureka);
          return eureka;
        } else {
          GatewayService.getInstance().init(null);
        }
      },
      inject: [ConfigService],
    },
  ],
})
export class CoreModule {}
