const {
  extractEyesDataFromHeaders,
  extraceDataFromRequest,
  generateEgTunnelError,
} = require('../../utils')

module.exports = {handler, extractErrorLogFields}

const DELETE_TUNNEL_ACTION_NAME = 'delete-tunnel'

async function handler(request, reply) {
  const {apiKey, eyesServerUrl} = extractEyesDataFromHeaders(request)

  const {
    params: {tunnelId},
    query: {reason},
  } = request

  request.timer.reset()

  const stopTunnelErrors = [] // TODO: Handle stop tunnels errors

  try {
    await this.tunnelProcessManager.stop(tunnelId)
  } catch (error) {
    stopTunnelErrors.push(generateEgTunnelError(error, 500))
  }

  try {
    await this.egTunnelManager.deleteTunnel({
      tunnelId,
      apiKey,
      eyesServerUrl,
      reason: reason || 'CLIENT_REQUEST',
    })
  } catch (e) {
    stopTunnelErrors.push(e)
  }

  request.performance.stopTunnel = request.timer.getTime()

  if (stopTunnelErrors.length > 0) {
    throw stopTunnelErrors.length == 1
      ? stopTunnelErrors[0]
      : generateEgTunnelError(
          stopTunnelErrors.map(({error}) => error),
          500,
        )
  }

  this.logger.info({
    action: DELETE_TUNNEL_ACTION_NAME,
    tunnelId,
    success: true,
    performance: request.performance,
  })

  reply.code(200).header('Content-Type', 'application/json').send()
}

function extractErrorLogFields(error, request) {
  const {
    params: {tunnelId},
    performance,
  } = request

  return {
    action: DELETE_TUNNEL_ACTION_NAME,
    tunnelId,
    success: false,
    error,
    performance,
  }
}
