use crate::{authentication::Authentication, data::VersionResult, Client};
type BoxedError = Box<dyn std::error::Error>;

const VERSION_ENDPOINT: &'static str = "/apiv2/info/version";

/// Calls the `info/version` endpoint.
///
/// ## Arguments
/// * `client` - The ImageVault `Client` to use.
///
/// ## Examples
///
/// ```
/// use imagevault::{
///     service::info,
///     Client,
///     authentication::ClientCredentialsAuthentication
/// };
///
/// # async fn test() -> Result<(), Box<dyn std::error::Error>> {
/// // Authentication is optional for this endpoint,
/// // but is most likely needed for further API calls.
/// let authentication = ClientCredentialsAuthentication::default();
/// let client = Client::new(
///     "identity",
///     "secret",
///     "https://myimagevault.local"
///     )?
///     .with_authentication(authentication);
///
/// let version = info::version(&client).await?;
/// # Ok(())
/// # }
/// ```
pub async fn version<T: Authentication>(client: &Client<T>) -> Result<VersionResult, BoxedError> {
    let version_url = client.base_url.join(VERSION_ENDPOINT)?;

    let response = client.reqwest_client.get(version_url).send().await?;
    if let Err(err) = response.error_for_status_ref() {
        return Err(Box::new(err));
    } else {
        let result = response.json::<VersionResult>().await?;
        return Ok(result);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::authentication::DummyAuth;
    use crate::testutil::get_test_data;
    #[test]
    fn version_test() {
        let mut rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            // setup mock HTTP response
            let mock = mockito::mock("GET", VERSION_ENDPOINT)
                .expect(1)
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body(get_test_data("info_version_result"))
                .create();
            let auth = DummyAuth::new();
            let client = Client::new("client_identity", "client_secret", &mockito::server_url())
                .unwrap()
                .with_authentication(auth);

            let version_result = version(&client).await;
            assert!(version_result.is_ok());
            mock.assert();
        });
    }
}
