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

const INFO_ENDPOINT: &'static str = "/apiv2/assets/info";
/// Calls the `assets/info` endpoint.
///
/// Returns an `AuthenticationMissing` error
/// if the `Client` does not have any `Authentication` set.
///
/// ## Arguments
/// * `client` - The ImageVault `Client` to use.
///
/// ## Examples
///
/// ```
/// use imagevault::{
///     service::assets,
///     Client,
///     authentication::ClientCredentialsAuthentication
/// };
///
/// # async fn test() -> Result<(), Box<dyn std::error::Error>> {
/// let authentication = ClientCredentialsAuthentication::default();
/// let client = Client::new(
///     "identity",
///     "secret",
///     "https://myimagevault.local"
///     )?
///     .with_authentication(authentication);
///
/// let info = assets::info(&client).await?;
/// # Ok(())
/// # }
/// ```
pub async fn info<T: Authentication>(client: &Client<T>) -> Result<InfoResult, BoxedError> {
    let auth_unwrapped = client
        .authentication
        .as_ref()
        .ok_or_else(|| Error::AuthenticationMissing)?;
    let auth_header = auth_unwrapped
        .lock()
        .unwrap()
        .authenticate(
            &client.client_identity,
            &client.client_secret,
            &client.base_url,
            &client.reqwest_client,
        )
        .await?;
    let full_url = client.base_url.join(INFO_ENDPOINT)?;

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::authentication::DummyAuth;
    use crate::testutil::get_test_data;
    #[test]
    fn parse_info_result_test() {
        let mut rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            // setup mock HTTP response
            let mock = mockito::mock("GET", INFO_ENDPOINT)
                .expect(1)
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body(get_test_data("assets_info_result"))
                .create();

            let auth = DummyAuth::new();
            let client = Client::new("client_identity", "client_secret", &mockito::server_url())
                .unwrap()
                .with_authentication(auth);

            let info_result = info(&client).await;
            assert!(info_result.is_ok());
            mock.assert();
        });
    }

    #[test]
    fn info_fails_if_not_authenticated() {
        let mut rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let client: Client<DummyAuth> = Client::new(
                "client_identity",
                "client_secret",
                "https://whateveritwontbecalled.local",
            )
            .unwrap();

            let info_result = info(&client).await;
            assert!(info_result.is_err());
            let error_text = info_result.unwrap_err().to_string();
            assert!(error_text == Error::AuthenticationMissing.to_string());
        });
    }
}
