import './instrument'; // ⚠️ 必须首行:Sentry 自动埋点需在其它模块加载前初始化
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { apiReference } from '@scalar/nestjs-api-reference';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import {
  GLOBAL_PREFIX,
  GLOBAL_PREFIX_EXCLUDE,
  buildPacOpenApiDocument,
} from './openapi/build-document';

async function bootstrap() {
  // rawBody: true → req.rawBody 保留原始 bytes,push HMAC 验签需要(parsed JSON 字段顺序不稳)
  const app = await NestFactory.create(AppModule, { bufferLogs: true, rawBody: true });

  app.use(helmet({ contentSecurityPolicy: false }));

  const corsOrigins = app.get(ConfigService).getOrThrow<{ origins: string[] }>('cors').origins;
  app.enableCors({
    origin: corsOrigins.length > 0 ? corsOrigins : true,
    credentials: false,
    methods: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Authorization', 'Content-Type', 'Accept'],
  });

  app.setGlobalPrefix(GLOBAL_PREFIX, { exclude: GLOBAL_PREFIX_EXCLUDE });

  app.useGlobalFilters(new AllExceptionsFilter());

  const document = buildPacOpenApiDocument(app);

  app.use('/api/openapi.json', (_req: unknown, res: { json: (b: unknown) => void }) =>
    res.json(document),
  );
  app.use(
    '/api/docs',
    apiReference({
      content: document,
      theme: 'purple',
      layout: 'modern',
    }),
  );

  const port = Number(process.env.PORT ?? 3001);
  await app.listen(port, '0.0.0.0');
  Logger.log(`PAC service listening on http://localhost:${port}`, 'Bootstrap');
  Logger.log(`API reference: http://localhost:${port}/api/docs`, 'Bootstrap');
}

bootstrap().catch((err) => {
  console.error('Failed to bootstrap', err);
  process.exit(1);
});
