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

async function bootstrap() {
  const logger = new Logger('Bootstrap');

  const app = await NestFactory.create(AppModule);

  // 连接 Kafka 微服务消费者
  const kafkaBrokers = (process.env.KAFKA_BROKERS || 'localhost:9092').split(',');
  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.KAFKA,
    options: {
      client: {
        clientId: process.env.KAFKA_CLIENT_ID || 'reporting-service',
        brokers: kafkaBrokers,
      },
      consumer: {
        groupId: process.env.KAFKA_GROUP_ID || 'reporting-service-group',
      },
      subscribe: {
        fromBeginning: false,
      },
    },
  });

  logger.log(`📡 Kafka consumer connecting to: ${kafkaBrokers.join(', ')}`);

  // Global prefix
  app.setGlobalPrefix('api/v1');

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

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

  // Swagger setup
  const config = new DocumentBuilder()
    .setTitle('Reporting & Analytics Service')
    .setDescription('RWA Durian Platform - Reporting & Analytics API')
    .setVersion('1.0')
    .addBearerAuth()
    .addTag('Health', '健康检查')
    .addTag('Reports', '报表管理')
    .addTag('Export', '报表导出')
    .build();

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

  const port = process.env.PORT || 3008;

  // 启动所有微服务（包括 Kafka 消费者）
  await app.startAllMicroservices();
  logger.log('📡 Kafka microservice started - listening for events');

  await app.listen(port);

  logger.log(`🚀 Reporting Service is running on: http://localhost:${port}`);
  logger.log(`📚 Swagger API docs: http://localhost:${port}/api/docs`);
}

bootstrap();
