const { ServiceConfig } = require('./config/ServiceConfig')
const { loadEnvironmentFiles } = require('./config/loadEnvironmentFiles')
const { NewsApplication } = require('./app/NewsApplication')

/**
 * Bootstrap
 *
 * Starts the news microservice and wires process lifecycle handlers.
 */
class Bootstrap {
  constructor() {
    loadEnvironmentFiles()
    const serviceConfig = new ServiceConfig()
    this._application = new NewsApplication(serviceConfig.toRuntimeConfig())
  }

  /**
   * @returns {Promise<void>}
   */
  async run() {
    await this._application.start()
    this._registerShutdownHooks()
  }

  /**
   * @returns {void}
   */
  _registerShutdownHooks() {
    const shutdown = async () => {
      await this._application.stop()
      process.exit(0)
    }
    process.on('SIGINT', shutdown)
    process.on('SIGTERM', shutdown)
  }
}

new Bootstrap().run().catch((error) => {
  console.error(error)
  process.exit(1)
})