use super::{HetznerClient, Result, SshKey};
use serde::Deserialize;
use tracing::info;

pub struct SshKeyManager {
    client: HetznerClient,
}

#[derive(Debug, Deserialize)]
struct ListSshKeysResponse {
    ssh_keys: Vec<SshKey>,
}

impl SshKeyManager {
    pub fn new(client: HetznerClient) -> Self {
        Self { client }
    }

    /// List all SSH keys
    pub async fn list_ssh_keys(&self) -> Result<Vec<SshKey>> {
        let response: ListSshKeysResponse = self.client.get("/ssh_keys").await?;
        Ok(response.ssh_keys)
    }

    /// Get SSH key by name
    pub async fn get_ssh_key_by_name(&self, name: &str) -> Result<Option<SshKey>> {
        info!("Looking for SSH key: {}", name);
        let keys = self.list_ssh_keys().await?;
        Ok(keys.into_iter().find(|k| k.name == name))
    }

    /// Get SSH key ID by name
    pub async fn get_ssh_key_id_by_name(&self, name: &str) -> Result<Option<u64>> {
        Ok(self.get_ssh_key_by_name(name).await?.map(|k| k.id))
    }
}
