use thiserror::Error;

#[derive(Error, Debug)]
pub enum KrakenError {
    #[error("HTTP request failed: {0}")]
    Http(#[from] reqwest::Error),

    #[error("Kraken API error: {0}")]
    Api(String),

    #[error(
        "Authentication required: set KRAKEN_API_KEY and KRAKEN_API_SECRET environment variables"
    )]
    AuthRequired,

    #[error("Invalid API response: {0}")]
    InvalidResponse(String),

    #[error("Rate limited — slow down requests")]
    RateLimited,

    #[error("Insufficient funds for this order")]
    InsufficientFunds,

    #[error("Unknown asset pair: {0}")]
    UnknownPair(String),

    #[error("Order not found: {0}")]
    OrderNotFound(String),
}

impl KrakenError {
    pub fn from_api_errors(errors: Vec<String>) -> Self {
        if errors.is_empty() {
            return KrakenError::Api("Unknown error".into());
        }
        let msg = errors.join("; ");
        if msg.contains("EAPI:Rate limit") {
            KrakenError::RateLimited
        } else if msg.contains("EOrder:Insufficient funds") {
            KrakenError::InsufficientFunds
        } else if msg.contains("EQuery:Unknown asset pair") {
            KrakenError::UnknownPair(msg)
        } else if msg.contains("EOrder:Unknown order") {
            KrakenError::OrderNotFound(msg)
        } else {
            KrakenError::Api(msg)
        }
    }
}
