use config::{Config, ConfigError, Environment, File, FileFormat};

pub fn load<'a, T: serde::de::Deserialize<'a>>(
    file_path: &str,
    format: FileFormat,
) -> Result<T, ConfigError> {
    let path = match std::env::var("CONFIG_PATH") {
        Ok(env_file_path) => env_file_path,
        Err(_) => String::from(file_path),
    };

    Config::builder()
        .add_source(File::from_str(&path, format))
        .add_source(Environment::default().separator("."))
        .build()?
        .try_deserialize()
}

#[test]
fn test_load_yaml() {
    use serde::Deserialize;

    #[derive(Debug, Deserialize)]
    struct Author {
        pub name: String,
        pub books: Vec<String>,
    }

    #[derive(Debug, Deserialize)]
    struct Test {
        pub count: u32,
        pub author: Author,
    }

    let expected_data: Test = Test {
        count: 10,
        author: Author {
            name: "John Ronald Reuel Tolkien".to_string(),
            books: vec!["The Lord of the Rings".to_string()],
        },
    };

    let data: Test = load(include_str!("./test_config.yaml"), FileFormat::Yaml).unwrap();
    assert_eq!(data.count, expected_data.count);
    assert_eq!(data.author.name, expected_data.author.name);
    assert_eq!(data.author.books, expected_data.author.books);
}
