import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { BadRequestException, Logger, ValidationPipe, VersioningType } from '@nestjs/common';
import cookieParser from 'cookie-parser';
import compression from 'compression';
import helmet from 'helmet';
import hpp from 'hpp';
import { ConfigService } from '@nestjs/config';
// import rateLimit from 'express-rate-limit';
import { CustomExceptionFilter } from './common/filters/http-exception.filter';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { setupSwagger } from 'swagger';

async function bootstrap() {
  const isProduction = process.env.NODE_ENV === 'production';
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: isProduction ? ['error', 'warn'] : ['log', 'error', 'warn', 'debug', 'verbose'],
  });
  const configService = app.get(ConfigService);

  const logger = new Logger('Bootstrap');

  // Serve static files
  app.useStaticAssets(join(__dirname, '..', 'src', 'public'));

  // Security Middlewares
  app.use(helmet());
  app.use(hpp());

  app.enableCors({
    origin: isProduction ? configService.get<string>('CORS_ORIGIN_PROD').split(',') : configService.get<string>('CORS_ORIGIN_DEV').split(','),
    credentials: true,
  });

  app.set('trust proxy', 1);

  // Performance Optimizations
  app.use(compression());
  app.use(cookieParser());

  // Global Validation
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
      exceptionFactory: errors => {
        return new BadRequestException(
          errors.map(err => ({
            field: err.property,
            errors: Object.values(err.constraints),
          })),
        );
      },
    }),
  );

  app.useGlobalFilters(new CustomExceptionFilter());

  // await AppDataSource.initialize();

  // Set global prefix for API
  // app.setGlobalPrefix('api');

  app.enableVersioning({
    type: VersioningType.URI,
    // defaultVersion: '1',
    // prefix: 'api',
    prefix: 'api/v',
  });

  // Swagger
  setupSwagger(app);
  const port = configService.get<number>('PORT') || 3000;
  await app.listen(port);
  logger.debug(`🚀 Server running on http://localhost:${port}/api/v1`);
  logger.debug(`🚀 Swagger running on http://localhost:${port}/api-docs`);
}
bootstrap();
