import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.enableCors({
    origin: true, // Allow all origins 
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
    credentials: true,
  });
  app.setGlobalPrefix('api'); // Set a global API prefix

  // Swagger / OpenAPI documentation
  const config = new DocumentBuilder()
    .setTitle('AuraK API')
    .setDescription('External API for accessing AuraK functionalities via API Key')
    .setVersion('1.0')
    .addApiKey({ type: 'apiKey', name: 'x-api-key', in: 'header' }, 'x-api-key')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/docs', app, document);

  await app.listen(process.env.PORT ?? 3001);

  // Ensure "Default" tenant exists
  const { TenantService } = await import('./tenant/tenant.service');
  const tenantService = app.get(TenantService);
  await tenantService.ensureDefaultTenant();
}
bootstrap();
