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

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

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

  app.enableCors({
    origin: process.env.CORS_ORIGIN || '*',
    credentials: true,
  });

  app.setGlobalPrefix('api/v2');

  const config = new DocumentBuilder()
    .setTitle('Trading Service API')
    .setDescription('交易服务 API 文档 - 积分股买卖交易')
    .setVersion('1.0')
    .addBearerAuth()
    .addTag('Trading', '交易相关')
    .addTag('Order', '订单相关')
    .addTag('Transfer', '划转相关')
    .addTag('Health', '健康检查')
    .build();

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

  const kafkaBrokers = process.env.KAFKA_BROKERS || 'localhost:9092';
  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.KAFKA,
    options: {
      client: {
        clientId: 'trading-service',
        brokers: kafkaBrokers.split(','),
      },
      consumer: {
        groupId: 'trading-service-group',
      },
    },
  });

  await app.startAllMicroservices();

  const port = process.env.PORT || 3022;
  await app.listen(port);

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

bootstrap();
