///|
/// Cross-runtime JS/Edge `@runtime.HttpClient` built on global Web `fetch` + `AbortController`.
/// Aborts the underlying HTTP request immediately on timeout or MoonBit coroutine cancellation.

///|
#external
priv type JsAbortController

///|
extern "js" fn js_new_abort_controller() -> JsAbortController =
  #| () => new AbortController()

///|
extern "js" fn js_abort_controller_abort(
  ctrl : JsAbortController,
  reason : String,
) -> Unit =
  #| (ctrl, reason) => { try { ctrl.abort(reason); } catch (_) {} }

///|
extern "js" fn js_arm_timeout(
  ctrl : JsAbortController,
  timeout_ms : Int32,
) -> Unit =
  #| (ctrl, timeoutMs) => {
  #|   if (timeoutMs > 0) {
  #|     ctrl.__cialloTimer = setTimeout(() => {
  #|       try { ctrl.abort(new Error("timeout")); } catch (_) {}
  #|     }, timeoutMs);
  #|   }
  #| }

///|
extern "js" fn js_clear_timeout(ctrl : JsAbortController) -> Unit =
  #| (ctrl) => {
  #|   if (ctrl.__cialloTimer != null) {
  #|     clearTimeout(ctrl.__cialloTimer);
  #|     ctrl.__cialloTimer = null;
  #|   }
  #| }

///|
extern "js" fn js_fetch_request(
  url : String,
  meth : String,
  headers_flat : FixedArray[String],
  has_body : Bool,
  body_bytes : Bytes,
  ctrl : JsAbortController,
) -> @js_async.Promise[JsResponse] =
  #| (url, method, headersFlat, hasBody, bodyBytes, ctrl) => {
  #|   const headers = new Headers();
  #|   for (let i = 0; i + 1 < headersFlat.length; i += 2) {
  #|     headers.append(headersFlat[i], headersFlat[i + 1]);
  #|   }
  #|   const init = { method, headers, signal: ctrl.signal };
  #|   if (hasBody && method !== "GET" && method !== "HEAD") {
  #|     init.body = bodyBytes;
  #|   }
  #|   return fetch(url, init);
  #| }

///|
extern "js" fn js_resp_status(resp : JsResponse) -> Int32 =
  #| (resp) => resp.status | 0

///|
extern "js" fn js_resp_headers_flat(resp : JsResponse) -> FixedArray[String] =
  #| (resp) => {
  #|   const out = [];
  #|   if (resp.headers && typeof resp.headers.forEach === "function") {
  #|     resp.headers.forEach((v, k) => { out.push(String(k), String(v)); });
  #|   }
  #|   return out;
  #| }

///|
extern "js" fn js_resp_has_body(resp : JsResponse) -> Bool =
  #| (resp) => resp.body != null

///|
extern "js" fn js_resp_body_stream(
  resp : JsResponse,
) -> @js_async.JsReadableStream =
  #| (resp) => resp.body

///|
extern "js" fn js_resp_array_buffer_bytes(
  resp : JsResponse,
) -> @js_async.Promise[Bytes] =
  #| async (resp) => new Uint8Array(await resp.arrayBuffer())

///|
fn is_js_streaming_ct(ct : String) -> Bool {
  let lower = ct.to_lower()
  lower.contains("text/event-stream") || lower.contains("application/x-ndjson")
}

///|
/// JavaScript / Edge outbound HTTP client implementing `@runtime.HttpClient`.
pub struct FetchHttpClient {
  priv timeout_ms : Int32
}

///|
/// Creates a Fetch-based `@runtime.HttpClient` with `AbortController` timeout & cancellation support.
pub fn fetch_http_client(timeout_ms~ : Int32 = 30_000) -> FetchHttpClient {
  { timeout_ms, }
}

///|
pub impl @runtime.HttpClient for FetchHttpClient with fn send(self, req) -> @http.Response raise @runtime.RuntimeError {
  let pairs : Array[String] = []
  for pair in req.headers.entries() {
    pairs.push(pair.0)
    pairs.push(pair.1)
  }
  let headers_flat = FixedArray::from_array(pairs)
  let (has_body, body_bytes) : (Bool, Bytes) = match req.body {
    @http.Body::Empty => (false, b"")
    @http.Body::Text(s) => (true, @utf8.encode(s))
    @http.Body::Bytes(b) => (true, b)
    @http.Body::Stream(_) => {
      let collected = req.body.read_all_bytes() catch {
        err =>
          raise @runtime.RuntimeError::IoFailure(
            "failed reading request body stream: \{err}",
          )
      }
      (true, collected)
    }
  }
  let ctrl = js_new_abort_controller()
  js_arm_timeout(ctrl, self.timeout_ms)
  let completed = Ref(false)
  defer {
    js_clear_timeout(ctrl)
    if !completed.val {
      js_abort_controller_abort(ctrl, "cancelled")
    }
  }
  let req_url = req.url.to_string()
  let js_resp = js_fetch_request(
    req_url,
    req.meth.as_str(),
    headers_flat,
    has_body,
    body_bytes,
    ctrl,
  ).wait() catch {
    err => {
      let msg = err.to_string()
      if msg.contains("timeout") || msg.contains("AbortError") {
        raise @runtime.RuntimeError::Timeout(
          "fetch request to \{req_url} aborted/timed out: \{msg}",
        )
      }
      raise @runtime.RuntimeError::IoFailure(
        "fetch request to \{req_url} failed: \{msg}",
      )
    }
  }
  let status = js_resp_status(js_resp)
  let resp_flat = js_resp_headers_flat(js_resp)
  let resp_headers = @http.Headers::Headers()
  let mut i = 0
  while i + 1 < resp_flat.length() {
    resp_headers.append(resp_flat[i], resp_flat[i + 1])
    i += 2
  }
  let ct = resp_headers.get("content-type").unwrap_or("")
  if is_js_streaming_ct(ct) && js_resp_has_body(js_resp) {
    completed.val = true
    js_clear_timeout(ctrl)
    let reader = @js_async.ReadableStream::from_js(js_resp_body_stream(js_resp))
    let stream = @http.ByteStream::ByteStream(next_chunk=() => reader.read(), cancel=reason => {
      js_abort_controller_abort(ctrl, reason)
      reader.close()
    })
    return @http.Response::Response(
      status~,
      headers=resp_headers,
      body=@http.Body::Stream(stream),
    )
  }
  let out_bytes = js_resp_array_buffer_bytes(js_resp).wait() catch {
    err => {
      let msg = err.to_string()
      if msg.contains("timeout") || msg.contains("AbortError") {
        raise @runtime.RuntimeError::Timeout(
          "fetch response body from \{req_url} aborted/timed out: \{msg}",
        )
      }
      raise @runtime.RuntimeError::IoFailure(
        "failed reading fetch response body: \{msg}",
      )
    }
  }
  completed.val = true
  let body : @http.Body = if out_bytes.is_empty() {
    @http.Body::Empty
  } else {
    @http.Body::Bytes(out_bytes)
  }
  @http.Response::Response(status~, headers=resp_headers, body~)
}