use std::fmt;

/// Error type returned by BigDataCloud API calls.
#[derive(Debug)]
pub enum Error {
    /// The API returned a non-2xx HTTP status.
    Api {
        status_code: u16,
        endpoint: String,
        body: String,
    },
    /// A network or transport error occurred.
    Http(reqwest::Error),
    /// JSON deserialisation failed.
    Json(serde_json::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Api { status_code, endpoint, .. } =>
                write!(f, "BigDataCloud API error {} on '{}'", status_code, endpoint),
            Error::Http(e) => write!(f, "HTTP error: {}", e),
            Error::Json(e) => write!(f, "JSON error: {}", e),
        }
    }
}

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

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

impl From<serde_json::Error> for Error {
    fn from(e: serde_json::Error) -> Self { Error::Json(e) }
}

pub type Result<T> = std::result::Result<T, Error>;
