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

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

  // ─── 🪖 Helmet: HTTP Security Headers ───────────────────────────────────────
  app.use(
    helmet({
      contentSecurityPolicy: {
        directives: {
          defaultSrc: ["'self'"],
          scriptSrc: ["'self'"],
          styleSrc: ["'self'", "'unsafe-inline'"],
          imgSrc: ["'self'", "data:", "https:"],
          connectSrc: ["'self'"],
          frameSrc: ["'none'"],
          objectSrc: ["'none'"],
        },
      },
      crossOriginEmbedderPolicy: false,
      hsts: {
        maxAge: 31536000,
        includeSubDomains: true,
        preload: true,
      },
      referrerPolicy: { policy: "strict-origin-when-cross-origin" },
      frameguard: { action: "deny" },
      noSniff: true,
      xssFilter: true,
    }),
  );

  // ─── 🌐 CORS Estrito ─────────────────────────────────────────────────────────
  const allowedOrigins = (process.env.ALLOWED_ORIGINS ?? "http://localhost:3000")
    .split(",")
    .map((o) => o.trim());

  app.enableCors({
    origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
      // Permite requests sem origem (ex: Postman, curl em dev) se em modo dev
      if (!origin && process.env.NODE_ENV !== "production") {
        return callback(null, true);
      }
      if (!origin || allowedOrigins.includes(origin)) {
        return callback(null, true);
      }
      callback(new Error(`Origem não autorizada: ${origin}`));
    },
    methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allowedHeaders: ["Content-Type", "Authorization", "x-tenant-id"],
    credentials: true,
    maxAge: 86400, // 24h preflight cache
  });

  // ─── 🔒 Global Prefix ────────────────────────────────────────────────────────
  app.setGlobalPrefix("api");

  // ─── 🚫 Input Validation & Sanitization ──────────────────────────────────────
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,             // Remove campos não declarados no DTO
      forbidNonWhitelisted: true,  // Rejeita requests com campos extras (400)
      transform: true,             // Transforma tipos automaticamente
      transformOptions: {
        enableImplicitConversion: true,
      },
      disableErrorMessages: process.env.NODE_ENV === "production", // Não expõe detalhes em prod
    }),
  );

  // ─── ⚠️ JWT_SECRET fraco detectado ──────────────────────────────────────────
  const jwtSecret = process.env.JWT_SECRET ?? "";
  if (!jwtSecret || jwtSecret === "dev-secret" || jwtSecret.length < 32) {
    console.warn("\n⚠️  [SECURITY WARNING] JWT_SECRET não definido ou muito fraco!");
    console.warn("   Gere um segredo forte com: openssl rand -base64 64");
    console.warn("   e defina-o em apps/api/.env como JWT_SECRET=<valor>\n");
  }

  const port = process.env.PORT ? Number(process.env.PORT) : 3333;
  await app.listen(port);
  console.log(`🚀 [API] Application is running on: http://localhost:${port}/api`);
  console.log(`📡 [API] Restarted successfully at ${new Date().toISOString()}`);
}

void bootstrap();
