//! RPC error types.

/// Status codes for RPC responses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum RpcStatus {
    /// Request succeeded.
    Ok = 0,
    /// Client sent a malformed request.
    BadRequest = 1,
    /// Authentication required or token invalid.
    Unauthorized = 2,
    /// Caller lacks permission for this operation.
    Forbidden = 3,
    /// Requested resource not found.
    NotFound = 4,
    /// Rate limit exceeded.
    RateLimited = 5,
    /// Request deadline exceeded (server-side timeout).
    DeadlineExceeded = 8,
    /// Server is shutting down (draining).
    Unavailable = 9,
    /// Internal server error.
    Internal = 10,
    /// Method not recognized.
    UnknownMethod = 11,
}

impl RpcStatus {
    /// Decode a status byte. Returns `None` for unknown values.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0 => Some(Self::Ok),
            1 => Some(Self::BadRequest),
            2 => Some(Self::Unauthorized),
            3 => Some(Self::Forbidden),
            4 => Some(Self::NotFound),
            5 => Some(Self::RateLimited),
            8 => Some(Self::DeadlineExceeded),
            9 => Some(Self::Unavailable),
            10 => Some(Self::Internal),
            11 => Some(Self::UnknownMethod),
            _ => None,
        }
    }
}

/// Errors that can occur in the RPC layer.
#[derive(Debug, thiserror::Error)]
pub enum RpcError {
    #[error("connection error: {0}")]
    Connection(String),

    #[error("encoding error: {0}")]
    Encode(String),

    #[error("decoding error: {0}")]
    Decode(String),

    #[error("server returned error status {status:?}: {message}")]
    Server {
        status: RpcStatus,
        message: String,
    },

    #[error("request timed out")]
    Timeout,

    #[error("stream closed unexpectedly")]
    StreamClosed,

    #[error("payload too large: {size} bytes (max {max})")]
    PayloadTooLarge { size: usize, max: usize },
}
