//! Non-Apple platforms: OS credential store via the `keyring` crate (no biometric ACL).

use crate::errors::{SafeError, SafeResult};

pub(super) const SERVICE_NAME: &str = "tsafe";

pub fn store_password(profile: &str, password: &str) -> SafeResult<()> {
    let entry = keyring::Entry::new(SERVICE_NAME, profile).map_err(|e| SafeError::Crypto {
        context: format!("keyring init: {e}"),
    })?;
    entry
        .set_password(password)
        .map_err(|e| SafeError::Crypto {
            context: format!("keyring store: {e}"),
        })?;
    Ok(())
}

pub fn retrieve_password(profile: &str) -> SafeResult<Option<String>> {
    let entry = keyring::Entry::new(SERVICE_NAME, profile).map_err(|e| SafeError::Crypto {
        context: format!("keyring init: {e}"),
    })?;
    match entry.get_password() {
        Ok(pw) => Ok(Some(pw)),
        Err(keyring::Error::NoEntry) => Ok(None),
        Err(e) => Err(SafeError::Crypto {
            context: format!("keyring retrieve: {e}"),
        }),
    }
}

pub fn remove_password(profile: &str) -> SafeResult<()> {
    let entry = keyring::Entry::new(SERVICE_NAME, profile).map_err(|e| SafeError::Crypto {
        context: format!("keyring init: {e}"),
    })?;
    match entry.delete_credential() {
        Ok(()) => Ok(()),
        Err(keyring::Error::NoEntry) => Ok(()),
        Err(e) => Err(SafeError::Crypto {
            context: format!("keyring delete: {e}"),
        }),
    }
}

pub fn has_password(profile: &str) -> bool {
    keyring::Entry::new(SERVICE_NAME, profile)
        .and_then(|e| e.get_password())
        .is_ok()
}

pub(super) fn quick_unlock_storage_note(_profile: &str) -> Option<String> {
    // Heuristic: returns a storage-tier classification. Not a cryptographic guarantee.
    None
}
