// backend/src/main.ts
import './instrument';
import { NestFactory } from '@nestjs/core';
import { urlencoded } from 'express';
import { AppModule } from './app.module';
import { createJsonBodyParser } from './common/body-parsers';
import { ValidationPipe } from '@nestjs/common';
import cookieParser from 'cookie-parser'; // 👈 Change this line!
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import {
  HttpExceptionFilter,
  validationExceptionFactory,
} from './common/errors';

// At the VERY TOP of main.ts, before anything else
const originalConsoleLog = console.log;
console.log = (...args) => {
  // Check if this is the massive Prisma dump (contains _clientVersion)
  if (args.some(arg => arg && typeof arg === 'object' && arg._clientVersion)) {
    console.error = originalConsoleLog; // Temporarily restore for this message
    originalConsoleLog('🔍🔍🔍 PRISMA CLIENT DUMP DETECTED 🔍🔍🔍');
    originalConsoleLog('Stack trace:', new Error().stack);
    return; // Don't print the actual object
  }
  originalConsoleLog.apply(console, args);
};

async function bootstrap() {
  // bodyParser is disabled so the JSON parsers can be registered in an explicit order below;
  // Nest's built-in one would otherwise reject a voice recording at 100 kb.
  const app = await NestFactory.create(AppModule, { bodyParser: false });

  // Nginx terminates TLS; AdminJS sessions and Secure cookies need the real proto/host.
  app.getHttpAdapter().getInstance().set('trust proxy', 1);

  // Voice needs a larger JSON limit than everything else; see body-parsers.ts.
  app.use(createJsonBodyParser());
  app.use(urlencoded({ extended: true }));
  
  app.useGlobalFilters(new HttpExceptionFilter());

  // Global pipes
  app.useGlobalPipes(new ValidationPipe({
    whitelist: true,
    forbidNonWhitelisted: true,
    transform: true,
    exceptionFactory: validationExceptionFactory,
  }));
  
  // Cookie parser - this is correct for Express
  app.use(cookieParser());
  
  // CORS
  app.enableCors({
    origin: process.env.FRONTEND_URL || 'http://localhost:3001',
    credentials: true,
  });
  
  // Global prefix
  app.setGlobalPrefix('api');

  // Swagger configuration
  const swaggerConfig = new DocumentBuilder()
    .setTitle('Dyolink API')
    .setDescription('Dental Clinic & Lab Communication Hub API')
    .setVersion('1.0')
    .addTag('auth', 'Authentication endpoints')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
        name: 'JWT',
        description: 'Enter JWT token',
        in: 'header',
      },
      'JWT-auth',
    )
    .build();

  const document = SwaggerModule.createDocument(app, swaggerConfig);
  
  SwaggerModule.setup('api/docs', app, document, {
    swaggerOptions: {
      persistAuthorization: true,
      tagsSorter: 'alpha',
      operationsSorter: 'alpha',
    },
    customSiteTitle: 'Dyolink API Documentation',
  });

  const port = parseInt(process.env.PORT || '', 10) || 3000;
  await app.listen(port);
  
  console.log(`🚀 Application is running on: http://localhost:${port}/api`);
  console.log(`📚 Swagger documentation: http://localhost:${port}/api/docs`);
  console.log(`📚 AdminJS Panel: http://localhost:${port}/admin`);
}

bootstrap();