use std::fmt;

pub type TransportResult<T> = Result<T, TransportError>;

#[derive(Debug)]
pub enum TransportError {
    Io(std::io::Error),
    InvalidEndpoint(String),
    InvalidQueryLength(usize),
    Protocol(String),
    Closed,
}

impl fmt::Display for TransportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(error) => error.fmt(f),
            Self::InvalidEndpoint(message) => write!(f, "{message}"),
            Self::InvalidQueryLength(length) => write!(
                f,
                "q query string length {length} exceeds 32-bit q IPC capacity"
            ),
            Self::Protocol(message) => write!(f, "{message}"),
            Self::Closed => write!(f, "connection is closed"),
        }
    }
}

impl std::error::Error for TransportError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
            _ => None,
        }
    }
}

impl From<std::io::Error> for TransportError {
    fn from(value: std::io::Error) -> Self {
        Self::Io(value)
    }
}
