import { NestFactory } from '@nestjs/core';
import { RequestMethod, ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';

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

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

  // CORS
  app.enableCors({
    origin: process.env['CORS_ORIGINS']?.split(',') || ['http://localhost:3000'],
    credentials: true,
  });

  // Swagger (development only)
  if (process.env['NODE_ENV'] !== 'production') {
    const config = new DocumentBuilder()
      .setTitle('Analytics Collector')
      .setDescription('Event collection endpoint for analytics')
      .setVersion('1.0')
      .build();
    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('docs', app, document);
  }

  // Global prefix — aligns with @lilith/analytics-client which POSTs to /analytics/track/*
  // Health endpoint excluded so Docker healthchecks can hit /health directly
  app.setGlobalPrefix('analytics', {
    exclude: [{ path: 'health', method: RequestMethod.GET }],
  });

  const port = process.env['PORT'] || 4001;
  await app.listen(port);

  console.log(`Analytics Collector running on port ${port}`);
  if (process.env['NODE_ENV'] !== 'production') {
    console.log(`Swagger docs available at http://localhost:${port}/docs`);
  }
}

bootstrap().catch((error) => {
  console.error('Failed to start Analytics Collector:', error);
  process.exit(1);
});
