import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ValidationPipe } from '@nestjs/common';
import { default as helmet } from 'helmet';

import { AppModule } from './app.module';
import { DatabaseService } from './database/database.service';

const bootstrap = async () => {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: ['log', 'error', 'warn'],
    cors: process.env.NODE_ENV === 'development'
  });

  app.set('trust proxy', 1);

  app.setGlobalPrefix('api');

  app.useGlobalPipes(
    new ValidationPipe({
      transform: false,
      whitelist: true
    })
  );

  const database: DatabaseService = app.get(DatabaseService);

  database.enableShutdownHooks(app);

  // app.use(helmet());

  await app.listen(process.env.PORT || 4200);
};

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire; // eslint-disable-line
const mainModule = __non_webpack_require__.main;
const moduleFilename = (mainModule && mainModule.filename) || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  bootstrap().catch(console.error);
}
