import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { SwaggerModule } from '@nestjs/swagger/dist/swagger-module';
import { DocumentBuilder } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { LogRequestInterceptor } from './common/interceptors/log-request.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule,
    { logger: ['error', 'warn', 'log', 'debug', 'verbose'] });

  // Log de chaque appel API si LOG_API_REQUESTS=true (mode debug)
  app.useGlobalInterceptors(new LogRequestInterceptor());

  // Configuration CORS pour autoriser les requêtes depuis localhost (dev) et production
  app.enableCors({
    origin: true, // Autorise toutes les origines (dev) - à restreindre en prod
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'Accept'],
    credentials: true,
  });

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

  const configService = app.get(ConfigService);

  const port = configService.get<number>('app.port', 3000);
  app.setGlobalPrefix('api/v1');

  const config = new DocumentBuilder()
    .setTitle("P'titsPas API")
    .setDescription("API pour l'application P'titsPas")
    .setVersion('1.0.0')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'Bearer',
        bearerFormat: 'JWT',
        name: 'Authorization',
        description: 'Enter JWT token',
        in: 'header',
      },
      'access-token',
    )
    //.addServer('/api/v1')
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/v1/swagger', app, document);



  await app.listen(port);
  console.log(`✅ P'titsPas API is running on: ${await app.getUrl()}`);
}

bootstrap().catch((err) => {
  console.error('❌ Error starting the application:', err);
  process.exit(1);
});
