// Query decoding follows the first-call behavior of uWebSockets QueryParser.h.
// MoonBit adaptation and modifications by justjavac, 2026.
// Authored by Alex Hultman, 2018-2020. See LICENSE-APACHE and NOTICE.
// Intellectual property of third-party.

///|
/// Applies upstream's permissive digit arithmetic, deliberately without hex validation.
fn query_digit(byte : Byte) -> Int32 {
  let number = byte.to_int() - b'0'.to_int()
  if number > 9 {
    (number & 223) - 7
  } else {
    number
  }
}

///|
/// Decodes a selected query value into independent immutable bytes.
fn decode_query_value(value : BytesView) -> Bytes? {
  let output = @buffer.Buffer(capacity=value.length())
  for offset = 0; offset < value.length(); {
    let byte = value[offset]
    if byte == b'%' {
      guard value.length() - offset >= 3 else { return None }
      output.write_byte(
        (query_digit(value[offset + 1]) * 16 + query_digit(value[offset + 2])).to_byte(),
      )
      continue offset + 3
    } else {
      output.write_byte(if byte == b'+' { b' ' } else { byte })
      continue offset + 1
    }
  }
  Some(output.to_bytes())
}

///|
/// Returns the first query entry whose raw, undecoded key equals `key` exactly.
/// Empty keys, missing entries, and truncated percent escapes return `None`.
/// `Valueless` distinguishes flags from `Value(b"")`. Values map `+` to SP and
/// use upstream's permissive percent arithmetic, so invalid hex pairs are not
/// rejected. Decoded NUL/obs-text is preserved. Repeated lookup is deterministic
/// and never modifies the target or other entries, unlike upstream's in-place API.
pub fn Request::get_query_value(self : Request, key : BytesView) -> QueryValue? {
  guard !key.is_empty() && self.get_query() is Some(query) else { return None }
  for offset = 0; offset < query.length(); {
    let end = offset + find_byte_scalar(query[offset:], b'&')
    let statement = query[offset:end]
    let equal = find_byte_scalar(statement, b'=')
    if statement[:equal] == key {
      if equal == statement.length() {
        return Some(Valueless)
      }
      return decode_query_value(statement[equal + 1:]).map(value => Value(value))
    }
    continue end + 1
  }
  None
}