/**
 * MPC Party Service - Main Entry Point
 *
 * RWA Durian System - MPC Server Party Service
 */

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

async function bootstrap() {
  const logger = new Logger('Bootstrap');

  // Create application
  const app = await NestFactory.create(AppModule, {
    logger: ['error', 'warn', 'log', 'debug', 'verbose'],
  });

  // Enable graceful shutdown hooks (calls onModuleDestroy on SIGTERM/SIGINT)
  // This ensures Kafka consumer disconnects properly, allowing fast rebalance on restart
  app.enableShutdownHooks();

  // Get config service
  const configService = app.get(ConfigService);
  const port = parseInt(process.env.APP_PORT || '3006', 10);
  const apiPrefix = process.env.API_PREFIX || 'api/v1';
  const env = process.env.NODE_ENV || 'development';

  // Set global prefix
  app.setGlobalPrefix(apiPrefix);

  // Enable CORS
  app.enableCors({
    origin: true,
    credentials: true,
  });

  // Global validation pipe
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  );

  // Swagger documentation (only in development)
  if (env !== 'production') {
    const swaggerConfig = new DocumentBuilder()
      .setTitle('MPC Party Service')
      .setDescription('RWA Durian System - MPC Server Party Service API')
      .setVersion('1.0')
      .addBearerAuth()
      .addTag('MPC Party', 'MPC party operations')
      .addTag('Health', 'Health check endpoints')
      .build();

    const document = SwaggerModule.createDocument(app, swaggerConfig);
    SwaggerModule.setup('api/docs', app, document, {
      swaggerOptions: {
        persistAuthorization: true,
      },
    });

    logger.log(`Swagger documentation available at /api/docs`);
  }

  // Start server
  await app.listen(port);
  logger.log(`MPC Party Service running on port ${port}`);
  logger.log(`Environment: ${env}`);
  logger.log(`API prefix: ${apiPrefix}`);
}

bootstrap().catch((error) => {
  console.error('Failed to start application:', error);
  process.exit(1);
});
