
import 'reflect-metadata'; // For NestJS DI (before any other imports)

import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { writeFileSync } from 'fs';
import { join } from 'path';
import { AppModule } from './app.module';

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

  // Swagger/OpenAPI configuration
  const config = new DocumentBuilder()
    .setTitle('GridPilot API')
    .setDescription('GridPilot API documentation')
    .setVersion('1.0')
    .addTag('races', 'Race management endpoints')
    .addTag('leagues', 'League management endpoints')
    .addTag('teams', 'Team management endpoints')
    .addTag('drivers', 'Driver management endpoints')
    .addTag('sponsors', 'Sponsor management endpoints')
    .addTag('payments', 'Payment and billing endpoints')
    .addTag('media', 'Media and file management endpoints')
    .addTag('analytics', 'Analytics and reporting endpoints')
    .build();

  const document = SwaggerModule.createDocument(app, config);

  // Serve Swagger UI at /api/docs
  SwaggerModule.setup('api/docs', app, document);

  // Export OpenAPI spec as JSON file when GENERATE_OPENAPI env var is set
  if (process.env.GENERATE_OPENAPI) {
    const outputPath = join(__dirname, '../openapi.json');
    writeFileSync(outputPath, JSON.stringify(document, null, 2));
    console.log(`✅ OpenAPI spec generated at: ${outputPath}`);
  }

  await app.listen(3000);
}
bootstrap();
