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('Planting 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 || 'planting-service-group';

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

  // 微服务 2: 用于合同签署事件消费（监听 planting-events）
  // 注意：planting-service 自己发布事件，也自己消费（松耦合的合同签署模块）
  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.KAFKA,
    options: {
      client: {
        clientId: 'planting-service-contract-signing',
        brokers: kafkaBrokers,
      },
      consumer: {
        groupId: `${kafkaGroupId}-contract-signing`,
      },
    },
  });

  // 微服务 3: 用于监听 identity 服务的 KYC 事件
  // 当用户完成实名认证后，为其补创建之前已支付订单的合同
  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.KAFKA,
    options: {
      client: {
        clientId: 'planting-service-identity-events',
        brokers: kafkaBrokers,
      },
      consumer: {
        groupId: `${kafkaGroupId}-identity-events`,
      },
    },
  });

  // 微服务 4: 用于监听 transfer-service 的转让事件（纯新增）
  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.KAFKA,
    options: {
      client: {
        clientId: 'planting-service-transfer',
        brokers: kafkaBrokers,
      },
      consumer: {
        groupId: `${kafkaGroupId}-transfer`,
      },
    },
  });

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

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

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

bootstrap();
