use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json as json;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LocalizationBundleSnapshot {
    pub locale_code: String,
    pub values: HashMap<String, String>,
}

#[derive(Clone)]
pub struct LocalizationStore {
    bundles: HashMap<String, LocalizationBundleSnapshot>,
}

impl LocalizationStore {
    pub fn new() -> Self {
        let mut bundles = HashMap::new();
        bundles.insert(
            "en".to_string(),
            load_bundle(
                "en",
                include_str!("../../../contracts/localization/en.json"),
            ),
        );
        bundles.insert(
            "sv".to_string(),
            load_bundle(
                "sv",
                include_str!("../../../contracts/localization/sv.json"),
            ),
        );
        Self { bundles }
    }

    pub fn bundle(&self, locale_code: &str) -> Option<LocalizationBundleSnapshot> {
        let Some(bundle) = self.bundles.get(locale_code) else {
            return None;
        };
        Some(bundle.clone())
    }
}

fn load_bundle(locale_code: &str, raw: &str) -> LocalizationBundleSnapshot {
    let values: HashMap<String, String> = json::from_str(raw).expect("valid localization bundle");
    LocalizationBundleSnapshot {
        locale_code: locale_code.to_string(),
        values,
    }
}
