/**
 * Dump OpenAPI CLI
 *
 * 把 PAC 的 OpenAPI spec 导出成静态 JSON,供文档站(fumadocs-openapi)渲染。
 * 用 Nest **preview 模式**:构建模块图 + 注册路由供 Swagger 内省,但**不实例化 provider**
 * —— 不连 DB / Redis,无副作用,纯导出。CI 里可直接跑,无需起服务。
 *
 * Usage:
 *   pnpm --filter @pac/service openapi:dump            # → ../pac-docs/openapi/pac.json
 *   pnpm --filter @pac/service openapi:dump -- out.json
 */
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { AppModule } from '../app.module';
import {
  GLOBAL_PREFIX,
  GLOBAL_PREFIX_EXCLUDE,
  buildPacOpenApiDocument,
} from '../openapi/build-document';

async function main() {
  const outArg = process.argv[2] ?? '../pac-docs/openapi/pac.json';
  const out = resolve(process.cwd(), outArg);

  const app = await NestFactory.create(AppModule, { preview: true, logger: false });
  app.setGlobalPrefix(GLOBAL_PREFIX, { exclude: GLOBAL_PREFIX_EXCLUDE });
  const document = buildPacOpenApiDocument(app);
  await app.close();

  mkdirSync(dirname(out), { recursive: true });
  writeFileSync(out, JSON.stringify(document, null, 2) + '\n');

  const pathCount = Object.keys(document.paths ?? {}).length;
  console.log(`OpenAPI written → ${out} (${pathCount} paths)`);
  if (pathCount === 0) {
    console.error('⚠️  0 paths — preview 模式可能没注册路由,检查 Nest 版本/模块结构');
    process.exitCode = 2;
  }
}

main().catch((err) => {
  console.error('dump-openapi failed', err);
  process.exit(1);
});
