///|
/// RFC 9420 §8 Key Schedule, Pre-Shared Key Secret Chain (§8.4),
/// Transcript Hashes (§8.2), and MLS-Exporter (§8.5).

///|
/// All secrets derived for a single MLS epoch.
#derive(Eq, Debug)
pub(all) struct EpochSecrets {
  suite : @types.CipherSuite
  joiner_secret : Bytes
  welcome_secret : Bytes
  epoch_secret : Bytes
  sender_data_secret : Bytes
  encryption_secret : Bytes
  exporter_secret : Bytes
  epoch_authenticator : Bytes
  external_secret : Bytes
  confirmation_key : Bytes
  membership_key : Bytes
  resumption_psk : Bytes
  init_secret : Bytes
}

///|
/// RFC 9420 §8.4 Compute `psk_secret` from an ordered list of `(PreSharedKeyID, psk_bytes)`.
pub fn compute_psk_secret(
  suite : @types.CipherSuite,
  psks : Array[(@types.PreSharedKeyID, Bytes)],
) -> Bytes raise @types.MlsError {
  let nh = suite.hash_len()
  let mut psk_secret = @crypto.zeros(nh)
  let count = psks.length()
  if count > 65535 {
    raise @types.MlsError("too many PSKs in single epoch")
  }
  for i = 0; i < count; i = i + 1 {
    let (id, psk) = psks[i]
    let psk_extracted = @crypto.hkdf_extract(suite, @crypto.zeros(nh), psk)
    let w = @codec.Writer::new()
    @codec.encode_psk_id(w, id)
    w.write_u16(i.reinterpret_as_uint())
    w.write_u16(count.reinterpret_as_uint())
    let psk_input = @crypto.expand_with_label(
      suite,
      psk_extracted,
      "derived psk",
      w.to_bytes(),
      nh,
    )
    psk_secret = @crypto.hkdf_extract(suite, psk_input, psk_secret)
  }
  psk_secret
}

///|
/// Derive epoch secrets from an existing `joiner_secret` (used by Welcome joiners
/// and by `advance_epoch`).
pub fn EpochSecrets::from_joiner_secret(
  suite : @types.CipherSuite,
  joiner_secret : Bytes,
  psk_secret : Bytes,
  group_context_bytes : Bytes,
) -> EpochSecrets raise @types.MlsError {
  let nh = suite.hash_len()
  let effective_psk = if psk_secret.length() == 0 {
    @crypto.zeros(nh)
  } else {
    psk_secret
  }
  let member_secret = @crypto.hkdf_extract(suite, joiner_secret, effective_psk)
  let welcome_secret = @crypto.derive_secret(suite, member_secret, "welcome")
  let epoch_secret = @crypto.expand_with_label(
    suite, member_secret, "epoch", group_context_bytes, nh,
  )
  let sender_data_secret = @crypto.derive_secret(
    suite, epoch_secret, "sender data",
  )
  let encryption_secret = @crypto.derive_secret(
    suite, epoch_secret, "encryption",
  )
  let exporter_secret = @crypto.derive_secret(suite, epoch_secret, "exporter")
  let epoch_authenticator = @crypto.derive_secret(
    suite, epoch_secret, "authentication",
  )
  let external_secret = @crypto.derive_secret(suite, epoch_secret, "external")
  let confirmation_key = @crypto.derive_secret(suite, epoch_secret, "confirm")
  let membership_key = @crypto.derive_secret(suite, epoch_secret, "membership")
  let resumption_psk = @crypto.derive_secret(suite, epoch_secret, "resumption")
  let init_secret = @crypto.derive_secret(suite, epoch_secret, "init")
  {
    suite,
    joiner_secret,
    welcome_secret,
    epoch_secret,
    sender_data_secret,
    encryption_secret,
    exporter_secret,
    epoch_authenticator,
    external_secret,
    confirmation_key,
    membership_key,
    resumption_psk,
    init_secret,
  }
}

///|
/// RFC 9420 §8 Advance the key schedule by one epoch from `init_secret_prev`,
/// `commit_secret`, `psk_secret`, and the serialized new `GroupContext`.
pub fn EpochSecrets::advance(
  suite : @types.CipherSuite,
  init_secret_prev : Bytes,
  commit_secret : Bytes,
  psk_secret : Bytes,
  group_context_bytes : Bytes,
) -> EpochSecrets raise @types.MlsError {
  let nh = suite.hash_len()
  let intermediate = @crypto.hkdf_extract(
    suite, init_secret_prev, commit_secret,
  )
  let joiner_secret = @crypto.expand_with_label(
    suite, intermediate, "joiner", group_context_bytes, nh,
  )
  EpochSecrets::from_joiner_secret(
    suite, joiner_secret, psk_secret, group_context_bytes,
  )
}

///|
/// RFC 9420 §8.3 Derive `(welcome_key, welcome_nonce)` from `welcome_secret`.
pub fn welcome_key_nonce(
  suite : @types.CipherSuite,
  welcome_secret : Bytes,
) -> (Bytes, Bytes) raise @types.MlsError {
  let key = @crypto.expand_with_label(
    suite,
    welcome_secret,
    "key",
    b"",
    suite.aead_key_len(),
  )
  let nonce = @crypto.expand_with_label(
    suite,
    welcome_secret,
    "nonce",
    b"",
    suite.aead_nonce_len(),
  )
  (key, nonce)
}

///|
/// Derive the external HPKE key pair `(external_priv, external_pub)` for External Commits.
pub fn EpochSecrets::external_key_pair(self : EpochSecrets) -> (Bytes, Bytes) {
  @crypto.kem_derive_key_pair(self.suite, self.external_secret)
}

///|
/// RFC 9420 §8.5 MLS-Exporter(label, context, length).
pub fn EpochSecrets::export_secret(
  self : EpochSecrets,
  label : String,
  context : Bytes,
  length : Int32,
) -> Bytes raise @types.MlsError {
  let derived = @crypto.derive_secret(self.suite, self.exporter_secret, label)
  let ctx_hash = @crypto.hash(self.suite, context)
  @crypto.expand_with_label(self.suite, derived, "exported", ctx_hash, length)
}

///|
/// RFC 9420 §8.2 Compute `confirmed_transcript_hash` from the prior
/// `interim_transcript_hash` and the authenticated Commit content.
pub fn compute_confirmed_transcript_hash(
  suite : @types.CipherSuite,
  interim_transcript_hash_before : Bytes,
  wire_format : @types.WireFormat,
  content : @types.FramedContent,
  signature : Bytes,
) -> Bytes raise @types.MlsError {
  let w = @codec.Writer::new()
  w.write_raw(interim_transcript_hash_before)
  w.write_u16(wire_format.to_u16())
  @codec.encode_framed_content(w, content)
  w.write_vlbytes(signature)
  @crypto.hash(suite, w.to_bytes())
}

///|
/// RFC 9420 §8.2 Compute `interim_transcript_hash` from `confirmed_transcript_hash`
/// and `confirmation_tag`.
pub fn compute_interim_transcript_hash(
  suite : @types.CipherSuite,
  confirmed_transcript_hash : Bytes,
  confirmation_tag : Bytes,
) -> Bytes raise @types.MlsError {
  let w = @codec.Writer::new()
  w.write_raw(confirmed_transcript_hash)
  w.write_vlbytes(confirmation_tag)
  @crypto.hash(suite, w.to_bytes())
}

///|
/// RFC 9420 §8.1 Compute `confirmation_tag = MAC(confirmation_key, confirmed_transcript_hash)`.
pub fn compute_confirmation_tag(
  suite : @types.CipherSuite,
  confirmation_key : Bytes,
  confirmed_transcript_hash : Bytes,
) -> Bytes {
  @crypto.mac(suite, confirmation_key, confirmed_transcript_hash)
}