/**
 * This is not a production server yet!
 * This is only a minimal backend to get started.
 */

import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

import { AppModule } from './app/app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { MicroserviceOptions } from '@nestjs/microservices';
import * as fs from 'fs';

async function bootstrap() {
  const SSL = process.env.SSL;
  const CERT = process.env.SSL_CERT;
  const PRIV_KEY = process.env.SSL_PRIV_KEY;

  let httpsOptions = {};
  // let app : any;
  if (SSL == 'true') {
    httpsOptions = {
      key: fs.readFileSync(PRIV_KEY),
      cert: fs.readFileSync(CERT),
    };
  }
  const app =
    SSL 
      ? await NestFactory.create(AppModule, { httpsOptions })
      : await NestFactory.create(AppModule);
  // const globalPrefix = 'api';
  // app.setGlobalPrefix(globalPrefix);
  app.enableCors();

  app.connectMicroservice<MicroserviceOptions>({
    options: { host: '0.0.0.0', port: process.env.MICROSERVICE_PORT },
  });

  await app.startAllMicroservices();
  const config = new DocumentBuilder()
    .setTitle('Rag Service')
    .setDescription('Rag Service API description')
    .setVersion('1.0')
    .addBearerAuth(
      { type: 'http', name: 'authorization', in: 'header' },
      'authorization'
    )
    .addServer(`https://dial-ai.henceforthsolutions.com:3002/`, 'staging server')
    .addServer(`https://64c7-122-173-29-192.ngrok-free.app/`, 'ngrok server')
    .addServer(`http://localhost:${process.env.PORT}/`, 'local server')
    .build();
  const document = SwaggerModule.createDocument(app, config);

  SwaggerModule.setup('docs', app, document);
  const port = process.env.PORT || 3000;
  await app.listen(port);
  Logger.log(`🚀 Application is running on: http://localhost:${port}`);
}

bootstrap();
