use serde::{Deserialize, Serialize};

const HISTORY_CAP: usize = 100;
const HISTORY_PATH: &str = ".rok-studio/history.json";

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoryEntry {
    pub method: String,
    pub url: String,
    pub status: u16,
    pub elapsed_ms: u64,
}

#[derive(Debug, Default)]
pub struct History {
    pub entries: Vec<HistoryEntry>,
}

impl History {
    pub fn load() -> Self {
        let Ok(content) = std::fs::read_to_string(HISTORY_PATH) else {
            return Self::default();
        };
        let entries: Vec<HistoryEntry> = serde_json::from_str(&content).unwrap_or_default();
        Self { entries }
    }

    pub fn push(&mut self, entry: HistoryEntry) {
        self.entries.push(entry);
        if self.entries.len() > HISTORY_CAP {
            self.entries.remove(0);
        }
        self.save();
    }

    fn save(&self) {
        if let Ok(json) = serde_json::to_string_pretty(&self.entries) {
            let _ = std::fs::write(HISTORY_PATH, json);
        }
    }
}
