import { NestFactory } from '@nestjs/core';
import { ValidationPipe, Logger } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';

/**
 * Bootstrap Function
 * وظيفة التشغيل الأساسية
 * 
 * This is the entry point of the NestJS application.
 * هذه هي نقطة البداية لتطبيق NestJS.
 */
async function bootstrap() {
  const logger = new Logger('Bootstrap');

  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  // Serve Static Assets | تقديم الملفات الثابتة
  // This allows us to share ad images for analysis
  app.useStaticAssets(join(__dirname, '..', 'public'));

  // Get ConfigService for port | الحصول على خدمة الإعدادات للمنفذ
  const configService = app.get(ConfigService);
  const port = configService.get<number>('PORT') || 3660;

  // Security | الحماية
  // Helmet adds various HTTP headers to protect the app
  app.use(helmet());
  app.enableCors();

  // Global Prefix | البادئة العالمية
  // This helps in versioning and clean routing
  app.setGlobalPrefix('api');

  // Global Guards, Filters, Interceptors | الحماية والمرشحات والمراقبين العالميين
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
      forbidNonWhitelisted: true,
    }),
  );
  app.useGlobalFilters(new HttpExceptionFilter());
  app.useGlobalInterceptors(new LoggingInterceptor());

  // Swagger Documentation | توثيق سواجير
  // Essential for any SaaS backend to allow frontend devs to explore endpoints
  const config = new DocumentBuilder()
    .setTitle('Ads Analytics SaaS API')
    .setDescription('The Meta Ads Analytics Platform API description')
    .setVersion('1.0')
    .addTag('ads')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/docs', app, document);

  // Start Server | بدء الخادم
  await app.listen(port);
  logger.log(`🚀 Application is running on: http://localhost:${port}/api`);
  logger.log(`📑 API Documentation available at: http://localhost:${port}/api/docs`);
}

bootstrap();
