///|
/// COSE_Encrypt (RFC 9052 ยง5.1). Tag 96 when `tagged` is true.
pub(all) struct Encrypt {
  tagged : Bool
  protected_header : Protected
  unprotected : Header
  ciphertext : Bytes?
  recipients : Array[Recipient]
} derive(Eq)

///|
pub extend Encrypt with Eq::{equal}

///|
#deprecated("Use `!=` instead", skip_current_package=true)
#doc(hidden)
pub extend Encrypt with Eq::{not_equal}

///|
/// Decode a tagged (96) or untagged COSE_Encrypt array.
pub fn Encrypt::decode(bytes : Bytes) -> Encrypt raise CoseError {
  let (tagged, items) = decode_message(bytes, 96UL, 4, "COSE_Encrypt")
  let raw = cbor_bstr_field(items[0], "protected header")
  let protected_header = Protected::from_raw(raw)
  let unprotected = Header::from_cbor(items[1])
  reject_shared_header_labels(protected_header.header, unprotected)
  let ciphertext = match cbor_unwrap(items[2]) {
    @cbor.Bytes(b) => Some(b)
    @cbor.Simple(22) => None
    _ => raise BadStructure("ciphertext must be a byte string or null")
  }
  {
    tagged,
    protected_header,
    unprotected,
    ciphertext,
    recipients: decode_recipients(items[3]),
  }
}

///|
/// Encode this COSE_Encrypt, using tag 96 when `tagged` is true.
pub fn Encrypt::encode(self : Encrypt) -> Bytes {
  encode_tagged(96UL, self.tagged, [
    @cbor.Bytes(self.protected_header.raw),
    self.unprotected.to_cbor(),
    payload_to_cbor(self.ciphertext),
    encode_recipients(self.recipients),
  ])
}

///|
/// Encrypt for one or more recipients. A recipient may itself contain
/// recipients. Each layer wraps the key of the layer above it: the top
/// layer wraps `cek`, and a nested layer wraps its parent's KEK.
/// `direct` recipients must hold that next-layer key and cannot nest.
/// A partial IV is XORed onto the Base IV of a direct recipient whose
/// key bytes are `cek`.
pub fn Encrypt::encrypt(
  protected_header : Header,
  unprotected : Header,
  plaintext : Bytes,
  external_aad : Bytes,
  cek : Bytes,
  recipients : Array[RecipientInput],
  tagged~ : Bool = true,
) -> Encrypt raise CoseError {
  if recipients.length() == 0 {
    raise BadStructure("COSE_Encrypt needs at least one recipient")
  }
  reject_shared_header_labels(protected_header, unprotected)
  let prot = Protected::from_header(protected_header)
  let alg = resolve_alg(prot.header, unprotected)
  let base = base_iv_for_direct_cek(recipients, cek)
  let iv = resolve_iv(alg, prot.header, unprotected, base)
  let built = seal_recipients(recipients, cek, alg)
  let aad = enc_structure("Encrypt", prot.raw, external_aad)
  {
    tagged,
    protected_header: prot,
    unprotected,
    ciphertext: Some(content_seal(alg, cek, iv, aad, plaintext)),
    recipients: built,
  }
}

///|
/// Open the message with one recipient key. The key's kid must match when both sides have one.
pub fn Encrypt::decrypt(
  self : Encrypt,
  external_aad : Bytes,
  key : CoseKey,
) -> Bytes raise CoseError {
  self.decrypt_with(external_aad, [key])
}

///|
/// Open the message with any of `keys`. Nested recipients are unwrapped
/// from the inside out; a leaf key is not used as the content key.
/// Every successfully unwrapped CEK is tried. A path whose key unwraps
/// but fails content authentication does not suppress another path.
pub fn Encrypt::decrypt_with(
  self : Encrypt,
  external_aad : Bytes,
  keys : Array[CoseKey],
) -> Bytes raise CoseError {
  let mut parent : CoseAlg? = None
  try {
    parent = Some(resolve_alg(self.protected_header.header, self.unprotected))
  } catch {
    _ => ()
  }
  let candidates = content_keys(self.recipients, keys, parent)
  let alg = match parent {
    Some(value) => value
    None => resolve_alg(self.protected_header.header, self.unprotected)
  }
  let mut last : CoseError = DecryptionFailed
  for i = 0; i < candidates.length(); i = i + 1 {
    let cek = candidates[i]
    try {
      let iv = resolve_iv(
        alg,
        self.protected_header.header,
        self.unprotected,
        base_iv_for(keys, cek),
      )
      let aad = enc_structure(
        "Encrypt",
        self.protected_header.raw,
        external_aad,
      )
      match self.ciphertext {
        None => raise DecryptionFailed
        Some(ct) => return content_open(alg, cek, iv, aad, ct)
      }
    } catch {
      err => last = err
    }
  }
  raise last
}