use cal_core::{AccountLite, Region};
use cal_core::device::device::DeviceStruct;
use crate::LocalCache;

/// Builds and stores region identifier mappings in the local cache.
///
/// # Arguments
/// * `reg` - Region to store locally
///
/// # Returns
/// * `()` - This function doesn't fail
pub fn build_region_identifiers_locally(local_cache: LocalCache, reg: &Region) {
    // Store the region in local cache
    local_cache.regions.insert(reg.id.to_string(), reg.clone());

    // Add primary identifier
    local_cache.region_idents.insert(reg.id.to_string(), reg.id.to_string());

    // Add alternative identifiers
    for vs in &reg.voice_servers {
        local_cache.region_idents.insert(vs.id.to_string(), reg.id.to_string());
        local_cache.region_idents.insert(vs.public_ip.to_string(), reg.id.to_string());
        local_cache.region_idents.insert(vs.private_ip.to_string(), reg.id.to_string());
    }
}

/// Populates the local account cache with account identifiers.
///
/// # Arguments
/// * `acc` - Account to cache locally
///
/// # Returns
/// * `()` - This function doesn't fail
pub fn build_account_identifiers_locally(local_cache: LocalCache, acc: &AccountLite) {
    // Store the account in local cache
    local_cache.accounts.insert(acc.id.clone(), acc.clone());

    // Add primary identifier to local cache
    local_cache.account_idents.insert(acc.id.clone(), acc.id.clone());

    // Add domain-based identifiers to local cache
    local_cache.account_idents.insert(
        format!("{}.connect.callable.io", acc.domain),
        acc.id.clone(),
    );

    // Add teams identifiers to local cache
    if !acc.teams.domain.is_empty() {
        local_cache.account_idents.insert(
            format!("{}.teams.callable.io", acc.teams.domain),
            acc.id.clone(),
        );
    }
}

