use crate::cli::ConfigCommands;
use crate::config::Config;
use crate::error::{CliError, Result};
use crate::output::{print_info, print_success};
pub async fn execute(cmd: &ConfigCommands) -> Result<()> {
match cmd {
ConfigCommands::Set { key, value } => set_config(key, value).await,
ConfigCommands::Get { key } => get_config(key).await,
ConfigCommands::List => list_config().await,
ConfigCommands::Reset => reset_config().await,
}
}
async fn set_config(key: &str, value: &str) -> Result<()> {
let mut config = Config::load()?;
match key {
"server.url" => config.server.url = value.to_string(),
"output.format" => {
if !["table", "json", "yaml"].contains(&value) {
return Err(CliError::InvalidInput(format!(
"Invalid output format: {}. Must be one of: table, json, yaml",
value
)));
}
config.output.format = value.to_string();
}
"output.color" => {
config.output.color = value.parse().map_err(|_| {
CliError::InvalidInput("output.color must be 'true' or 'false'".to_string())
})?;
}
"log.level" => {
if !["error", "warn", "info", "debug"].contains(&value) {
return Err(CliError::InvalidInput(format!(
"Invalid log level: {}. Must be one of: error, warn, info, debug",
value
)));
}
config.log.level = value.to_string();
}
_ => {
return Err(CliError::InvalidInput(format!("Unknown config key: {}", key)));
}
}
config.save()?;
print_success(&format!("Set {} = {}", key, value));
Ok(())
}
async fn get_config(key: &str) -> Result<()> {
let config = Config::load()?;
let value = match key {
"server.url" => &config.server.url,
"output.format" => &config.output.format,
"output.color" => return Ok(print_info(&format!("{} = {}", key, config.output.color))),
"log.level" => &config.log.level,
_ => {
return Err(CliError::InvalidInput(format!("Unknown config key: {}", key)));
}
};
print_info(&format!("{} = {}", key, value));
Ok(())
}
async fn list_config() -> Result<()> {
let config = Config::load()?;
print_info("Current configuration:");
println!();
println!("server.url = {}", config.server.url);
println!("output.format = {}", config.output.format);
println!("output.color = {}", config.output.color);
println!("log.level = {}", config.log.level);
println!();
print_info(&format!("Accounts: {}", config.accounts.len()));
Ok(())
}
async fn reset_config() -> Result<()> {
let config = Config::default();
config.save()?;
print_success("Configuration reset to defaults");
Ok(())
}