//! Policy command handlers (export, import, resign)

use std::process::ExitCode;

use aphoria::AphoriaConfig;

use crate::cli::PolicyCommands;

pub async fn handle_policy_command(command: PolicyCommands, config: &AphoriaConfig) -> ExitCode {
    match command {
        PolicyCommands::Export { name, output } => {
            match aphoria::export_policy(name, output, config).await {
                Ok(()) => {
                    println!("Policy exported successfully.");
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    eprintln!("Policy export error: {e}");
                    ExitCode::from(3)
                }
            }
        }
        PolicyCommands::Import { file } => match aphoria::import_policy(file, config).await {
            Ok(stats) => {
                println!("Policy imported successfully:");
                println!("  Assertions: {}", stats.assertions_imported);
                println!("  Aliases: {}", stats.aliases_imported);
                if stats.predicate_aliases_imported > 0 {
                    println!("  Predicate aliases: {}", stats.predicate_aliases_imported);
                }
                ExitCode::SUCCESS
            }
            Err(e) => {
                eprintln!("Policy import error: {e}");
                ExitCode::from(3)
            }
        },
        PolicyCommands::Resign { file, output, key, reason, chain_signatures } => {
            match aphoria::resign_policy(file, output, key, reason, chain_signatures).await {
                Ok(stats) => {
                    println!("Policy re-signed successfully:");
                    println!("  Assertions preserved: {}", stats.assertions_count);
                    println!("  Aliases preserved: {}", stats.aliases_count);
                    if stats.signature_chain_length > 0 {
                        println!("  Signature chain length: {}", stats.signature_chain_length);
                    }
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    eprintln!("Policy re-sign error: {e}");
                    ExitCode::from(3)
                }
            }
        }
    }
}
