import { NestFactory } from '@nestjs/core'
import { ValidationPipe, Logger, RequestMethod } from '@nestjs/common'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'
import { AppModule } from './app.module'

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

  // Global prefix (exclude mobile API routes and downloads that need custom paths)
  app.setGlobalPrefix('api/v1', {
    exclude: [
      { path: 'api/app/version/(.*)', method: RequestMethod.ALL },
      { path: 'api/app/version/check', method: RequestMethod.GET },
      { path: 'downloads/(.*)', method: RequestMethod.GET },
    ],
  })

  // Validation
  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
  const config = new DocumentBuilder()
    .setTitle('Admin Service API')
    .setDescription('RWA管理服务API - 移动应用版本管理')
    .setVersion('1.0.0')
    .addBearerAuth()
    .addTag('Version Management', '版本管理')
    .addTag('Health', '健康检查')
    .build()
  const document = SwaggerModule.createDocument(app, config)
  SwaggerModule.setup('api/docs', app, document)

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

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

bootstrap()
