// @generated — session persistence version authority
// Generated by `xtask protocol-codegen` from `SessionPersistenceVersionAuthorityMachine` transitions.

use std::fmt;

pub const SESSION_VERSION: u32 = 2;
pub const STORED_INPUT_STATE_VERSION: u32 = 3;
pub const SESSION_METADATA_SCHEMA_VERSION: u32 = 2;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionPersistenceVersionField {
    SessionEnvelope,
    StoredInputState,
    SessionMetadataSchema,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionPersistenceVersionAuthorityError {
    field: SessionPersistenceVersionField,
    current: u32,
    observed: u32,
}

impl fmt::Display for SessionPersistenceVersionAuthorityError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "generated session persistence version authority rejected {:?}: expected current {}, got {}",
            self.field, self.current, self.observed
        )
    }
}

impl std::error::Error for SessionPersistenceVersionAuthorityError {}

fn restore_version(
    field: SessionPersistenceVersionField,
    observed: u32,
    current: u32,
) -> Result<u32, SessionPersistenceVersionAuthorityError> {
    if observed == current {
        Ok(current)
    } else {
        Err(SessionPersistenceVersionAuthorityError {
            field,
            current,
            observed,
        })
    }
}

#[must_use]
pub fn session_envelope_version() -> u32 {
    SESSION_VERSION
}

#[must_use]
pub fn stored_input_state_version() -> u32 {
    STORED_INPUT_STATE_VERSION
}

#[must_use]
pub fn session_metadata_schema_version() -> u32 {
    SESSION_METADATA_SCHEMA_VERSION
}

pub fn restore_session_envelope_version(
    observed: u32,
) -> Result<u32, SessionPersistenceVersionAuthorityError> {
    restore_version(
        SessionPersistenceVersionField::SessionEnvelope,
        observed,
        SESSION_VERSION,
    )
}

pub fn restore_stored_input_state_version(
    observed: u32,
) -> Result<u32, SessionPersistenceVersionAuthorityError> {
    restore_version(
        SessionPersistenceVersionField::StoredInputState,
        observed,
        STORED_INPUT_STATE_VERSION,
    )
}

pub fn restore_session_metadata_schema_version(
    observed: u32,
) -> Result<u32, SessionPersistenceVersionAuthorityError> {
    restore_version(
        SessionPersistenceVersionField::SessionMetadataSchema,
        observed,
        SESSION_METADATA_SCHEMA_VERSION,
    )
}
