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

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

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

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

  // Swagger documentation
  if (process.env.SWAGGER_ENABLED !== 'false') {
    const config = new DocumentBuilder()
      .setTitle('Mining Wallet Service API')
      .setDescription('挖矿钱包服务 API - 100% 独立的钱包管理系统')
      .setVersion('1.0')
      .addBearerAuth()
      .addTag('System Accounts', '系统账户管理')
      .addTag('Pool Accounts', '池账户管理')
      .addTag('User Wallets', '用户钱包管理')
      .addTag('Regions', '区域管理')
      .addTag('Blockchain', 'KAVA区块链集成')
      .addTag('Health', '健康检查')
      .build();

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

  // Connect Kafka microservice
  const kafkaBrokers = process.env.KAFKA_BROKERS || 'localhost:9092';
  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.KAFKA,
    options: {
      client: {
        clientId: 'mining-wallet-service',
        brokers: kafkaBrokers.split(','),
      },
      consumer: {
        groupId: 'mining-wallet-service-group',
      },
      subscribe: {
        // 显式订阅需要消费的 topics
        fromBeginning: true,
      },
    },
  });

  await app.startAllMicroservices();

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

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

bootstrap();
