//! Typed access to the free-form `settings.*` map from the loaded config.

use loco_rs::prelude::*;

use crate::models::shop_settings;

/// Look up a string-valued `settings.<key>` entry, returning `None` if config
/// has no settings map, the key is missing, or the value is not a string.
pub fn get<'a>(ctx: &'a AppContext, key: &str) -> Option<&'a str> {
    ctx.config
        .settings
        .as_ref()
        .and_then(|settings| settings.get(key))
        .and_then(|value| value.as_str())
}

/// Look up an admin-editable setting in the database, falling back to config when
/// the row is missing. Empty DB values are returned as-is so admins can clear a
/// setting deliberately.
pub async fn get_editable(ctx: &AppContext, key: &str) -> Result<String> {
    Ok(match shop_settings::Entity::get(&ctx.db, key).await? {
        Some(value) => value,
        None => get(ctx, key).unwrap_or("").to_string(),
    })
}

pub async fn bank_details(ctx: &AppContext) -> Result<(String, String)> {
    Ok((
        get_editable(ctx, "bank_iban").await?,
        get_editable(ctx, "bank_account_name").await?,
    ))
}
