settings_loader 1.0.0

Opinionated configuration settings load mechanism for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
//! Comprehensive test suite for LayerBuilder explicit configuration layering API.
//!
//! Tests validate:
//! - Layer precedence (later layers override earlier)
//! - All layer types (Path, EnvVar, EnvSearch, Secrets, EnvVars)
//! - Format support (YAML, JSON, TOML)
//! - Backward compatibility with implicit layering
//! - Error handling and edge cases

use serde::{Deserialize, Serialize};
use serial_test::serial;
use settings_loader::LayerBuilder;
use std::fs;

// Mock types for testing
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
struct TestConfig {
    #[serde(default)]
    app_name: String,
    #[serde(default)]
    port: u16,
    #[serde(default)]
    debug: bool,
    #[serde(default)]
    db: TestDatabaseSettings,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
struct TestDatabaseSettings {
    host: String,
    user: Option<String>,
    password: String,
}

/// Test 1: LayerBuilder creation and basic structure
#[test]
fn test_layer_builder_new() {
    // Should create empty builder
    let builder = LayerBuilder::new();
    assert!(builder.is_empty());
}

/// Test 2: with_path adds a Path layer
#[test]
fn test_layer_builder_with_path() {
    let builder = LayerBuilder::new().with_path("/path/to/config.yaml");

    assert_eq!(builder.layer_count(), 1);
    assert!(builder.has_path_layer());
}

/// Test 3: with_env_var adds an EnvVar layer
#[test]
fn test_layer_builder_with_env_var() {
    let builder = LayerBuilder::new().with_env_var("APP_CONFIG_PATH");

    assert_eq!(builder.layer_count(), 1);
    assert!(builder.has_env_var_layer("APP_CONFIG_PATH"));
}

/// Test 4: with_secrets adds a Secrets layer
#[test]
fn test_layer_builder_with_secrets() {
    let builder = LayerBuilder::new().with_secrets("/path/to/secrets.yaml");

    assert_eq!(builder.layer_count(), 1);
    assert!(builder.has_secrets_layer());
}

/// Test 5: with_env_vars adds an EnvVars layer
#[test]
fn test_layer_builder_with_env_vars() {
    let builder = LayerBuilder::new().with_env_vars("APP", "__");

    assert_eq!(builder.layer_count(), 1);
    assert!(builder.has_env_vars_layer("APP", "__"));
}

/// Test 6: Multiple layers compose in order
#[test]
fn test_layer_builder_multiple_layers() {
    let builder = LayerBuilder::new()
        .with_path("/path/to/base.yaml")
        .with_path("/path/to/override.yaml")
        .with_env_vars("APP", "__");

    assert_eq!(builder.layer_count(), 3);
    // Verify order is maintained
    let layers = builder.layers();
    assert!(layers[0].is_path());
    assert!(layers[1].is_path());
    assert!(layers[2].is_env_vars());
}

/// Test 7: Layer precedence - later layers override earlier ones
#[test]
fn test_layer_precedence_yaml_override() {
    let temp_dir = tempfile::tempdir().unwrap();

    // Base config: port=8000, debug=false
    let base_path = temp_dir.path().join("base.yaml");
    fs::write(
        &base_path,
        "app_name: MyApp\nport: 8000\ndebug: false\ndb:\n  host: localhost\n  password: base_pass",
    )
    .unwrap();

    // Override config: port=9000, debug=true
    let override_path = temp_dir.path().join("override.yaml");
    fs::write(&override_path, "port: 9000\ndebug: true").unwrap();

    let builder = LayerBuilder::new().with_path(&base_path).with_path(&override_path);

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    // Later layer should override earlier
    assert_eq!(result.port, 9000);
    assert!(result.debug);
    // Earlier layer values preserved for non-overridden fields
    assert_eq!(result.app_name, "MyApp");
    assert_eq!(result.db.host, "localhost");
}

/// Test 8: Path layer fails gracefully if file not found
#[test]
fn test_path_layer_missing_file() {
    let builder = LayerBuilder::new().with_path("/nonexistent/path/config.yaml");

    let result = builder.build();
    assert!(result.is_err());
    // Error should indicate file not found or similar
}

/// Test 9: EnvVar layer skipped if env var not set
#[test]
#[serial]
fn test_env_var_layer_missing_env() {
    // Ensure env var is not set
    std::env::remove_var("NONEXISTENT_CONFIG_PATH");

    let builder = LayerBuilder::new().with_env_var("NONEXISTENT_CONFIG_PATH");

    // Should succeed but layer is skipped (empty)
    let result = builder.build();
    assert!(result.is_ok());
}

/// Test 10: EnvVar layer loads config if env var is set
#[test]
#[serial]
fn test_env_var_layer_with_set_env() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join("config.yaml");
    fs::write(
        &config_path,
        "app_name: EnvVarApp\nport: 3000\ndebug: true\ndb:\n  host: host.local\n  password: env_pass",
    )
    .unwrap();

    std::env::set_var("TEST_CONFIG_PATH", config_path.to_string_lossy().to_string());

    let builder = LayerBuilder::new().with_env_var("TEST_CONFIG_PATH");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.app_name, "EnvVarApp");
    assert_eq!(result.port, 3000);

    std::env::remove_var("TEST_CONFIG_PATH");
}

/// Test 11: Secrets layer loads and overrides
#[test]
fn test_secrets_layer_override() {
    let temp_dir = tempfile::tempdir().unwrap();

    let base_path = temp_dir.path().join("base.yaml");
    fs::write(
        &base_path,
        "app_name: SecretApp\nport: 5000\ndebug: false\ndb:\n  host: localhost\n  password: base_secret",
    )
    .unwrap();

    let secrets_path = temp_dir.path().join("secrets.yaml");
    fs::write(&secrets_path, "db:\n  password: actual_secret_password").unwrap();

    let builder = LayerBuilder::new().with_path(&base_path).with_secrets(&secrets_path);

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    // Secrets should override base
    assert_eq!(result.db.password, "actual_secret_password");
    // Other values preserved
    assert_eq!(result.app_name, "SecretApp");
}

/// Test 12: EnvVars layer integrates with system environment variables
#[test]
#[serial]
fn test_env_vars_layer_integration() {
    let temp_dir = tempfile::tempdir().unwrap();
    let base_path = temp_dir.path().join("base.yaml");
    fs::write(
        &base_path,
        "app_name: EnvVarsApp\nport: 7000\ndebug: false\ndb:\n  host: localhost\n  password: pass",
    )
    .unwrap();

    // Use "_" as separator - MYAPP_PORT maps to port, MYAPP_DB_HOST maps to db.host
    std::env::set_var("MYAPP_DB_HOST", "prod.host.com");
    std::env::set_var("MYAPP_PORT", "8888");

    let builder = LayerBuilder::new().with_path(&base_path).with_env_vars("MYAPP", "_");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.port, 8888);
    assert_eq!(result.db.host, "prod.host.com");
    assert_eq!(result.app_name, "EnvVarsApp");
    std::env::remove_var("MYAPP_PORT");
    std::env::remove_var("MYAPP_DB_HOST");
}

/// Test 13: Multiple file format support (YAML, JSON, TOML)
#[test]
fn test_multiple_file_formats_yaml() {
    let temp_dir = tempfile::tempdir().unwrap();
    let path = temp_dir.path().join("config.yaml");
    fs::write(
        &path,
        "app_name: YamlApp\nport: 6000\ndebug: false\ndb:\n  host: db.yaml\n  password: pass_yaml",
    )
    .unwrap();

    let builder = LayerBuilder::new().with_path(&path);
    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.app_name, "YamlApp");
    assert_eq!(result.db.host, "db.yaml");
}

/// Test 14: JSON file format support
#[test]
fn test_multiple_file_formats_json() {
    let temp_dir = tempfile::tempdir().unwrap();
    let path = temp_dir.path().join("config.json");
    fs::write(
        &path,
        r#"{"app_name":"JsonApp","port":7001,"debug":false,"db":{"host":"db.json","password":"pass_json"}}"#,
    )
    .unwrap();

    let builder = LayerBuilder::new().with_path(&path);
    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.app_name, "JsonApp");
    assert_eq!(result.db.host, "db.json");
}

/// Test 15: TOML file format support
#[test]
fn test_multiple_file_formats_toml() {
    let temp_dir = tempfile::tempdir().unwrap();
    let path = temp_dir.path().join("config.toml");
    fs::write(
        &path,
        r#"app_name = "TomlApp"
port = 7002
debug = false
[db]
host = "db.toml"
password = "pass_toml"
"#,
    )
    .unwrap();

    let builder = LayerBuilder::new().with_path(&path);
    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.app_name, "TomlApp");
    assert_eq!(result.db.host, "db.toml");
}

/// Test 16: Complex multi-layer scenario (Turtle use case)
#[test]
#[serial]
fn test_turtle_scenario() {
    let temp_dir = tempfile::tempdir().unwrap();

    // User scope config
    let user_path = temp_dir.path().join("user.yaml");
    fs::write(
        &user_path,
        "app_name: Turtle\nport: 7800\ndebug: false\ndb:\n  host: user.host\n  password: user_pass",
    )
    .unwrap();

    // Project scope config (overrides user)
    let project_path = temp_dir.path().join("project.yaml");
    fs::write(&project_path, "port: 7801\ndb:\n  host: project.host").unwrap();

    // Secrets (overrides project)
    let secrets_path = temp_dir.path().join("secrets.yaml");
    fs::write(&secrets_path, "db:\n  password: actual_secret").unwrap();

    // Build layers: user → project → secrets → env vars
    let builder = LayerBuilder::new()
        .with_path(&user_path)
        .with_path(&project_path)
        .with_secrets(&secrets_path)
        .with_env_vars("TURTLE", "_");

    // Simulate env var override
    std::env::set_var("TURTLE_PORT", "7999");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    // Verify precedence chain: env > secrets > project > user
    assert_eq!(result.port, 7999); // From env var (highest priority)
    assert_eq!(result.db.password, "actual_secret"); // From secrets
    assert_eq!(result.db.host, "project.host"); // From project
    assert_eq!(result.app_name, "Turtle"); // From user (lowest priority)

    // Cleanup
    std::env::remove_var("TURTLE_PORT");
}

/// Test 17: Empty config from builder (no layers)
#[test]
fn test_empty_builder() {
    let builder = LayerBuilder::new();
    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();

    // Should create empty config without error
    assert!(config.get_string("app_name").is_err());
}

/// Test 18: Builder pattern fluent interface
#[test]
fn test_fluent_interface() {
    let _builder = LayerBuilder::new()
        .with_path("a.yaml")
        .with_path("b.yaml")
        .with_env_vars("APP", "__");

    // Compilation success proves fluent API works
    // Compilation success proves fluent API works
}

/// Test 19: Layer query methods
#[test]
fn test_layer_query_methods() {
    let builder = LayerBuilder::new()
        .with_path("config.yaml")
        .with_env_var("CONFIG_VAR")
        .with_secrets("secrets.yaml")
        .with_env_vars("APP", "_");

    assert_eq!(builder.layer_count(), 4);
    assert!(!builder.is_empty());

    let layers = builder.layers();
    assert_eq!(layers.len(), 4);
}

/// Test 20: Path layer with various extensions
#[test]
fn test_path_layer_extension_detection() {
    let temp_dir = tempfile::tempdir().unwrap();

    // Test .yml (alternate YAML extension)
    let yml_path = temp_dir.path().join("config.yml");
    fs::write(
        &yml_path,
        "app_name: YmlApp\nport: 5555\ndebug: false\ndb:\n  host: localhost\n  password: yml_pass",
    )
    .unwrap();

    let builder = LayerBuilder::new().with_path(&yml_path);
    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.app_name, "YmlApp");
}

/// Test 21: Secrets path layer failure if file not found
#[test]
fn test_secrets_layer_missing_file() {
    let builder = LayerBuilder::new().with_secrets("/nonexistent/secrets.yaml");

    let result = builder.build();
    assert!(result.is_err());
}

/// Test 22: Mixed present and absent optional layers
#[test]
#[serial]
fn test_mixed_optional_layers() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join("config.yaml");
    fs::write(
        &config_path,
        "app_name: MixedApp\nport: 6666\ndebug: true\ndb:\n  host: mixed.host\n  password: mixed_pass",
    )
    .unwrap();

    // EnvVar layer missing, but should not fail build
    std::env::remove_var("MISSING_CONFIG");

    let builder = LayerBuilder::new()
        .with_path(&config_path)
        .with_env_var("MISSING_CONFIG")  // This layer skipped gracefully
        .with_env_vars("MIXED", "_");

    let result = builder.build();
    assert!(result.is_ok());
}

/// Test 23: Clone and debug traits
#[test]
fn test_layer_builder_traits() {
    let builder1 = LayerBuilder::new().with_path("config.yaml").with_env_vars("APP", "_");

    // Debug should work
    let debug_str = format!("{:?}", builder1);
    assert!(!debug_str.is_empty());

    // Note: If cloning is supported, test clone() here
}

/// Test 24: Builder method chaining order independence
#[test]
fn test_builder_order_matters() {
    let temp_dir = tempfile::tempdir().unwrap();

    let base_path = temp_dir.path().join("base.yaml");
    fs::write(
        &base_path,
        "port: 1000\napp_name: Base\ndebug: false\ndb:\n  host: base\n  password: base",
    )
    .unwrap();

    let override_path = temp_dir.path().join("override.yaml");
    fs::write(&override_path, "port: 2000").unwrap();

    // Order 1: base then override
    let builder1 = LayerBuilder::new().with_path(&base_path).with_path(&override_path);

    let config1 = builder1.build().unwrap().build().unwrap();
    let result1: TestConfig = config1.try_deserialize().unwrap();
    assert_eq!(result1.port, 2000); // Override wins

    // Order 2: override then base (should be different)
    let builder2 = LayerBuilder::new().with_path(&override_path).with_path(&base_path);

    let config2 = builder2.build().unwrap().build().unwrap();
    let result2: TestConfig = config2.try_deserialize().unwrap();
    assert_eq!(result2.port, 1000); // Base wins now
}

/// Test 25: Real-world scenario with all layer types
#[test]
#[serial]
fn test_comprehensive_real_world_scenario() {
    let temp_dir = tempfile::tempdir().unwrap();

    // Base application config
    let app_config = temp_dir.path().join("application.yaml");
    fs::write(
        &app_config,
        "app_name: RealWorldApp\nport: 8000\ndebug: false\ndb:\n  host: localhost\n  password: default",
    )
    .unwrap();

    // Environment-specific config
    let prod_config = temp_dir.path().join("production.yaml");
    fs::write(&prod_config, "debug: false\ndb:\n  host: prod.db.com").unwrap();

    // Secrets file
    let secrets = temp_dir.path().join("secrets.yaml");
    fs::write(&secrets, "db:\n  password: prod_secret_password_123").unwrap();

    // Set env var for additional config
    let runtime_config = temp_dir.path().join("runtime.yaml");
    fs::write(&runtime_config, "app_name: RuntimeOverride").unwrap();
    std::env::set_var("RUNTIME_CONFIG", runtime_config.to_string_lossy().to_string());

    // Build comprehensive layer stack
    let builder = LayerBuilder::new()
        .with_path(&app_config)         // Level 1: Base config
        .with_path(&prod_config)        // Level 2: Environment-specific
        .with_env_var("RUNTIME_CONFIG")  // Level 3: Optional runtime config
        .with_secrets(&secrets)          // Level 4: Secrets
        .with_env_vars("APP", "_"); // Level 5: System environment variables

    // Add system env overrides
    std::env::set_var("APP_PORT", "9000");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    // Verify complete precedence chain
    assert_eq!(result.port, 9000); // From system env var (highest)
    assert_eq!(result.db.password, "prod_secret_password_123"); // From secrets
    assert_eq!(result.db.host, "prod.db.com"); // From production.yaml
    assert_eq!(result.app_name, "RuntimeOverride"); // From runtime config
    assert!(!result.debug); // From production.yaml

    // Cleanup
    std::env::remove_var("RUNTIME_CONFIG");
    std::env::remove_var("APP_PORT");
}

/// Debug test to understand config crate Environment behavior
#[test]
#[serial]
fn test_debug_env_vars_behavior() {
    use std::fs;

    let temp_dir = tempfile::tempdir().unwrap();
    let config_path = temp_dir.path().join("config.yaml");
    fs::write(
        &config_path,
        "db_host: localhost\nport: 7000\ndb:\n  user: default_user",
    )
    .unwrap();

    std::env::set_var("MYAPP_DB_HOST", "prod.host.com");
    std::env::set_var("MYAPP_PORT", "8888");
    std::env::set_var("MYAPP_DB_USER", "admin");
    std::env::set_var("MYAPP_DB__USER", "admin_nested");

    // Test what config crate does with these env vars - separator "_"
    let config = config::Config::builder()
        .add_source(config::File::from(config_path.as_path()))
        .add_source(
            config::Environment::default()
                .prefix("MYAPP")
                .separator("_")
                .try_parsing(true),
        )
        .build()
        .unwrap();

    println!("\n=== With separator '_' ===");
    println!("db_host: {:?}", config.get_string("db_host"));
    println!("db.host: {:?}", config.get_string("db.host"));
    println!("port: {:?}", config.get_string("port"));
    println!("db.user: {:?}", config.get_string("db.user"));
    println!("db_user: {:?}", config.get_string("db_user"));

    std::env::remove_var("MYAPP_DB_HOST");
    std::env::remove_var("MYAPP_PORT");
    std::env::remove_var("MYAPP_DB_USER");
    std::env::remove_var("MYAPP_DB__USER");

    // Test with double underscore separator
    std::env::set_var("MYAPP_DB__HOST", "prod.host.com");
    std::env::set_var("MYAPP_PORT", "8888");

    let config2 = config::Config::builder()
        .add_source(config::File::from(config_path.as_path()))
        .add_source(
            config::Environment::default()
                .prefix("MYAPP")
                .separator("__")
                .try_parsing(true),
        )
        .build()
        .unwrap();

    println!("\n=== With separator '__' ===");
    println!("db.host: {:?}", config2.get_string("db.host"));
    println!("port: {:?}", config2.get_string("port"));

    std::env::remove_var("MYAPP_DB__HOST");
    std::env::remove_var("MYAPP_PORT");
}

/// Test 26: EnvVars layer works as the sole source.
#[test]
#[serial]
fn test_env_vars_only() {
    std::env::set_var("MYAPP_PORT", "8888");
    std::env::set_var("MYAPP_DB_HOST", "prod.host.com");
    std::env::set_var("MYAPP_DB_PASSWORD", "env_pass");

    let builder = LayerBuilder::new().with_env_vars("MYAPP", "_");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.port, 8888);
    assert_eq!(result.db.host, "prod.host.com");
    assert_eq!(result.db.password, "env_pass");
    // app_name is not set, so it will be the default for String, which is empty.
    assert_eq!(result.app_name, "");

    std::env::remove_var("MYAPP_PORT");
    std::env::remove_var("MYAPP_DB_HOST");
    std::env::remove_var("MYAPP_DB_PASSWORD");
}

/// Test 27: EnvSearch layer searches directories and finds environment-specific file
#[test]
fn test_layer_builder_with_env_search() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_dir = temp_dir.path().join("config");
    fs::create_dir_all(&config_dir).unwrap();

    // Create a production.yaml file in the config directory
    let prod_config = config_dir.join("production.yaml");
    fs::write(&prod_config, "port: 9999\napp_name: ProdApp").unwrap();

    let env = settings_loader::Environment::from("production");
    let builder = LayerBuilder::new().with_env_search(env, vec![config_dir.clone()]);

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.port, 9999);
    assert_eq!(result.app_name, "ProdApp");
}

/// Test 28: EnvSearch layer skips gracefully if no file found
#[test]
fn test_layer_builder_with_env_search_missing() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_dir = temp_dir.path().join("config");
    fs::create_dir_all(&config_dir).unwrap();

    let env = settings_loader::Environment::from("production");
    let builder = LayerBuilder::new().with_env_search(env, vec![config_dir]);

    // Should not error, just produce empty config
    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    assert!(config.get_string("app_name").is_err());
}

/// Test 29: with_path_in_dir discovers YAML file
#[test]
fn test_with_path_in_dir_discovers_yaml() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_dir = temp_dir.path().join("config");
    fs::create_dir_all(&config_dir).unwrap();

    // Create application.yaml in config directory
    let yaml_path = config_dir.join("application.yaml");
    fs::write(
        &yaml_path,
        "app_name: YamlDiscovered\nport: 5000\ndebug: true\ndb:\n  host: yaml.host\n  password: yaml_pass",
    )
    .unwrap();

    let builder = LayerBuilder::new().with_path_in_dir(&config_dir, "application");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.app_name, "YamlDiscovered");
    assert_eq!(result.port, 5000);
    assert_eq!(result.db.host, "yaml.host");
}

/// Test 30: with_path_in_dir discovers TOML file
#[test]
fn test_with_path_in_dir_discovers_toml() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_dir = temp_dir.path().join("config");
    fs::create_dir_all(&config_dir).unwrap();

    // Create application.toml in config directory
    let toml_path = config_dir.join("application.toml");
    fs::write(
        &toml_path,
        r#"app_name = "TomlDiscovered"
port = 6000
debug = false
[db]
host = "toml.host"
password = "toml_pass"
"#,
    )
    .unwrap();

    let builder = LayerBuilder::new().with_path_in_dir(&config_dir, "application");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.app_name, "TomlDiscovered");
    assert_eq!(result.port, 6000);
    assert_eq!(result.db.host, "toml.host");
}

/// Test 31: with_path_in_dir discovers JSON file
#[test]
fn test_with_path_in_dir_discovers_json() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_dir = temp_dir.path().join("config");
    fs::create_dir_all(&config_dir).unwrap();

    // Create application.json in config directory
    let json_path = config_dir.join("application.json");
    fs::write(
        &json_path,
        r#"{"app_name":"JsonDiscovered","port":7000,"debug":true,"db":{"host":"json.host","password":"json_pass"}}"#,
    )
    .unwrap();

    let builder = LayerBuilder::new().with_path_in_dir(&config_dir, "application");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.app_name, "JsonDiscovered");
    assert_eq!(result.port, 7000);
    assert_eq!(result.db.host, "json.host");
}

/// Test 32: with_path_in_dir prefers YAML over other formats when multiple exist
#[test]
fn test_with_path_in_dir_format_precedence() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_dir = temp_dir.path().join("config");
    fs::create_dir_all(&config_dir).unwrap();

    // Create multiple formats - YAML should be preferred
    fs::write(
        config_dir.join("application.yaml"),
        "app_name: FromYaml\nport: 1111\ndebug: false\ndb:\n  host: yaml\n  password: pass",
    )
    .unwrap();
    fs::write(
        config_dir.join("application.toml"),
        r#"app_name = "FromToml"
port = 2222
"#,
    )
    .unwrap();
    fs::write(
        config_dir.join("application.json"),
        r#"{"app_name":"FromJson","port":3333}"#,
    )
    .unwrap();

    let builder = LayerBuilder::new().with_path_in_dir(&config_dir, "application");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    // Should load YAML (first in precedence order)
    assert_eq!(result.app_name, "FromYaml");
    assert_eq!(result.port, 1111);
}

/// Test 33: with_path_in_dir fails if no matching file found
#[test]
fn test_with_path_in_dir_no_file_found() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_dir = temp_dir.path().join("config");
    fs::create_dir_all(&config_dir).unwrap();

    // No application.* files exist
    let builder = LayerBuilder::new().with_path_in_dir(&config_dir, "application");

    let result = builder.build();
    assert!(result.is_err());
}

/// Test 34: with_path_in_dir works with relative paths
#[test]
fn test_with_path_in_dir_relative_path() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_dir = temp_dir.path().join("config");
    fs::create_dir_all(&config_dir).unwrap();

    fs::write(
        config_dir.join("settings.yaml"),
        "app_name: RelativePath\nport: 4444\ndebug: false\ndb:\n  host: relative\n  password: pass",
    )
    .unwrap();

    // Change to temp dir to test relative path
    let original_dir = std::env::current_dir().unwrap();
    std::env::set_current_dir(&temp_dir).unwrap();

    let builder = LayerBuilder::new().with_path_in_dir("config", "settings");

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    assert_eq!(result.app_name, "RelativePath");
    assert_eq!(result.port, 4444);

    // Restore original directory
    std::env::set_current_dir(original_dir).unwrap();
}

/// Test 35: with_path_in_dir can be combined with other layers
#[test]
fn test_with_path_in_dir_with_other_layers() {
    let temp_dir = tempfile::tempdir().unwrap();
    let config_dir = temp_dir.path().join("config");
    fs::create_dir_all(&config_dir).unwrap();

    // Base config in directory
    fs::write(
        config_dir.join("base.yaml"),
        "app_name: BaseApp\nport: 5555\ndebug: false\ndb:\n  host: base.host\n  password: base_pass",
    )
    .unwrap();

    // Override config as explicit path
    let override_path = temp_dir.path().join("override.yaml");
    fs::write(&override_path, "port: 6666\ndebug: true").unwrap();

    let builder = LayerBuilder::new()
        .with_path_in_dir(&config_dir, "base")
        .with_path(&override_path);

    let config_builder = builder.build().unwrap();
    let config = config_builder.build().unwrap();
    let result: TestConfig = config.try_deserialize().unwrap();

    // Override should win for port and debug
    assert_eq!(result.port, 6666);
    assert!(result.debug);
    // Base values preserved
    assert_eq!(result.app_name, "BaseApp");
    assert_eq!(result.db.host, "base.host");
}