import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import compression from 'fastify-compress';
import { ConfigService } from '@nestjs/config';
import { Environment } from './environment';
import { notNilEmpty } from 'qx-util';
import FastifyMultipart from 'fastify-multipart';
import FastifyCookie from 'fastify-cookie';
import FastifyStatic from 'fastify-static';
import { resolve } from 'path';

function registerConfig(configService: ConfigService<any>) {
  const enableRuntime = configService.get<boolean>('runtime.enable');
  if (notNilEmpty(enableRuntime)) {
    Environment.EnableRuntime = enableRuntime;
  }
  const defaultAddress = configService.get<string>('default_api.address');
  Environment.DefaultAPI.Address = defaultAddress || '';
  const defaultPath = configService.get<string>('default_api.path');
  Environment.DefaultAPI.Path = defaultPath || '';
  const enableR8APIMode = configService.get<boolean | string>('ibiz.r8ApiMode');
  Environment.EnableR8APIMode = enableR8APIMode === true || enableR8APIMode === 'true' ? true : false;
  const staticRoute = configService.get<string>('static.route');
  Environment.Static.Route = staticRoute || '/';
  const staticPath = configService.get<string>('static.path');
  Environment.Static.Path = staticPath || 'resources/app';
}

/**
 * 启动应用
 *
 * @author chitanda
 * @date 2021-08-17 20:08:22
 */
async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter({ maxParamLength: 1000 }));
  app.register(FastifyMultipart, {
    addToBody: true,
  });
  // 获取配置参数服务
  const configService: ConfigService<{ app: any }, boolean> = app.get(ConfigService);
  // 应用配置
  const appConfig = configService.get('app');
  registerConfig(configService);
  // 设置服务全局根路径
  app.setGlobalPrefix(Environment.BasePath);
  // 对发送内容进行压缩
  app.register(compression, { encodings: ['gzip', 'deflate'] });
  app.register(FastifyCookie, { secret: resolve(__dirname, '..', 'resources/secret-key') });
  // 静态文件设置
  app.register(FastifyStatic, { root: resolve(__dirname, '..', Environment.Static.Path), prefix: Environment.Static.Route });
  // 启动应用监听
  await app.listen(appConfig.port || 3000, '0.0.0.0');
}
bootstrap();
