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 { KtqValidationPipes } from './system/pipes/ktq-validation-pipe';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  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 KtqValidationPipes({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      exceptionFactory: KtqValidationPipes.exceptionFactory,
    }),
  );

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

  await app.listen(Number(process.env.APP_PORT), process.env.APP_HOST);
}

bootstrap();
