use std::io::Write;

use attune::Settings;

#[derive(Clone, Settings)]
struct EnvConfig {
    #[setting(env = "ATTUNE_DERIVE_PORT", default = 8080)]
    port: u16,

    #[setting(env = "ATTUNE_DERIVE_THEME", default = "system")]
    theme: String,
}

#[derive(Clone, Settings)]
#[settings(app = "derive_source_test", config_path = "settings.toml")]
struct TomlConfig {
    #[setting(env = "ATTUNE_DERIVE_TOML_PORT", default = 8080)]
    port: u16,

    #[setting(default = "system")]
    theme: String,
}

#[test]
fn env_values_override_defaults() {
    temp_env::with_vars(
        [
            ("ATTUNE_DERIVE_PORT", Some("9000")),
            ("ATTUNE_DERIVE_THEME", Some("dark")),
        ],
        || {
            let settings = EnvConfig::load().unwrap();

            assert_eq!(settings.port().get(), 9000);
            assert_eq!(settings.theme().get(), "dark");
        },
    );
}

#[test]
fn toml_values_override_defaults() {
    let mut file = tempfile::NamedTempFile::new().unwrap();
    writeln!(file, "port = 7000").unwrap();
    writeln!(file, "theme = 'dark'").unwrap();

    temp_env::with_vars(
        [
            (
                "DERIVE_SOURCE_TEST_CONFIG",
                Some(file.path().to_str().unwrap()),
            ),
            ("ATTUNE_DERIVE_TOML_PORT", None),
        ],
        || {
            let settings = TomlConfig::load().unwrap();

            assert_eq!(settings.port().get(), 7000);
            assert_eq!(settings.theme().get(), "dark");
        },
    );
}

#[test]
fn env_values_override_toml_values() {
    let mut file = tempfile::NamedTempFile::new().unwrap();
    writeln!(file, "port = 7000").unwrap();
    writeln!(file, "theme = 'dark'").unwrap();

    temp_env::with_vars(
        [
            (
                "DERIVE_SOURCE_TEST_CONFIG",
                Some(file.path().to_str().unwrap()),
            ),
            ("ATTUNE_DERIVE_TOML_PORT", Some("9000")),
        ],
        || {
            let settings = TomlConfig::load().unwrap();

            assert_eq!(settings.port().get(), 9000);
            assert_eq!(settings.theme().get(), "dark");
        },
    );
}
