import { Logger } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { NestFactory } from '@nestjs/core';
import helmet from 'helmet';
import compression from 'compression';

import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    bufferLogs: true,
  });

  const logger = new Logger('Bootstrap');

  app.use(helmet());
  app.use(compression());

  app.enableCors({
    origin: '*',
    credentials: true,
  });

  // <<<inject:global-middleware>>>

  const port = parseInt(process.env.PORT ?? '8000', 10);
  const host = process.env.HOST ?? '0.0.0.0';

  // Enable Swagger docs in development or when explicitly requested.
  const enableDocs = process.env.RAPIDKIT_ENABLE_SWAGGER === '1' || process.env.NODE_ENV !== 'production';
  if (enableDocs) {
    const config = new DocumentBuilder()
      .setTitle('{{ project_name | default("RapidKit App") }} API')
      .setDescription('Auto-generated API docs')
      .setVersion('{{ app_version | default("1.0.0") }}')
      .addBearerAuth()
      .build();

    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('docs', app, document);
  }

  await app.listen(port, host);

  logger.log(`🚀 Application is running on http://${host}:${port}`);
  // <<<inject:bootstrap-hooks>>>
}

bootstrap().catch((error) => {
  // eslint-disable-next-line no-console
  console.error('❌ Failed to bootstrap application', error);
  process.exit(1);
});
