import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import * as requestIp from 'request-ip';

import { AppModule } from './app.module';
import { ConfigurationService } from './config/configuration.service';
import { BadRequestExceptionFilter } from './utils/exceptions/bad-request.exceptions';
import { UnauthorizedExceptionFilter } from './utils/exceptions/unauthorized-request.exceptions';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  const config = app.get(ConfigurationService);

  app.useGlobalFilters(new BadRequestExceptionFilter());
  app.useGlobalFilters(new UnauthorizedExceptionFilter());

  app.useGlobalPipes(
    new ValidationPipe({
      errorHttpStatusCode: 422,
      // we can whitelist the acceptable properties, and any property not included in the whitelist is automatically stripped from the resulting object
      whitelist: true,
      // you can stop the request from processing when non-whitelisted properties are present, and return an error response to the user
      // forbidNonWhitelisted: true,
      enableDebugMessages: true,
    }),
  );

  app.use(requestIp.mw());

  if (config.app.nodeEnv !== 'production') {
    const swaggerConfig = new DocumentBuilder()
      .setTitle('API')
      .setDescription('API docs')
      .setVersion('1.0')
      .addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' })
      .build();

    const document = SwaggerModule.createDocument(app, swaggerConfig);
    SwaggerModule.setup('docs', app, document);
  }

  await app.listen(config.app.port);
}
bootstrap();
