//! Synor RPC SDK Error Types.

use std::fmt;

/// RPC SDK error type.
#[derive(Debug)]
pub enum RpcError {
    /// HTTP request failed.
    Request(String),
    /// API returned an error.
    Api {
        message: String,
        status_code: u16,
        code: Option<String>,
    },
    /// JSON serialization/deserialization failed.
    Serialization(String),
    /// WebSocket connection error.
    WebSocket(String),
    /// Invalid input provided.
    Validation(String),
    /// Request timed out.
    Timeout,
}

impl fmt::Display for RpcError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RpcError::Request(msg) => write!(f, "Request error: {}", msg),
            RpcError::Api {
                message,
                status_code,
                code,
            } => {
                if let Some(c) = code {
                    write!(f, "API error [{}]: {} (status {})", c, message, status_code)
                } else {
                    write!(f, "API error: {} (status {})", message, status_code)
                }
            }
            RpcError::Serialization(msg) => write!(f, "Serialization error: {}", msg),
            RpcError::WebSocket(msg) => write!(f, "WebSocket error: {}", msg),
            RpcError::Validation(msg) => write!(f, "Validation error: {}", msg),
            RpcError::Timeout => write!(f, "Request timed out"),
        }
    }
}

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

impl From<reqwest::Error> for RpcError {
    fn from(err: reqwest::Error) -> Self {
        if err.is_timeout() {
            RpcError::Timeout
        } else {
            RpcError::Request(err.to_string())
        }
    }
}

impl From<serde_json::Error> for RpcError {
    fn from(err: serde_json::Error) -> Self {
        RpcError::Serialization(err.to_string())
    }
}

/// Result type alias for RPC operations.
pub type Result<T> = std::result::Result<T, RpcError>;
