use crate::cache::{get_hash, get_str, BB8Pool, CacheError};
use cal_core::AccountLite;
use log::{debug, info};

pub async fn get_account_by_ident_lite(
    pool: &BB8Pool,
    key: &str,
) -> Result<Option<AccountLite>, CacheError> {
    let result = get_hash(pool, "cb:accounts", key).await;
    match result {
        Ok(r) => match r {
            None => {
                info!("get_account_by_ident_lite({}) Redis Result None", key);
                Ok(None)
            }
            Some(value) => {
                //HASH values created by Java Redisson have unwanted " in value so remove them
                let fixed_str = value.replace("\"", "");
                debug!(
                    "get_account_by_ident_lite({}) Redis Result {}",
                    key, fixed_str
                );
                get_account_by_id_lite(pool, &fixed_str).await
            }
        },
        Err(e) => Err(e),
    }
}

pub async fn get_account_by_id_lite(
    pool: &BB8Pool,
    key: &str,
) -> Result<Option<AccountLite>, CacheError> {
    let _key = format!("cb:account:{}", key);
    let result = get_str(pool, &_key).await;
    match result {
        Ok(r) => match r {
            None => {
                info!("get_account_by_id_lite({}) Redis Result None", &_key);
                Ok(None)
            }
            Some(value) => {
                let account: AccountLite = serde_json::from_str(&value).unwrap();
                debug!(
                    "get_account_by_id_lite({}) Redis Result {}",
                    &_key, account.name
                );
                Ok(Some(account))
            }
        },
        Err(e) => Err(e),
    }
}
