import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ValidationPipe } from '@nestjs/common';
import * as cookieParser from 'cookie-parser';
import helmet from 'helmet';
import { AppModule } from './app.module';

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

  // VPS derrière Apache / reverse proxy — obligatoire pour rate limiter + IP logs corrects
  app.set('trust proxy', 1);

  // Security headers
  app.use(helmet());

  // Cookie parser avec signature
  const cookieSecret = process.env.COOKIE_SECRET;
  if (!cookieSecret) throw new Error('COOKIE_SECRET manquant');
  app.use(cookieParser(cookieSecret));

  // CORS — multi-origin depuis l'env
  const allowedOrigins = (process.env.FRONTEND_URL ?? 'http://localhost:5173')
    .split(',')
    .map((o) => o.trim());

  app.enableCors({
    origin: allowedOrigins,
    credentials: true,
  });

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

  // Prefix global
  app.setGlobalPrefix('api');

  const port = process.env.PORT ?? 4000;
  await app.listen(port);
  console.log(`TetaRdPG backend démarré sur le port ${port}`);
}

bootstrap();
