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);

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

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

  // CORS 配置
  app.enableCors({
    origin: '*',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    credentials: true,
  });

  // Swagger API 文档
  const config = new DocumentBuilder()
    .setTitle('Transfer Service API')
    .setDescription('RWA 榴莲皇后平台树转让服务 API')
    .setVersion('1.0.0')
    .addBearerAuth()
    .addTag('转让订单', '转让订单相关接口')
    .addTag('管理端', '管理端转让相关接口')
    .addTag('健康检查', '服务健康检查接口')
    .build();

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

  // Kafka 微服务配置
  const kafkaBrokers = process.env.KAFKA_BROKERS?.split(',') || ['localhost:9092'];
  const kafkaGroupId = process.env.KAFKA_GROUP_ID || 'transfer-service-group';

  // 微服务 1: 用于接收 ACK 确认消息
  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.KAFKA,
    options: {
      client: {
        clientId: 'transfer-service-ack',
        brokers: kafkaBrokers,
      },
      consumer: {
        groupId: `${kafkaGroupId}-ack`,
      },
    },
  });

  // 微服务 2: 用于接收各服务的 Saga 步骤确认事件
  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.KAFKA,
    options: {
      client: {
        clientId: 'transfer-service-saga-events',
        brokers: kafkaBrokers,
      },
      consumer: {
        groupId: `${kafkaGroupId}-saga-events`,
      },
    },
  });

  // 启动所有 Kafka 微服务
  await app.startAllMicroservices();
  logger.log('Kafka microservices started (ACK + Saga Events)');

  const port = process.env.APP_PORT || 3013;
  await app.listen(port);

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

bootstrap();
