///|
/// HTTP metadata delivered by Envoy. Header names are lowercase. Only entries
/// explicitly selected by the service owner are exposed to the policy.
pub(all) struct Request {
  http_method : String
  path : String
  headers : Map[String, String]
}

///|
/// Allow supplies authoritative identity headers. Deny accepts 401 or 403.
/// Unavailable signals an operational failure to the gateway.
pub(all) enum Decision {
  Allow(Array[(String, String)])
  Deny(Int32)
  Unavailable
}

///|
#derive(Debug)
pub(all) suberror CheckError {
  InvalidRequest
  InvalidDecision
  PolicyUnavailable
  RequestTooLarge
}

///|
#derive(Debug)
pub suberror ConfigurationError {
  InvalidHeader(String)
}

///|
pub struct Service {
  priv policy : (Request) -> Decision
  priv allowed_headers : Array[String]
  priv identity_headers : Array[String]
}

///|
fn config_header_name(name : String) -> Bool {
  if name.is_empty() || name.length() > 128 {
    return false
  }
  for c in name {
    match c {
      'a'..<='z' | '0'..<='9' | '-' => ()
      _ => return false
    }
  }
  true
}

///|
/// Build a reusable service. Declare only the incoming headers the policy
/// reads and the outgoing x-auth-* or x-authenticated-* headers it owns.
pub fn Service::new(
  policy : (Request) -> Decision,
  allowed_headers~ : Array[String],
  identity_headers~ : Array[String],
) -> Service raise ConfigurationError {
  let seen : Map[String, Bool] = Map([])
  for name in allowed_headers {
    guard config_header_name(name) && !seen.contains(name) else {
      raise InvalidHeader(name)
    }
    seen[name] = true
  }
  for name in identity_headers {
    guard config_header_name(name) &&
      (
        (name.has_prefix("x-auth-") && name.length() > 7) ||
        (name.has_prefix("x-authenticated-") && name.length() > 16)
      ) &&
      !seen.contains(name) else {
      raise InvalidHeader(name)
    }
    seen[name] = true
  }
  {
    policy,
    allowed_headers: allowed_headers.copy(),
    identity_headers: identity_headers.copy(),
  }
}

///|
/// Evaluate the serialized Envoy v3 CheckRequest. The response bytes are a
/// CheckResponse only for completed decisions. Transport failures stay errors.
pub fn Service::check(self : Service, data : Bytes) -> Bytes raise CheckError {
  guard data.length() <= 65536 else { raise RequestTooLarge }
  let request = decode_request(data, self.allowed_headers) catch {
    _ => raise InvalidRequest
  }
  let decision = (self.policy)(request)
  if decision is Unavailable {
    raise PolicyUnavailable
  }
  encode_response(decision, self.identity_headers) catch {
    _ => raise InvalidDecision
  }
}