import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import { join } from 'path';

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

  // 信任 Nginx/Kong 代理传入的 X-Forwarded-For，使 req.ip 返回真实客户端 IP
  app.set('trust proxy', 1);

  app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true, forbidNonWhitelisted: true }));
  app.enableCors({ origin: process.env.CORS_ORIGIN || '*', credentials: true });
  app.setGlobalPrefix('api/v2', {
    exclude: ['api/app/version/check', 'downloads/:filename'], // 移动端版本检查和下载不加前缀
  });

  // 静态文件服务 - 用于 APK/IPA 下载
  const uploadDir = process.env.UPLOAD_DIR || './uploads';
  app.useStaticAssets(join(process.cwd(), uploadDir), {
    prefix: '/downloads/',
  });

  const config = new DocumentBuilder()
    .setTitle('Mining Admin Service API')
    .setDescription('挖矿管理后台 API 文档')
    .setVersion('2.0')
    .addBearerAuth()
    .addTag('Auth', '认证')
    .addTag('Config', '配置管理')
    .addTag('Dashboard', '仪表盘')
    .addTag('Users', '用户管理')
    .addTag('Reports', '报表')
    .addTag('Audit', '审计日志')
    .addTag('Version Management', '版本管理')
    .addTag('Mobile App Version', '移动端版本检查')
    .build();

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

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

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

bootstrap();
