import { NestFactory } from '@nestjs/core';
import { ValidationPipe, VersioningType } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
import helmet from 'helmet';
import compression from 'compression';
import { AppModule } from './app.module';
import { Logger } from 'nestjs-pino';
import { helmetConfig, corsConfig } from './infrastructure/security/security.config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    bufferLogs: true,
  });

  // Get config service
  const configService = app.get(ConfigService);
  const port = configService.get<number>('PORT', 4000);
  const apiPrefix = configService.get<string>('API_PREFIX', 'api/v1');

  // Use Pino logger
  app.useLogger(app.get(Logger));

  // Security - Helmet with OWASP recommended headers
  app.use(helmet(helmetConfig));

  // Compression for API responses
  app.use(compression());

  // CORS with strict configuration
  app.enableCors(corsConfig);

  // Global prefix
  app.setGlobalPrefix(apiPrefix);

  // API versioning
  app.enableVersioning({
    type: VersioningType.URI,
  });

  // Global validation pipe
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    })
  );

  // Swagger documentation
  const config = new DocumentBuilder()
    .setTitle('Xpeditis API')
    .setDescription(
      'Maritime Freight Booking Platform - API for searching rates and managing bookings'
    )
    .setVersion('1.0')
    .addBearerAuth()
    .addTag('rates', 'Rate search and comparison')
    .addTag('bookings', 'Booking management')
    .addTag('auth', 'Authentication and authorization')
    .addTag('users', 'User management')
    .addTag('organizations', 'Organization management')
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/docs', app, document, {
    customSiteTitle: 'Xpeditis API Documentation',
    customfavIcon: 'https://xpeditis.com/favicon.ico',
    customCss: '.swagger-ui .topbar { display: none }',
  });

  await app.listen(port);

  console.log(`
    ╔═══════════════════════════════════════╗
    ║                                       ║
    ║   🚢 Xpeditis API Server Running     ║
    ║                                       ║
    ║   API: http://localhost:${port}/${apiPrefix}      ║
    ║   Docs: http://localhost:${port}/api/docs  ║
    ║                                       ║
    ╚═══════════════════════════════════════╝
  `);
}

bootstrap();
