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

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

  // Build allowed origins list from environment variables
  const allowedOrigins = [
    process.env.FRONTEND_URL ?? 'http://localhost:5173',
    'https://placebo.mk', // Production domain
    'https://www.placebo.mk', // Also allow www subdomain
    process.env.PWA_URL ?? 'http://localhost:5174',
    process.env.STRAPI_URL ?? 'http://localhost:1337',
  ].filter(Boolean); // Remove any undefined/null values

  console.log('CORS enabled for origins:', allowedOrigins);

  app.enableCors({
    origin: allowedOrigins,
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'Accept', 'Origin'],
    exposedHeaders: ['Content-Range', 'X-Content-Range'],
    credentials: true,
    maxAge: 3600,
  });

  app.setGlobalPrefix('api/v1');

  // Apply global validation pipe
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
      forbidNonWhitelisted: true,
    }),
  );

  const port = process.env.PORT ?? 3000;
  const host = '0.0.0.0'; // Bind to all interfaces for Docker
  await app.listen(port, host);

  console.log(`Application is running on: http://${host}:${port}`);
}
void bootstrap();
