import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import cors from 'cors';
import express from 'express';
import * as bodyParser from 'body-parser';
import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common';
import { ExpressAdapter } from '@nestjs/platform-express';
import { join } from 'path';

async function bootstrap() {
  const expressApp = express();

  // 1️⃣ Raw body ONLY for Stripe webhook – must come before Nest attaches
  expressApp.use(
    '/billing/webhook',
    bodyParser.raw({ type: 'application/json' }),
  );

  // 2️⃣ Attach Nest to this same Express instance
  const app = await NestFactory.create(
    AppModule,
    new ExpressAdapter(expressApp),
  );
  app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
  // app.use(bodyParser.json());
  // app.use(bodyParser.urlencoded({ extended: true }));

  // 3️⃣ CORS
  const allowed = new Set([
    'http://localhost:3000',
    'http://localhost:3001',
    'http://localhost:3002',
    'http://localhost:4200',
    'http://localhost:5173',
    'https://trytalento.glmaagencyprojects.com',
    'http://webtrytalento.glmaagencyprojects.com',
    'https://webtrytalento.glmaagencyprojects.com',
  ]);
  app.use(
    cors({
      origin: (origin, cb) =>
        !origin || allowed.has(origin) ? cb(null, true) : cb(new Error('CORS')),
      methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'],
      allowedHeaders: ['Authorization', 'Content-Type', 'Stripe-Signature'],
      credentials: true,
      optionsSuccessStatus: 204,
    }),
  );

  app.use(bodyParser.json({ limit: '500mb' }));
  app.use(bodyParser.urlencoded({ limit: '500mb', extended: true }));

  // 4️⃣ Validation
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );

  // 5️⃣ Static uploads
  app.use('/uploads', express.static(join(__dirname, '..', 'uploads')));

  await app.listen(process.env.PORT ?? 3002);
  console.log(
    `🚀 Server running on http://localhost:${process.env.PORT ?? 3002}`,
  );
}
bootstrap();