use crate::fact::MemoFact;
use anyhow::Result;
use std::path::PathBuf;

pub struct GlobalStore {
    path: PathBuf,
}

impl GlobalStore {
    pub fn new() -> Self {
        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
        Self {
            path: PathBuf::from(home)
                .join(".bctx")
                .join("vault")
                .join("global.json"),
        }
    }

    pub fn load(&self) -> Result<Vec<MemoFact>> {
        if !self.path.exists() {
            return Ok(Vec::new());
        }
        let json = std::fs::read_to_string(&self.path)?;
        Ok(serde_json::from_str(&json)?)
    }

    pub fn save(&self, facts: &[MemoFact]) -> Result<()> {
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let json = serde_json::to_string_pretty(facts)?;
        std::fs::write(&self.path, json)?;
        Ok(())
    }
}

impl Default for GlobalStore {
    fn default() -> Self {
        Self::new()
    }
}
