// src/main.ts

import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { Logger, ValidationPipe } from '@nestjs/common';
import helmet from 'helmet';
import morgan from 'morgan';
import { PrismaClientExceptionFilter } from 'nestjs-prisma';
import { urlencoded, json } from 'express';
import { AppConfigService } from 'src/config/app/app-config.service';
import { TransformResponseInterceptor } from 'src/common/interceptor/transform.response.interceptor';
import { UUIDRequestInterceptor } from 'src/common/interceptor/uid.interceptor';
import { AppModule } from '../../app/app.module';

export default async function bootstrap() {
  const logger = new Logger('Bootstrap');
  const app = await NestFactory.create(AppModule);
  const appConfig = app.get(AppConfigService);

  app.setGlobalPrefix('v1');
  const loggingType = appConfig.environment;
  app.use(morgan(loggingType));
  app.use(json({ limit: '50mb' }));

  app.use(urlencoded({ extended: true, limit: '50mb' }));
  app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
  app.useGlobalInterceptors(new UUIDRequestInterceptor());
  app.useGlobalInterceptors(new TransformResponseInterceptor());
  const { httpAdapter } = app.get(HttpAdapterHost);
  app.useGlobalFilters(new PrismaClientExceptionFilter(httpAdapter));

  app.use(
    helmet({
      contentSecurityPolicy:
        appConfig.environment === 'localhost' ? false : undefined,
    }),
  );

  app.enableCors();

  const config = new DocumentBuilder()
    .setTitle('Laca city API')
    .setDescription('The Laca city API description')
    .setVersion('0.1')
    .addBearerAuth()
    .addBasicAuth()
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('docs', app, document);

  const port = String(appConfig.port);
  await app.listen(port);
  logger.log(`Application listening on port ${port}`);
}
