//! Desktop-side config helpers. The `Config` struct itself lives in
//! the sibling `config` module (TOML schema, platform-agnostic). This
//! module only provides the per-platform default path via the
//! `directories` crate, plus two convenience functions for load/save
//! against that default path.

use std::path::PathBuf;

use directories::ProjectDirs;
pub use crate::config::{Config, ConfigError};

const CONFIG_FILENAME: &str = "client.toml";

/// Default config path, following OS conventions:
///   Linux:   `~/.config/doctate/client.toml`
///   Windows: `%APPDATA%\doctate\client.toml`
///   macOS:   `~/Library/Application Support/doctate/client.toml`
pub fn default_config_path() -> Result<PathBuf, ConfigError> {
    ProjectDirs::from("", "", "doctate")
        .map(|dirs| dirs.config_dir().join(CONFIG_FILENAME))
        .ok_or(ConfigError::NoConfigDir)
}

/// Convenience: load from `default_config_path()`.
pub fn load() -> Result<Option<Config>, ConfigError> {
    Config::load_from(&default_config_path()?)
}

/// Convenience: save to `default_config_path()`.
pub fn save(cfg: &Config) -> Result<(), ConfigError> {
    cfg.save_to(&default_config_path()?)
}

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

    #[test]
    fn default_path_ends_with_client_toml() {
        // Sanity check on the ProjectDirs wiring — can't assert the
        // exact path (varies per host), but the filename is deterministic.
        let path = default_config_path().expect("config path available in test env");
        assert_eq!(
            path.file_name().and_then(|s| s.to_str()),
            Some("client.toml")
        );
    }
}
