import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
import helmet from 'helmet';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';

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

  // Increase body size limit for base64 image uploads (10MB)
  app.use(require('express').json({ limit: '10mb' }));
  app.use(require('express').urlencoded({ limit: '10mb', extended: true }));

  // Replace default logger with Winston
  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));

  // Security headers with Helmet
  app.use(
    helmet({
      contentSecurityPolicy: {
        directives: {
          defaultSrc: ["'self'"],
          styleSrc: ["'self'", "'unsafe-inline'"], // GraphQL Playground needs unsafe-inline
          scriptSrc: ["'self'", "'unsafe-inline'", "'unsafe-eval'"], // GraphQL Playground needs unsafe-eval
          imgSrc: ["'self'", 'data:', 'https:'],
          connectSrc: ["'self'"],
          fontSrc: ["'self'", 'data:'],
          objectSrc: ["'none'"],
          mediaSrc: ["'self'"],
          frameSrc: ["'none'"],
        },
      },
      crossOriginEmbedderPolicy: false, // Disable for compatibility
      crossOriginResourcePolicy: { policy: 'cross-origin' },
      hsts: {
        maxAge: 31536000, // 1 year
        includeSubDomains: true,
        preload: true,
      },
      frameguard: {
        action: 'deny',
      },
      noSniff: true,
      xssFilter: true,
      referrerPolicy: {
        policy: 'strict-origin-when-cross-origin',
      },
    }),
  );

  // Strict CORS configuration
  const allowedOrigins = process.env.CORS_ORIGIN?.split(',').map((o) => o.trim()) || [
    'http://localhost:19000',            // Expo dev
    'http://localhost:3001',             // Next.js dev (legacy)
    'http://localhost:3030',             // Next.js dev (current)
    'http://localhost:3005',             // Next.js dev (port 3005)
    'http://localhost:3335',             // Admin dashboard dev
    'https://maternal.noru1.ro',         // Production frontend (legacy)
    'https://maternal-api.noru1.ro',     // Production API (legacy)
    'https://pfadmin.noru1.ro',          // Production admin dashboard
    'https://web.parentflowapp.com',     // Production frontend
    'https://api.parentflowapp.com',     // Production API (for GraphQL playground)
  ];

  app.enableCors({
    origin: (origin, callback) => {
      // Allow requests with no origin (mobile apps, Postman, etc.)
      if (!origin) {
        return callback(null, true);
      }

      if (allowedOrigins.indexOf(origin) !== -1) {
        callback(null, true);
      } else {
        console.warn(`CORS blocked origin: ${origin}`);
        callback(new Error(`Origin ${origin} not allowed by CORS`));
      }
    },
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
    allowedHeaders: [
      'Content-Type',
      'Authorization',
      'X-Requested-With',
      'apollo-require-preflight',
    ],
    exposedHeaders: ['Content-Range', 'X-Content-Range'],
    credentials: true,
    preflightContinue: false,
    optionsSuccessStatus: 204,
    maxAge: 86400, // 24 hours
  });

  // Global validation pipe with comprehensive settings
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true, // Strip properties that don't have decorators
      forbidNonWhitelisted: true, // Throw error if non-whitelisted values are provided
      transform: true, // Automatically transform payloads to DTO instances
      transformOptions: {
        enableImplicitConversion: true, // Convert primitive types automatically
      },
      disableErrorMessages: process.env.NODE_ENV === 'production', // Hide validation error details in production
      validationError: {
        target: false, // Don't expose the target object in errors
        value: false, // Don't expose the value in errors
      },
    }),
  );

  const port = process.env.API_PORT || 3000;
  await app.listen(port, '0.0.0.0');

  console.log(`🚀 Backend API running on http://0.0.0.0:${port}`);
  console.log(`📚 API Base: http://0.0.0.0:${port}/api/v1`);
  console.log(`🔒 Security: Helmet enabled, CORS configured for ${allowedOrigins.length} origins`);
}
bootstrap();
