import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { GlobalExceptionFilter } from './common/filters/global-exception.filter';
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
import { getRequiredNumber } from './common/utils/config.util';
import { Logger } from 'nestjs-pino';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

class Bootstrap {}

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    bufferLogs: true,
  });
  const appLogger = app.get(Logger);
  const config = app.get(ConfigService);

  app.enableShutdownHooks();
  // Trust proxy 설정 (프록시/LB 환경에서 정확한 클라이언트 IP 추출)
  app.set('trust proxy', true);
  // (선택) 로컬망 브라우저에서 쿠키/인증까지 쓸 거면 옵션 CORS 권장
  app.enableCors({
    origin: true, // 필요하면 ["http://172.18.100.80:5173", ...] 처럼 명시로 바꾸기
    credentials: true, // 쿠키/세션 쓰면 true
    maxAge: 600, // 10분
  });

  app.useLogger(appLogger);
  app.useGlobalPipes(new ValidationPipe({ transform: true }));
  app.useGlobalFilters(new GlobalExceptionFilter(appLogger));
  app.useGlobalInterceptors(app.get(ResponseInterceptor));

  const swaggerConfig = new DocumentBuilder()
    .setTitle('POP Monitoring API')
    .setDescription('')
    .setVersion('1.0')
    .build();
  const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);
  SwaggerModule.setup('/docs', app, swaggerDocument);

  const port = getRequiredNumber(config, 'PORT');
  await app.listen(port, '0.0.0.0');

  appLogger.log(
    {
      event: 'app.lifecycle',
      operation: 'api_listening',
      host: '0.0.0.0',
      port,
    },
    'API listening',
    Bootstrap.name,
  );
}

void bootstrap();
