use crate::authentication::Authentication;
use crate::data::Category;
use crate::error::Error;
use crate::Client;

type BoxedError = Box<dyn std::error::Error>;
const GET_CATEGORIES_ENDPOINT: &'static str = "/apiv2/categoryservice/getcategories";

/// Calls `categoryservice/getcategories`.
///
/// Returns an `AuthenticationMissing` error
/// if the `Client` does not have any `Authentication` set.
///
/// ## Arguments
/// * `client` - The ImageVault `Client` to use.
///
/// ## Examples
///
/// ```
/// use imagevault::{
///     service::category_service,
///     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 categories = category_service::get_categories(&client).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_categories<T: Authentication>(
    client: &Client<T>,
) -> Result<Vec<Category>, 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(GET_CATEGORIES_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::<Vec<Category>>().await?;
        return Ok(result);
    }
}

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

            let categories = get_categories(&client).await;
            assert!(categories.is_ok());
            mock.assert();
            assert!(categories.unwrap().len() > 0);
        });
    }
}
