use crate::db::Database;
use crate::identity::{IdKeyData, escape};
use std::path::Path;
use std::process::exit;

pub fn show_key(db_path: &Path, search: String, expose_secret: bool) -> anyhow::Result<()> {
    let db = Database::load_or_create(db_path)?;

    let matches = db.fuzzy_search(search);

    if matches.len() > 1 {
        println!("there were multiple best matches, showing all");
    } else if matches.is_empty() {
        println!("no matches found");
        exit(0);
    }

    for each_match in &matches {
        println!("match: {:?}", each_match);

        let show_sk = expose_secret && matches!(each_match.keys, IdKeyData::Local(..));

        if !show_sk {
            println!(
                "   pk: sage/{}/{}/{}",
                each_match.keys.pk()?,
                escape(each_match.name.clone()),
                escape(each_match.email.clone())
            );
        } else {
            let IdKeyData::Local(k) = &each_match.keys else {
                continue;
            };
            println!(
                "   sk: sage/{}/{}/{}",
                k,
                escape(each_match.name.clone()),
                escape(each_match.email.clone())
            );
        }
    }

    Ok(())
}
