import 'reflect-metadata';
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

async function generate(): Promise<void> {
  process.env.NODE_ENV ??= 'development';
  process.env.PORT ??= '3000';
  process.env.DATABASE_URL ??=
    'postgresql://velody:velody@localhost:5432/velody?schema=public';
  process.env.STORAGE_ROOT ??= join(process.cwd(), '..', 'runtime', 'storage');
  process.env.PUBLIC_BASE_URL ??= 'http://localhost:3000';
  process.env.DEVICE_BOOTSTRAP_SECRET ??= 'openapi-placeholder-secret';
  process.env.MAX_UPLOAD_SIZE_BYTES ??= '524288000';

  const { createApp } = await import('../src/app.factory');
  const app = await createApp();
  const document = SwaggerModule.createDocument(
    app,
    new DocumentBuilder()
      .setTitle('Velody API')
      .setDescription('Velody Phase 1 foundation API')
      .setVersion('1.0.0')
      .build(),
  );

  const outputDir = join(process.cwd(), 'openapi');
  await mkdir(outputDir, { recursive: true });
  await writeFile(
    join(outputDir, 'velody.openapi.json'),
    JSON.stringify(document, null, 2),
  );
  await app.close();
}

void generate();
