// SPDX-License-Identifier: Apache-2.0

use crate::MdbClient;

use std::process::ExitCode;

use anyhow::{Context, Result};
use clap::Parser;

/// Retrieve a sample from the server and check that the user is part of a group
/// which is able to access the file's originating source.
#[derive(Parser, Clone, Debug, PartialEq)]
pub struct RetrieveSample {
    /// The hash of the file to retrieve
    pub hash: String,

    /// Whether or not to download the sample wrapped in a `CaRT` file
    #[arg(long, action, default_value_t = false)]
    pub cart: bool,
}

impl RetrieveSample {
    pub async fn exec(&self, config: &MdbClient) -> Result<ExitCode> {
        let _bytes = hex::decode(&self.hash).context("Provided hash wasn't valid hexidecimal")?;

        let file_name = if self.cart {
            format!("{}.cart", self.hash)
        } else {
            self.hash.clone()
        };

        let contents = config
            .retrieve(&self.hash, self.cart)
            .await
            .context("failed to retrieve sample")?;
        std::fs::write(&file_name, contents).context("failed to write file to disk")?;

        Ok(ExitCode::SUCCESS)
    }
}

#[test]
fn verify_cli() {
    use clap::CommandFactory;

    RetrieveSample::command().debug_assert();
}
