//! Implements the `manta get boot-parameters` command.

use anyhow::Error;

use crate::common::app_context::AppContext;
use crate::common::clap_ext::ArgMatchesExt;
use crate::http_client::MantaClient;
use crate::output;
use manta_shared::types::params::boot_parameters::GetBootParametersParams;

/// Parse CLI arguments into typed [`GetBootParametersParams`].
fn parse_boot_parameters_params(
  cli_args: &clap::ArgMatches,
  settings_hsm_group_name_opt: Option<&str>,
) -> GetBootParametersParams {
  GetBootParametersParams {
    hsm_group: cli_args.opt_string("group"),
    nodes: cli_args.opt_string("nodes"),
    settings_hsm_group_name: settings_hsm_group_name_opt.map(String::from),
  }
}

/// CLI adapter for `manta get boot-parameters`.
///
/// Parses CLI arguments into typed parameters, delegates to
/// the service layer, and formats the output.
pub async fn exec(
  ctx: &AppContext<'_>,
  token: &str,
  cli_args: &clap::ArgMatches,
) -> Result<(), Error> {
  let params =
    parse_boot_parameters_params(cli_args, ctx.settings_hsm_group_name_opt);

  let server_url = ctx.manta_server_url;
  let boot_parameters = MantaClient::new(server_url, ctx.site_name)?
    .get_boot_parameters(token, &params)
    .await?;

  output::boot_parameters::print(&boot_parameters)?;

  Ok(())
}

#[cfg(test)]
mod tests {
  use super::*;

  fn boot_params_cmd() -> clap::Command {
    crate::build::get::subcommand_get_boot_parameters()
  }

  #[test]
  fn parse_nodes_only_leaves_group_unset() {
    let matches = boot_params_cmd().get_matches_from([
      "boot-parameters",
      "--nodes",
      "x1000c0s0b0n0",
    ]);
    let params = parse_boot_parameters_params(&matches, None);
    assert!(params.hsm_group.is_none());
    assert_eq!(params.nodes.as_deref(), Some("x1000c0s0b0n0"));
    assert!(params.settings_hsm_group_name.is_none());
  }

  #[test]
  fn parse_hsm_group() {
    let matches = boot_params_cmd().get_matches_from([
      "boot-parameters",
      "--group",
      "compute",
    ]);
    let params = parse_boot_parameters_params(&matches, None);
    assert_eq!(params.hsm_group.as_deref(), Some("compute"));
  }

  #[test]
  fn parse_settings_hsm_group_preserved_alongside_nodes() {
    let matches = boot_params_cmd().get_matches_from([
      "boot-parameters",
      "--nodes",
      "x1000c0s0b0n0",
    ]);
    let params = parse_boot_parameters_params(&matches, Some("default-group"));
    assert_eq!(
      params.settings_hsm_group_name.as_deref(),
      Some("default-group")
    );
  }
}
