use crate::{AuthIndex, ExodusError, NetworkCurve};

use ghost_traits::exodus::IdentifierConverter;

impl IdentifierConverter<AuthIndex, ExodusError> for NetworkCurve {
    fn convert_identifier_to_index(
        identifier_bytes: &[u8],
    ) -> Result<AuthIndex, ExodusError> {
        const SIZE: usize = core::mem::size_of::<AuthIndex>();

        let start = identifier_bytes.len().checked_sub(SIZE)
            .ok_or(ExodusError::InvalidParticipantId)?;

        let bytes_array = identifier_bytes.get(start..)
            .and_then(|slice| slice.try_into().ok())
            .ok_or(ExodusError::InvalidParticipantId)?;

        AuthIndex::from_be_bytes(bytes_array)
            .checked_sub(1)
            .ok_or(ExodusError::InvalidParticipantId)
    }

    fn non_zero_index(index: AuthIndex) -> Result<AuthIndex, ExodusError> {
        index.checked_add(1).ok_or(ExodusError::InvalidParticipantId)
    }
}
