'use strict'
const {getErrorStatusCode, getOriginalError} = require('../../utils')
const errorHandlerFactory = require('./error-handler-factory')

const createTunnel = require('./create-tunnel')
const deleteTunnel = require('./delete-tunnel')
const connectivityTest = require('./connectivity-test')

module.exports = async function (app, {logger}) {
  app.route({
    method: 'POST',
    url: '/tunnels',
    handler: createTunnel.handler,
    errorHandler: errorHandlerFactory({
      logger,
      fieldExtractor: createTunnel.extractErrorLogFields,
      getStatusCode: getErrorStatusCode,
      getResponse: getOriginalError,
    }),
  })
  app.route({
    method: 'DELETE',
    url: '/tunnels/:tunnelId',
    handler: deleteTunnel.handler,
    errorHandler: errorHandlerFactory({
      logger,
      fieldExtractor: deleteTunnel.extractErrorLogFields,
      getStatusCode: getErrorStatusCode,
      getResponse: getOriginalError,
    }),
  })
  app.route({
    method: 'GET',
    url: '/tunnels/:tunnelId/connectivity-test',
    handler: connectivityTest.handler,
    errorHandler: errorHandlerFactory({
      logger,
      fieldExtractor: connectivityTest.extractErrorLogFields,
      getStatusCode: getErrorStatusCode,
      getResponse: getOriginalError,
    })
  })
  app.route({
    method: 'GET',
    url: '/tunnels',
    handler: async function(_request, reply){
      const tunnelIds = this.tunnelProcessManager.getRunningTunnels()
      return reply.status(200).send(tunnelIds)
    }
  })
}
