///|
/// What a request gives to prove who sends it: the access token of the
/// `Authorization: Bearer` header or of the `access_token` query value. The
/// debug representation shows `[REDACTED]` for the token.
#derive(Eq, Debug)
pub(all) struct Credentials {
  token : AccessToken?
}

///|
pub extend Credentials with Eq::{equal, not_equal}

///|
pub extend Credentials with @debug.Debug::{to_repr}

///|
/// Who a connection belongs to: an optional user ID, and the claims that the
/// authenticator gives. An identity with no user ID is anonymous.
#derive(Eq, Debug)
pub struct Identity {
  priv user_id : UserId?
  priv claims : ReadOnlyArray[(String, String)]
}

///|
pub extend Identity with Eq::{equal, not_equal}

///|
pub extend Identity with @debug.Debug::{to_repr}

///|
/// The identity with no user ID and no claims.
pub fn Identity::anonymous() -> Identity {
  { user_id: None, claims: ReadOnlyArray::from_array([]), }
}

///|
/// The identity of the user `user_id` with `claims`. A claim name can come more
/// than one time, for example `role`.
pub fn Identity::user(
  user_id : UserId,
  claims~ : ArrayView[(String, String)] = [],
) -> Identity {
  { user_id: Some(user_id), claims: ReadOnlyArray::from_array(claims), }
}

///|
/// The user ID, or `None` for an anonymous identity.
pub fn Identity::user_id(self : Identity) -> UserId? {
  self.user_id
}

///|
/// The claims in their order.
pub fn Identity::claims(self : Identity) -> Iter[(String, String)] {
  self.claims.iter()
}

///|
/// True when the identity has the claim `name` with `value`.
pub fn Identity::has_claim(
  self : Identity,
  name : String,
  value : String,
) -> Bool {
  self.claims.iter().any(claim => claim.0 == name && claim.1 == value)
}

///|
/// The refusal of an authenticator. The reason is for the log of the server;
/// the client gets only the status 401.
#derive(Eq, Debug)
pub(all) suberror AuthRejected {
  AuthRejected(String)
}

///|
pub extend AuthRejected with Eq::{equal, not_equal}

///|
pub extend AuthRejected with @debug.Debug::{to_repr}

///|
/// A request target with each `id` and `access_token` query value replaced by
/// `[REDACTED]`, for a log line. The value of `id` is the connection token.
pub fn redact_target(target : String) -> String {
  guard target.find("?") is Some(at) else { return target }
  let parts = target[at + 1:]
    .split("&")
    .map(part => {
      let name = match part.find("=") {
        Some(eq) => part[:eq].to_owned()
        None => part.to_owned()
      }
      // The server percent-decodes the names, so `%69d` is also `id`.
      let plain = (@percent.decode(name) catch { _ => name }).to_lower()
      if plain == "id" || plain == "access_token" {
        "\{name}=\{redacted}"
      } else {
        part.to_owned()
      }
    })
    .collect()
  target[:at + 1].to_owned() + parts.join("&")
}