'use strict'
const fastify = require('fastify')
const {version} = require('../package.json')

module.exports = createApp

function createApp({
  egTunnelManagerUrl = 'https://exec-wus.applitools.com',
  tunnelConfigFileDirectory,
  logFileDirectory,
  runTunnelBinPath,
  socks5Proxies,
  portRange,
  logger,
}) {
  const app = fastify()
  app.decorate('logger', logger)

  // Add functions and objects for performance tests
  app.addHook('preHandler', (request, reply, done) => {
    const startTime = Date.now()
    request.durationFromPerHandler = () => Date.now() - startTime

    let time
    request.timer = {
      reset: () => {
        time = Date.now()
      },
      getTime: () => Date.now() - time,
      getTimeInSeconds: () => (Date.now() - time) / 1000,
    }

    request.performance = {}
    done()
  })

  app.get('/healthz', async () => ({version}))

  logger.info({action: 'create-app', success: true})

  app.register(require('./plugins/tunnel-process-manager-plugin'), {
    env: {
      tunnelConfigFileDirectory,
      logFileDirectory,
      runTunnelBinPath,
      socks5Proxies,
      portRange,
    },
  })

  app.register(require('./plugins/execution-grid-tunnel-manager'), {
    env: {
      egTunnelManagerUrl: egTunnelManagerUrl,
    },
  })

  app.register(require('./routes/tunnels'), {logger})

  return app
}
