import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import type { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'node:path';
import { AppModule } from './app.module';
import { apiConfig } from './config/app.config';
import cookieParser from 'cookie-parser';
import helmet from 'helmet';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.use(helmet());
  app.use(cookieParser());
  app.useStaticAssets(join(__dirname, '..', 'public'), {
    prefix: '/public/',
  });

  // --- CORS tracking logs ---
  // console.log('[CORS DEBUG] NODE_ENV:', process.env.NODE_ENV);
  // console.log(
  //   '[CORS DEBUG] Raw CORS_ORIGIN env value:',
  //   JSON.stringify(process.env.CORS_ORIGIN),
  // );

  const corsOrigin = process.env.CORS_ORIGIN?.trim()
    ? process.env.CORS_ORIGIN.split(',')
        .map((origin) => origin.trim())
        .filter(Boolean)
    : false;

  // console.log('[CORS DEBUG] Parsed corsOrigin value:', corsOrigin);
  if (corsOrigin === false) {
    console.warn(
      '[CORS WARNING] CORS_ORIGIN is not set or empty — all cross-origin requests will be BLOCKED.',
    );
  }

  app.enableCors({
    origin: (requestOrigin, callback) => {
      // Log every incoming request's Origin header and whether it was allowed
      const isAllowed =
        !requestOrigin || // same-origin / non-browser requests have no Origin header
        (Array.isArray(corsOrigin) && corsOrigin.includes(requestOrigin));

      // console.log(
      //   `[CORS CHECK] Incoming Origin: "${requestOrigin}" | Allowed: ${isAllowed} | Configured origins: ${JSON.stringify(corsOrigin)}`,
      // );

      if (isAllowed) {
        callback(null, true);
      } else {
        callback(new Error(`Origin "${requestOrigin}" not allowed by CORS`), false);
      }
    },
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
  });

  app.setGlobalPrefix(apiConfig.prefix);

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true, // strip unknown properties
      forbidNonWhitelisted: true, // reject requests with unknown properties
      transform: true, // auto-transform payloads to DTO instances
    }),
  );

  await app.listen(
    process.env.PORT ? Number(process.env.PORT) : apiConfig.port,
  );
  console.log(
    `🚀 Server is running on port:${process.env.PORT ?? apiConfig.port}/${apiConfig.prefix}`,
  );
}
bootstrap();
