import { NestFactory } from '@nestjs/core';
import * as bodyParser from 'body-parser';
import { useContainer } from 'class-validator';
import * as cookieParser from 'cookie-parser';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { BadRequestExceptionFilter } from './system/filters/bad-request-exception-filter';
import { AppValidationPipes } from './system/pipes/app-validation-pipe';

import * as fs from 'fs';
import { SocketIoAdapter } from './socket-adapter';

async function bootstrap() {
  const httpsOptions = {
    key: fs.readFileSync('ssl/localhost+1-key.pem'),
    cert: fs.readFileSync('ssl/localhost+1.pem'),
  };

  const app = await NestFactory.create(AppModule, { httpsOptions });

  const prefix_version = process.env.PREFIX_VERSION;

  app.enableCors({
    origin: '*',
    methods: ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'],
    allowedHeaders: 'Content-Type, Authorization',
    // credentials: true,
  });

  app.use(cookieParser());

  app.setGlobalPrefix(prefix_version);

  app.useGlobalFilters(new BadRequestExceptionFilter());

  app.use(
    helmet({
      crossOriginResourcePolicy: false,
    }),
  );

  // Set global body parser limits
  app.use(bodyParser.json({ limit: '10mb' })); // hoặc lớn hơn nếu cần
  app.use(bodyParser.urlencoded({ limit: '10mb', extended: true }));

  app.useGlobalPipes(
    new AppValidationPipes({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      exceptionFactory: AppValidationPipes.exceptionFactory,
    }),
  );

  useContainer(app.select(AppModule), { fallbackOnErrors: true });

  await app.listen(Number(process.env.APP_API_PORT));

  // ===== App cho WebSocket (WS hoặc WSS) =====
  const wsApp = await NestFactory.create(AppModule);
  wsApp.useWebSocketAdapter(new SocketIoAdapter(wsApp));
  await wsApp.listen(Number(process.env.APP_SOCKET_PORT));
}

bootstrap();
