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'
import { GlobalExceptionFilter } from '@/shared/filters'
import { TransformInterceptor } from '@/shared/interceptors'

async function bootstrap() {
  const logger = new Logger('Bootstrap')
  const app = await NestFactory.create(AppModule)

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

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

  // Global filters
  app.useGlobalFilters(new GlobalExceptionFilter())

  // Global interceptors
  app.useGlobalInterceptors(new TransformInterceptor())

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

  // Swagger
  const config = new DocumentBuilder()
    .setTitle('Authorization Service API')
    .setDescription('RWA授权管理服务API - 社区/省市公司授权、阶梯考核、月度评估与排名')
    .setVersion('1.0.0')
    .addBearerAuth()
    .addTag('Authorization', '授权管理')
    .addTag('Admin Authorization', '管理员授权操作')
    .build()
  const document = SwaggerModule.createDocument(app, config)
  SwaggerModule.setup('api/docs', app, document)

  // Kafka 微服务 - 用于 @EventPattern 消费认种事件
  const kafkaBrokers = process.env.KAFKA_BROKERS?.split(',') || ['localhost:9092']
  const kafkaGroupId = process.env.KAFKA_GROUP_ID || 'authorization-service-group'

  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.KAFKA,
    options: {
      client: {
        clientId: 'authorization-service',
        brokers: kafkaBrokers,
      },
      consumer: {
        groupId: kafkaGroupId,
      },
    },
  })

  await app.startAllMicroservices()
  logger.log('Kafka microservice started for planting event consumption')

  const port = parseInt(process.env.APP_PORT || '3009', 10)
  await app.listen(port)

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

bootstrap()
