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

async function bootstrap() {
  const logger = new Logger('Bootstrap');
  const app = await NestFactory.create(AppModule);

  // 全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  );

  // CORS配置
  app.enableCors({
    origin: process.env.CORS_ORIGIN || '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    credentials: true,
  });

  // API前缀
  app.setGlobalPrefix('api/v1');

  // Swagger文档
  if (process.env.NODE_ENV !== 'production') {
    const config = new DocumentBuilder()
      .setTitle('Referral Service API')
      .setDescription('推荐团队服务 API 文档')
      .setVersion('1.0')
      .addBearerAuth()
      .addTag('Referral', '推荐关系管理')
      .addTag('Leaderboard', '龙虎榜')
      .addTag('Team Statistics', '团队统计')
      .addTag('Health', '健康检查')
      .build();

    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('api/docs', app, document);
    logger.log('Swagger documentation available at /api/docs');
  }

  const port = parseInt(process.env.APP_PORT || '3004', 10);
  await app.listen(port);
  logger.log(`Referral Service is running on port ${port}`);
}

bootstrap();
