//! Implements the `manta config set log` command.

use anyhow::Error;
use clap::ArgMatches;
use toml_edit::value;

use crate::cli::output::action_result;
use manta_shared::common::config::{read_config_toml, write_config_toml};

/// Set the logging verbosity level.
pub fn exec(cli_config_set_log: &ArgMatches) -> Result<(), Error> {
  let log_level: &String = cli_config_set_log
    .get_one("LOG_LEVEL")
    .ok_or_else(|| Error::msg("LOG_LEVEL argument is required"))?;

  set_log(log_level)
}

fn set_log(new_log_level_opt: &str) -> Result<(), Error> {
  let (path, mut doc) = read_config_toml()?;

  tracing::info!("Changing log verbosity level to {}", new_log_level_opt);

  doc["log"] = value(new_log_level_opt);

  write_config_toml(&path, &doc)?;

  match doc.get("log") {
    Some(log_level) => {
      action_result::print(&format!("log verbosity set to {log_level}"), None)?
    }
    None => tracing::error!(
      "'log' key missing from config after \
       writing — this should not happen"
    ),
  }

  Ok(())
}
