//! Synor Wallet SDK error types.

use std::fmt;

/// Result type for wallet operations.
pub type Result<T> = std::result::Result<T, WalletError>;

/// Wallet SDK error.
#[derive(Debug)]
pub enum WalletError {
    /// HTTP request error.
    Http(reqwest::Error),
    /// API error response.
    Api {
        /// HTTP status code.
        status_code: u16,
        /// Error message.
        message: String,
        /// Error code.
        code: Option<String>,
    },
    /// Client is closed.
    ClientClosed,
    /// Invalid configuration.
    InvalidConfig(String),
    /// Serialization error.
    Serialization(serde_json::Error),
}

impl fmt::Display for WalletError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            WalletError::Http(e) => write!(f, "HTTP error: {}", e),
            WalletError::Api {
                status_code,
                message,
                code,
            } => {
                if let Some(code) = code {
                    write!(f, "API error [{}]: {} (status {})", code, message, status_code)
                } else {
                    write!(f, "API error: {} (status {})", message, status_code)
                }
            }
            WalletError::ClientClosed => write!(f, "Client is closed"),
            WalletError::InvalidConfig(msg) => write!(f, "Invalid configuration: {}", msg),
            WalletError::Serialization(e) => write!(f, "Serialization error: {}", e),
        }
    }
}

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

impl From<reqwest::Error> for WalletError {
    fn from(error: reqwest::Error) -> Self {
        WalletError::Http(error)
    }
}

impl From<serde_json::Error> for WalletError {
    fn from(error: serde_json::Error) -> Self {
        WalletError::Serialization(error)
    }
}
