import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder, OpenAPIObject } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerConfigService } from './config/swagger/config.service';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.enableCors({
    origin: true,
    methods: ['GET', 'POST', 'PATCH', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization', 'Accept-Language'],
  });

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
    }),
  );

  const swaggerConfigService =
    app.get<SwaggerConfigService>(SwaggerConfigService);

  const swaggerDocumentBuilder = new DocumentBuilder()
    .setTitle('Fit API')
    .setDescription(
      'An API for accessing a collection of food-related data, recipes, meals, exercises and track your daily routine.',
    )
    .setVersion('1.0.0')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
        name: 'JWT',
        description: 'Enter JWT token',
        in: 'header',
      },
      'JWT',
    )
    .addSecurityRequirements('JWT');

  if (swaggerConfigService.server) {
    swaggerDocumentBuilder.addServer(swaggerConfigService.server);
  }

  const swaggerConfig = swaggerDocumentBuilder.build();

  const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);

  const swaggerCustomOptions = {
    swaggerOptions: {
      defaultModelsExpandDepth: -1,
      persistAuthorization: true,
    },
  };

  Object.values((swaggerDocument as OpenAPIObject).paths).forEach(
    (path: any) => {
      // Removes security from public routes
      Object.values(path).forEach((method: any) => {
        if (
          Array.isArray(method.security) &&
          method.security.includes('public')
        ) {
          method.security = [];
        }

        // Removes HTTP responses without description
        Object.keys(method.responses).forEach((key: any) => {
          if (method.responses[key].description === '') {
            method.responses[key] = undefined;
          }
        });
      });
    },
  );

  SwaggerModule.setup('docs', app, swaggerDocument, swaggerCustomOptions);

  await app.listen(3000);
}
bootstrap();
