module WolfCore::HttpOperations

def async_http_get(**args)

def async_http_get(**args)
  puts "starting async_http_get"
  puts "async_http_get args are"
  pp args
  run_async do
    response = http_get(**args)
    puts "async_http_get response is"
    pp parse_http_response(response).to_h
  end
end

def async_http_post(**args)

def async_http_post(**args)
  puts "starting async_http_post"
  puts "async_http_post args are"
  pp args
  run_async do
    response = http_post(**args)
    puts "async_http_post response is"
    pp parse_http_response(response).to_h
  end
end

def async_http_put(**args)

def async_http_put(**args)
  puts "starting async_http_put"
  puts "async_http_put args are"
  pp args
  run_async do
    response = http_put(**args)
    puts "async_http_put response is"
    pp parse_http_response(response).to_h
  end
end

def http_get(url:, headers: {}, query: nil)

def http_get(url:, headers: {}, query: nil)
  WolfCore::HttpDataSource.http_get(url: url, headers: headers, query: query)
end

def http_post(url:, headers: {}, body: nil, query: nil)

def http_post(url:, headers: {}, body: nil, query: nil)
  WolfCore::HttpDataSource.http_post(url: url, headers: headers, query: query, body: body)
end

def http_put(url:, headers: {}, body: nil, query: nil)

def http_put(url:, headers: {}, body: nil, query: nil)
  WolfCore::HttpDataSource.http_put(url: url, headers: headers, query: query, body: body)
end

def parse_http_response(response)

def parse_http_response(response)
  body = JSON.parse(response.body) rescue response.body
  OpenStruct.new({
    code: response.code,
    body: body,
    message: response.message,
  })
end

def validate_http_response(response:, message:, error_data: nil)

def validate_http_response(response:, message:, error_data: nil)
  unless response.code == 200
    error_data = {
      message: message,
      response: parse_http_response(response)
    }.merge(error_data || {})
    raise_service_error(error_data)
  end
end