// r8r: rust port of n8n.io
// Initial author: Michael Cochran <mcochran@cochranblock.org>
// Built for: Tanner Woodrum, intended cofounder
// License: Unlicense (public domain dedication, see UNLICENSE)

use super::error::NodeError;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::path::Path;

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CredentialStore {
    #[serde(flatten)]
    pub creds: HashMap<String, HashMap<String, Value>>,
}

impl CredentialStore {
    pub fn from_toml_file<P: AsRef<Path>>(path: P) -> Result<Self, NodeError> {
        let raw = std::fs::read_to_string(path)?;
        let store: CredentialStore = toml::from_str(&raw)
            .map_err(|e| NodeError::Other(format!("credentials toml: {e}")))?;
        Ok(store)
    }

    pub fn get(&self, name: &str) -> Option<&HashMap<String, Value>> {
        self.creds.get(name)
    }

    pub fn field(&self, name: &str, field: &str) -> Result<&Value, NodeError> {
        self.creds
            .get(name)
            .ok_or_else(|| NodeError::MissingCredential(name.to_string()))?
            .get(field)
            .ok_or_else(|| NodeError::MissingCredential(format!("{name}.{field}")))
    }
}
