///|
/// Native HTTP client using moonbitlang/core/async/http's ClientConnection

///|
/// Fetch URL using native HTTP client
pub async fn fetch(
  url : String,
  options~ : FetchOptions = FetchOptions::default(),
) -> HttpResponse raise HttpError {
  let prepared = prepare_fetch_options(url, options)
  // @async_http keys headers by `CaseInsensitiveString`, so lift the plain
  // `Map[String, String]` the crater API exposes into that key type.
  let request_headers : Map[@async_http.CaseInsensitiveString, String] = Map([])
  for k, v in prepared.headers {
    request_headers[@async_http.CaseInsensitiveString(k)] = v
  }
  let origin = extract_origin(url)
  let path : StringView = if origin.length() == url.length() {
    "/"
  } else {
    url[origin.length():]
  }
  // Keep connection setup separate from the request so InvalidUrl retains
  // the same meaning as it did with the previous host-based client.
  let client = @async_http.ClientConnection(origin, headers=request_headers) catch {
    _ => raise InvalidUrl(url)
  }
  defer client.close()
  let request_method = match prepared.http_method {
    "POST" => @async_http.RequestMethod::Post
    "PUT" => @async_http.RequestMethod::Put
    _ => @async_http.RequestMethod::Get
  }
  let (response, body_bytes) = try {
    client.request(request_method, path)
    if request_method != @async_http.RequestMethod::Get {
      client.text.write(prepared.body)
    }
    let response = client.end_request()
    (response, client.read_all())
  } catch {
    err => raise NetworkError(err.to_string())
  }
  let body = @utf8.decode(body_bytes[:]) catch { _ => "" }
  // Convert headers back to the plain lowercase-keyed map crater exposes
  let headers : Map[String, String] = Map([])
  for k, v in response.headers {
    headers[k.0.to_lower()] = v
  }
  let result = { status: response.code, headers, body, }
  enforce_cors_response(url, prepared, result)
}