use std::fs;
use std::path::PathBuf;

use serde::Deserialize;

#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct Config {
    pub min_size: Option<String>,
    pub skip: Vec<String>,
    pub only: Vec<String>,
    pub exclude: Vec<String>,
    pub max_depth: Option<usize>,
    pub no_global: Option<bool>,
}

impl Config {
    pub fn load() -> Self {
        let path = config_path();
        match fs::read_to_string(&path) {
            Ok(contents) => toml::from_str(&contents).unwrap_or_default(),
            Err(_) => Config::default(),
        }
    }
}

fn config_path() -> PathBuf {
    dirs::home_dir()
        .expect("could not determine home directory")
        .join(".rasa/config.toml")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_empty() {
        let cfg: Config = toml::from_str("").unwrap();
        assert!(cfg.skip.is_empty());
        assert!(cfg.min_size.is_none());
    }

    #[test]
    fn parse_full() {
        let cfg: Config = toml::from_str(
            r#"
            min_size = "200MB"
            skip = ["docker", "downloads"]
            exclude = ["/tmp/skip-me"]
            max_depth = 4
            no_global = true
            "#,
        )
        .unwrap();
        assert_eq!(cfg.min_size.as_deref(), Some("200MB"));
        assert_eq!(cfg.skip, vec!["docker", "downloads"]);
        assert_eq!(cfg.exclude, vec!["/tmp/skip-me"]);
        assert_eq!(cfg.max_depth, Some(4));
        assert_eq!(cfg.no_global, Some(true));
    }

    #[test]
    fn unknown_fields_ignored() {
        let cfg: Config = toml::from_str("foo = 42\n").unwrap();
        assert!(cfg.skip.is_empty());
    }
}
