use coap_message::error::RenderableOnMinimal;

/// Error type for manipulation of [`MessageMut`][crate::inmemory::MessageMut] mutable messages.
///
/// This is presented externally as an internal server error, but has enough structure to be useful
/// for debugging through `dbg!()`.
#[derive(Debug, thiserror::Error)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum WriteError {
    #[error("operations did not adhere to required sequence")]
    OutOfSequence,
    #[error("no space in buffer")]
    OutOfSpace,
}

impl RenderableOnMinimal for WriteError {
    type Error<IE: RenderableOnMinimal + core::fmt::Debug> = IE;
    fn render<M: coap_message::MinimalWritableMessage>(
        self,
        msg: &mut M,
    ) -> Result<(), Self::Error<M::UnionError>> {
        coap_message_utils::Error::internal_server_error().render::<M>(msg)
    }
}

impl From<core::convert::Infallible> for WriteError {
    fn from(never: core::convert::Infallible) -> Self {
        match never {}
    }
}

#[test]
fn test_error_format() {
    extern crate std;
    use std::{format, string::String};

    fn render(e: &dyn core::error::Error) -> String {
        format!("{e}")
    }
    // Not necessarily *exactly* like that text, but something like it, and implementing Error
    assert_eq!(render(&WriteError::OutOfSpace), "no space in buffer");
}
