//! Network commands.

use anyhow::Result;

use crate::client::RpcClient;
use crate::output::{self, OutputFormat};

/// Add a peer.
pub async fn add_peer(client: &RpcClient, address: &str, format: OutputFormat) -> Result<()> {
    let success = client.add_peer(address).await?;

    match format {
        OutputFormat::Json => {
            let result = serde_json::json!({
                "success": success,
                "address": address,
            });
            println!("{}", serde_json::to_string_pretty(&result)?);
        }
        OutputFormat::Text => {
            if success {
                output::print_success(&format!("Added peer: {}", address));
            } else {
                output::print_error(&format!("Failed to add peer: {}", address));
            }
        }
    }

    Ok(())
}

/// Ban a peer.
pub async fn ban_peer(client: &RpcClient, peer: &str, format: OutputFormat) -> Result<()> {
    let success = client.ban_peer(peer).await?;

    match format {
        OutputFormat::Json => {
            let result = serde_json::json!({
                "success": success,
                "peer": peer,
            });
            println!("{}", serde_json::to_string_pretty(&result)?);
        }
        OutputFormat::Text => {
            if success {
                output::print_success(&format!("Banned peer: {}", peer));
            } else {
                output::print_error(&format!("Failed to ban peer: {}", peer));
            }
        }
    }

    Ok(())
}

/// Unban a peer.
pub async fn unban_peer(client: &RpcClient, peer: &str, format: OutputFormat) -> Result<()> {
    let success = client.unban_peer(peer).await?;

    match format {
        OutputFormat::Json => {
            let result = serde_json::json!({
                "success": success,
                "peer": peer,
            });
            println!("{}", serde_json::to_string_pretty(&result)?);
        }
        OutputFormat::Text => {
            if success {
                output::print_success(&format!("Unbanned peer: {}", peer));
            } else {
                output::print_error(&format!("Failed to unban peer: {}", peer));
            }
        }
    }

    Ok(())
}
