use crate::authentication::Authentication;
use crate::error::Error as ImageVaultError;
use crate::Client;

const DELETE_ENDPOINT: &'static str = "/apiv2/mediaservice/deletemediaitems";

/// Calls `mediaservice/deletemediaitems`.
///
/// Returns an `AuthenticationMissing` error
/// if the `Client` does not have any `Authentication` set.
///
/// ## Arguments
/// * `client` - The ImageVault `Client` to use.
/// * `media_item_ids` - The media item IDs to delete.
///
/// ## Examples
///
/// ```
/// use std::path::Path;
/// use imagevault::{
///     service::media_service,
///     Client,
///     authentication::ClientCredentialsAuthentication
/// };
///
/// # async fn test() -> Result<(), imagevault::error::Error> {
/// let authentication = ClientCredentialsAuthentication::default();
/// let client = Client::new(
///     "identity",
///     "secret",
///     "https://myimagevault.local"
///     )?
///     .with_authentication(authentication);
/// 
/// // Delete media items with IDs 42, 43 and 44
/// let delete_result = media_service::delete_media_items(&client, &vec![42, 43, 44]).await?;
/// # Ok(())
/// # }
/// ```
pub async fn delete_media_items<T: Authentication + Sync>(
    client: &Client<T>,
    media_item_ids: &[u64]
) -> Result<(), ImageVaultError> {
    let full_url = client.base_url.join(DELETE_ENDPOINT)?;
    let auth_unwrapped = client
        .authentication
        .as_ref()
        .ok_or_else(|| ImageVaultError::AuthenticationMissing)?;
    let auth_header = auth_unwrapped
        .lock()
        .await
        .authenticate(
            &client.client_identity,
            &client.client_secret,
            &client.base_url,
            &client.reqwest_client,
        )
        .await?;
    
    let response = client
        .reqwest_client
        .post(full_url)
        .bearer_auth(auth_header)
        .json(media_item_ids)
        .send()
        .await?;
    if let Err(err) = response.error_for_status_ref() {
        return Err(err.into());
    } else {
        return Ok(());
    }
}