import io.opentelemetry.api.trace.Span

def url = parameters.get('url')

def email = inargs['email']
def token = inargs['captcha_response']?: 'MISSING'
def enabled = (session['agov.recovery.captchaSettings.enabled']?:'true').toBoolean()

def ip = request.getLoginContext()['connection.HttpHeader.X-Real-IP'] ?: 'unknown'
def userAgent = request.getLoginContext()['connection.HttpHeader.user-agent'] ?: request.getLoginContext()['connection.HttpHeader.User-Agent'] ?: 'unknown'

def payload = "{ \"userIp\": \"${ip}\", \"email\": \"${email}\", \"userAgent\": \"${userAgent}\" }"

LOG.debug('Token: ' + token)
LOG.debug('Payload: ' + payload)

try {

  if (!enabled) {
    LOG.info("FriendlyCAPTCHA is disabled, allowing operation for ${payload}")
    response.setResult('ok')
    return
  }

  def spanCtxt = Span.current().getSpanContext()
  def traceparent = "00-${spanCtxt.getTraceId()}-${spanCtxt.getSpanId()}-${spanCtxt.getTraceFlags().asHex()}"

  def httpClient = HttpClients.create(parameters)
  def httpResponse = Http.post()
          .url(url)
          .header("Accept", "application/json")
          .header("X-FriendlyCAPTCHA-Token", token)
          .header("traceparent", traceparent)
          .entity(Http.entity()
                  .content(payload)
                  .contentType("application/json")
                  .build())
          .build()
          .send(httpClient)

  LOG.debug('Response Status Code: ' + httpResponse.code())
  LOG.debug('Response: ' + httpResponse.bodyAsString())

  if (httpResponse.code() == 200) {
      if (httpResponse.bodyAsString().contains('SUCCESSFUL')) {
          response.setResult('ok')
          return
       } else {
       LOG.warn("Friendly captcha not successful for '{ \"userIp\": \"${ip}\", \"email\": \"${email}\", \"userAgent\": \"${userAgent}\" }'")
       response.setResult('exit.1')
       return      
     }
  } else {
    LOG.error("Friendly captcha failed with statuscode ${httpResponse.code()} for '{ \"userIp\": \"${ip}\", \"email\": \"${email}\", \"userAgent\": \"${userAgent}\" }'")
    response.setResult('error')
    response.setError(1, 'Unexpected HTTP reponse')
  }
} catch (all) {
  // Handle exception and set the transition
  LOG.error("Friendly captcha failed with a general error '${all}' for '{ \"userIp\": \"${ip}\", \"email\": \"${email}\", \"userAgent\": \"${userAgent}\" }', service-url: ${url}")
  response.setResult('error')
  response.setError(1, 'Exception during HTTP call')
}