//! Synor Storage SDK Error Types.

use std::fmt;

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

impl fmt::Display for StorageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StorageError::Request(msg) => write!(f, "Request error: {}", msg),
            StorageError::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)
                }
            }
            StorageError::Serialization(msg) => write!(f, "Serialization error: {}", msg),
            StorageError::Validation(msg) => write!(f, "Validation error: {}", msg),
            StorageError::Timeout => write!(f, "Request timed out"),
            StorageError::Io(msg) => write!(f, "IO error: {}", msg),
        }
    }
}

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

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

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

impl From<std::io::Error> for StorageError {
    fn from(err: std::io::Error) -> Self {
        StorageError::Io(err.to_string())
    }
}

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