import { Logger, ValidationPipe } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
// import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
import helmet from "helmet";
import { corsConfig } from "./config/cors.config";

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(corsConfig);

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

    app.use(
      helmet({
        contentSecurityPolicy: {
          directives: {
            defaultSrc: ["'self'"],
            scriptSrc: [
              "'self'",
              "'unsafe-inline'",
              "'unsafe-eval'",
              "https://eu-assets.i.posthog.com",
            ],
            connectSrc: [
              "'self'",
              "https://eu.posthog.com",
              "https://eu-assets.i.posthog.com",
            ],
            imgSrc: ["'self'", "data:", "https:"],
            styleSrc: ["'self'", "'unsafe-inline'"],
            fontSrc: ["'self'", "data:", "https:"],
          },
        },
        crossOriginResourcePolicy: {
          policy: "cross-origin",
        },
        crossOriginOpenerPolicy: {
          policy: "same-origin-allow-popups",
        },
      }),
    );

    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();
