use super::PassageRun;
use anyhow::Result;
use std::path::PathBuf;

pub struct PassageStore {
    path: PathBuf,
}

impl PassageStore {
    pub fn new(base: PathBuf) -> Self {
        Self {
            path: base.join("passages.json"),
        }
    }

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

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