import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { BadRequestExceptionFilter } from './system/filters/bad-request-exception-filter';
import { IoAdapter } from '@nestjs/platform-socket.io';
import * as cookieParser from 'cookie-parser';
import { useContainer } from 'class-validator';
import { WebBidsService } from './modules/bids/services/web-bids.service';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const prefix_version = '/api/v1';

  const webBidService = app.get<WebBidsService>(WebBidsService);

  const webs = await webBidService.webBidRepo.find();

  const urls = webs.map((web) => web.origin_url);

  const corsOrigins = process.env.CORS
    ? process.env.CORS.split(',').map((origin) => origin.trim())
    : ['*']; // hoặc [] tùy ý bạn

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

  app.use(cookieParser());

  app.setGlobalPrefix(prefix_version, {});

  app.useWebSocketAdapter(new IoAdapter(app));

  app.useGlobalFilters(new BadRequestExceptionFilter());

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

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

  await app.listen(process.env.PORT);
}
bootstrap();
