import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { ValidationPipe, Logger } from '@nestjs/common';
import cookieParser from 'cookie-parser';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';

async function bootstrap() {
  // ---- Fail-fast on missing critical secrets ----
  const jwtSecret = process.env.JWT_SECRET;
  if (!jwtSecret || jwtSecret.length < 32) {
    throw new Error('JWT_SECRET must be set and at least 32 characters');
  }
  if (!process.env.CRON_SECRET) {
    throw new Error('CRON_SECRET must be set');
  }
  if (process.env.NODE_ENV === 'production') {
    const webOriginEnv = process.env.WEB_ORIGIN;
    if (!webOriginEnv || webOriginEnv === '*') {
      throw new Error('WEB_ORIGIN must be set to a specific origin in production (not "*")');
    }
    for (const o of webOriginEnv.split(',').map((s) => s.trim())) {
      if (!o.startsWith('https://')) {
        throw new Error(`All WEB_ORIGIN values must use HTTPS in production: ${o}`);
      }
    }
  }

  const app = await NestFactory.create(AppModule, {
    bufferLogs: true,
  });

  // ---- Security headers ----
  app.use(helmet({
    hsts: { maxAge: 31536000, includeSubDomains: true },
  }));

  // ---- Cookie parser (for JWT cookie) ----
  app.use(cookieParser());

  // ---- CORS ----
  const webOrigin = process.env.WEB_ORIGIN || 'http://localhost:3001';
  app.enableCors({
    origin: webOrigin.split(',').map((o) => o.trim()),
    credentials: true,
  });

  // ---- Global validation ----
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      transformOptions: { enableImplicitConversion: true },
    }),
  );

  // ---- Global exception filter ----
  app.useGlobalFilters(new AllExceptionsFilter());

  // ---- API prefix ----
  app.setGlobalPrefix('api', { exclude: ['health'] });

  const port = parseInt(process.env.API_PORT || '4001', 10);
  const host = process.env.API_HOST || '127.0.0.1';

  await app.listen(port, host);
  Logger.log(`🚀 Vihar Sewa API running on http://${host}:${port}`, 'Bootstrap');
  Logger.log(`📍 CORS allowed origin: ${webOrigin}`, 'Bootstrap');
}

bootstrap().catch((err) => {
  // eslint-disable-next-line no-console
  console.error('Failed to start API:', err);
  process.exit(1);
});
