import { Logger, ValidationPipe } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";

async function bootstrap() {
  const logger = new Logger("Bootstrap");

  try {
    logger.log("Starting application...");

    const app = await NestFactory.create(AppModule, {
      logger: ["error", "warn", "log", "debug", "verbose"],
    });

    // Enable CORS
    app.enableCors({
      origin: [
        "https://www.placebo.mk",
        "https://placebo.mk",
        "http://localhost:5173",
        "https://imkapi.oblak.solutions",
      ],
      methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
      credentials: true,
      allowedHeaders: [
        "Origin",
        "X-Requested-With",
        "Content-Type",
        "Accept",
        "Authorization",
        'Access-Control-Allow-Headers',
        "Access-Control-Allow-Origin",
        "Access-Control-Allow-Credentials",
      ],
      exposedHeaders: [
              'Access-Control-Allow-Origin',
              'Access-Control-Allow-Credentials',
            ],
      preflightContinue: false,
      optionsSuccessStatus: 204,
    });

    // Global pipes
    app.useGlobalPipes(
      new ValidationPipe({
        transform: true,
        whitelist: true,
      }),
    );

    const port = process.env.PORT || 3000;

    logger.log(`Attempting to start server on port ${port}...`);
    await app.listen(port, "0.0.0.0");

    logger.log(`Application is running on: ${await app.getUrl()}`);
  } catch (error) {
    logger.error("Failed to start application:", error);
    process.exit(1);
  }
}

bootstrap();
