// ========== 즉시 로그 출력 (Docker 로그 테스트) ==========
console.log('========================================');
console.log('[BOOT] main.ts loaded at', new Date().toISOString());
console.log('[BOOT] Node version:', process.version);
console.log('[BOOT] ENV:', process.env.NODE_ENV);
console.log('========================================');

import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe, Logger } from '@nestjs/common';
import { JwtAuthGuard } from './common/guards/jwt-auth.guard';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { types } from 'pg';

// ========== 전역 에러 핸들러 ==========
process.on('uncaughtException', (error) => {
  console.error('╔═══════════ UNCAUGHT EXCEPTION ═══════════╗');
  console.error(`Timestamp: ${new Date().toISOString()}`);
  console.error(`Error: ${error.message}`);
  console.error(`Stack: ${error.stack}`);
  console.error('╚══════════════════════════════════════════╝');
});

process.on('unhandledRejection', (reason) => {
  console.error('╔═══════════ UNHANDLED REJECTION ═══════════╗');
  console.error(`Timestamp: ${new Date().toISOString()}`);
  console.error(`Reason: ${reason}`);
  console.error('╚═══════════════════════════════════════════╝');
});

// PostgreSQL numeric 타입 변환
types.setTypeParser(1700, parseFloat);

async function bootstrap() {
  const logger = new Logger('Bootstrap');
  
  logger.log('========================================');
  logger.log('Application starting...');
  logger.log(`NODE_ENV: ${process.env.NODE_ENV}`);
  logger.log(`POSTGRES_HOST: ${process.env.POSTGRES_HOST}`);
  logger.log('========================================');

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

    logger.log('NestFactory.create() 완료');

    app.enableCors({
      origin: (origin, callback) => {
        if (!origin) return callback(null, true);
        
        const allowedPatterns = [
          /^http:\/\/localhost:\d+$/,
          /^http:\/\/127\.0\.0\.1:\d+$/,
          /^http:\/\/192\.168\.11\.\d+:\d+$/,
          /^https?:\/\/.*\.turbosoft\.kr$/,
        ];
        
        const isAllowed = allowedPatterns.some(pattern => pattern.test(origin));
        callback(null, isAllowed);
      },
      credentials: true,
    });

    app.useGlobalPipes(
      new ValidationPipe({
        transform: true,
        whitelist: false,
        transformOptions: { enableImplicitConversion: true },
      }),
    );

    app.useGlobalFilters(new AllExceptionsFilter());
    app.useGlobalInterceptors(new LoggingInterceptor(), new TransformInterceptor());

    const reflector = app.get(Reflector);
    app.useGlobalGuards(new JwtAuthGuard(reflector));

    const port = process.env.PORT ?? 4000;
    await app.listen(port, '0.0.0.0');
    
    logger.log(`✅ Server running on port ${port}`);

  } catch (error) {
    logger.error('❌ Application failed to start!');
    logger.error(`Error: ${error.message}`);
    logger.error(`Stack: ${error.stack}`);
    process.exit(1);
  }
}

bootstrap();
