pub mod algorithms;
pub mod indieauth;
pub mod link_rel;
pub mod micropub;
pub mod webmention;

#[cfg(test)]
mod test;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("No {rel:?} endpoints were found at {url:?}")]
    NoEndpointsFound { rel: String, url: String },

    #[error(
        "The Webmention endpoint at {url:?} returned a unexpected status code of {status_code:?})"
    )]
    WebmentionUnsupportedStatusCode {
        status_code: reqwest::StatusCode,
        url: String,
    },

    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        std::mem::discriminant(self) == std::mem::discriminant(other)
    }
}

static IN_BUILT_APP_USER_AGENT: &str =
    concat!(env!("CARGO_PKG_NAME"), "-rs/", env!("CARGO_PKG_VERSION"));

/// Represents the base client interface for IndieWeb activity.
pub trait IConfiguration {
    /// Define the base request.
    fn request(&self, reason: Option<String>) -> reqwest::Client {
        let agent = if IN_BUILT_APP_USER_AGENT == self.user_agent() {
            IN_BUILT_APP_USER_AGENT.to_owned()
        } else {
            format!("{} {}", self.user_agent(), IN_BUILT_APP_USER_AGENT)
        };

        reqwest::Client::builder()
            .user_agent(format!(
                "{} ({})",
                agent,
                reason.unwrap_or_else(|| "A generic request".to_owned())
            ))
            .timeout(std::time::Duration::new(30, 0))
            .connect_timeout(std::time::Duration::new(30, 0))
            .connection_verbose(true)
            .build()
            .expect("Failed to construct HTTP client for IndieWeb interactivity")
    }

    /// The agent string to use when making out-going requests.
    fn user_agent(&self) -> &str {
        IN_BUILT_APP_USER_AGENT
    }
}

pub type Configuration = dyn IConfiguration + Send + Sync;
