//! Token-Storage im Windows Credential Manager (keyring-Crate).
//! Analog zur Mac-App (Keychain): mgc_-Session-Token + DNS-Token
//! liegen NIE im Frontend/localStorage.

use keyring::Entry;

const SERVICE: &str = "org.rebreak.magic";
const SESSION_KEY: &str = "session-token";
const DNS_KEY: &str = "dns-token";

fn entry(key: &str) -> Result<Entry, String> {
    Entry::new(SERVICE, key).map_err(|e| format!("Credential-Store-Fehler: {e}"))
}

pub fn save_session_token(token: &str) -> Result<(), String> {
    entry(SESSION_KEY)?
        .set_password(token)
        .map_err(|e| format!("Token speichern fehlgeschlagen: {e}"))
}

pub fn load_session_token() -> Option<String> {
    entry(SESSION_KEY).ok()?.get_password().ok()
}

pub fn save_dns_token(token: &str) -> Result<(), String> {
    entry(DNS_KEY)?
        .set_password(token)
        .map_err(|e| format!("DNS-Token speichern fehlgeschlagen: {e}"))
}

pub fn load_dns_token() -> Option<String> {
    entry(DNS_KEY).ok()?.get_password().ok()
}

pub fn clear_all() {
    if let Ok(e) = entry(SESSION_KEY) {
        let _ = e.delete_credential();
    }
    if let Ok(e) = entry(DNS_KEY) {
        let _ = e.delete_credential();
    }
}
