import 'dotenv/config';

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import cookieParser from 'cookie-parser';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';

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

  // req.ip reflects the real client from X-Forwarded-For IP.
  app.set('trust proxy', 1);
  app.setGlobalPrefix('api/v1', {
    exclude: [''], // Exclude root path from global prefix
  });
  app.use(cookieParser());
  //Apply filter Response format standard API
  app.useGlobalFilters(new HttpExceptionFilter());
  app.useGlobalInterceptors(new TransformInterceptor());
  //Allow origin who can access to this API
  app.enableCors({
    origin: [
      'http://localhost:3000',
      'https://mis-stage.datacolabx.com',
      'https://mis-pro.datacolabx.com',
    ],
    credentials: true,
  });

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );
  //API Document
  const config = new DocumentBuilder()
    .setTitle('G-PSF MIS API')
    .setDescription('API documentation for the G-PSF MIS backend')
    .setVersion('1.0')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
      },
      'access-token',
    )
    .build();

  const document = SwaggerModule.createDocument(app, config);

  SwaggerModule.setup('api/v1/docs', app, document, {
    swaggerOptions: {
      persistAuthorization: true,
    },
  });

  const port = Number(process.env.PORT) || 3000;

  await app.listen(port);

  console.log(`Server running on http://localhost:${port}`);
  console.log(`Swagger docs running on http://localhost:${port}/api/v1/docs`);
}

bootstrap().catch((error) => {
  console.error(error);
  process.exit(1);
});
