import io.opentelemetry.api.trace.Span

def url = parameters.get('url')
def email = inargs['email']
def language = session['ch.nevis.session.user.language'] ?: 'en'
def payload = '{ "email": "' + email + '", "language": "' + language + '"}'

try {
  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("traceparent", traceparent)
          .entity(Http.entity()
                  .content(payload)
                  .contentType("application/json")
               //   .charSet("utf-8")
                  .build())
          .build()
          .send(httpClient)

  LOG.info('Response Message: ' + httpResponse.reasonPhrase())
  LOG.info('Response Status Code: ' + httpResponse.code())
  LOG.info('Response: ' + httpResponse.bodyAsString())

  if (httpResponse.code() == 200) {
    response.setResult('ok')
  } else {
    LOG.error('Unexcpected HTTP response code: ' + httpResponse.code())
    response.setResult('error')
    response.setError(1, 'Unexpected HTTP reponse')
  }
} catch (all) {
  // Handle exception and set the transition
  LOG.error('error: ' + all, all)
  response.setResult('error')
  response.setError(1, 'Exception during HTTP call')
}