import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { Logger, ValidationPipe } from '@nestjs/common';
import { getSwaggerConfig } from './config/swagger.config';
import multipart from '@fastify/multipart';
import fastifyCookie from '@fastify/cookie';

// 👈 Import the Fastify application type
import { type NestFastifyApplication, FastifyAdapter } from '@nestjs/platform-fastify';
import { HttpExceptionFilter } from './core/exceptions/http.exceptions';
import { ResponseInterceptor } from './core/interceptors/response.interceptor';
// import { PaginationInterceptor } from './core/interceptors/pagination.interceptor';

async function bootstrap() {
  const logger = new Logger('APP');

  // 1. Create the application using the Fastify adapter
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(), // Instantiate the FastifyAdapter
    // Optional: Pass the custom logger (like your 'APP' logger) to NestFactory
    { logger: ['error', 'warn', 'log', 'debug', 'verbose'] },
  );

  await app.register(fastifyCookie);

  await app.register(multipart);
  app.useGlobalPipes(new ValidationPipe());

  app.useGlobalInterceptors(
    new ResponseInterceptor(),
    // , new PaginationInterceptor()
  );
  app.useGlobalFilters(new HttpExceptionFilter());

  const configService = app.get<ConfigService>(ConfigService);
  // Ensure the port is handled correctly, use 4000 as fallback if needed
  const APP_PORT = configService.getOrThrow<number>('APP_PORT') ?? 4000;

  // 2. Swagger Integration Note
  // Since you are using platform-fastify, you must ensure your getSwaggerConfig
  // function is configured to use the Fastify platform option if necessary.
  getSwaggerConfig(app);

  app.enableCors({
    origin: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    credentials: true,
    optionsSuccessStatus: 204,
  });

  // 3. Listen on port using Fastify's listen method
  // '0.0.0.0' is recommended for Docker/containerized environments
  await app.listen(APP_PORT, '0.0.0.0', () => {
    logger.log(`Application is running on: http://localhost:${APP_PORT}`);
    logger.log(`Swagger documentation: http://localhost:${APP_PORT}/docs`);
  });
}

bootstrap();
