reinhardt-apps 0.3.7

Application registry and management for Reinhardt framework
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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
//! Application builder module
//!
//! Provides a builder pattern for configuring and constructing Reinhardt applications.
//! Inspired by Django's application configuration system.

use crate::apps::{AppConfig, AppError, Apps};
use std::collections::HashMap;
use std::sync::Arc;
use thiserror::Error;

/// Errors that can occur when building an application
#[derive(Debug, Error)]
pub enum BuildError {
	/// An error originating from the application registry.
	#[error("Application error: {0}")]
	App(#[from] AppError),

	/// The provided configuration value is invalid.
	#[error("Invalid configuration: {0}")]
	InvalidConfig(String),

	/// A required configuration value was not provided.
	#[error("Missing required configuration: {0}")]
	MissingConfig(String),

	/// An error in route configuration.
	#[error("Route configuration error: {0}")]
	RouteError(String),

	/// An error in database configuration.
	#[error("Database configuration error: {0}")]
	DatabaseError(String),
}

/// A specialized `Result` type for application build operations.
pub type BuildResult<T> = Result<T, BuildError>;

/// Route definition for the application
/// Lightweight wrapper around path patterns
#[derive(Clone)]
pub struct RouteConfig {
	/// URL path pattern for this route.
	pub path: String,
	/// Name of the handler associated with this route.
	pub handler_name: String,
	/// Optional name for reverse URL lookup.
	pub name: Option<String>,
	/// Optional namespace for grouping routes.
	pub namespace: Option<String>,
}

impl RouteConfig {
	/// Create a new route configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::RouteConfig;
	///
	/// let route = RouteConfig::new("/users/", "UserListHandler");
	/// assert_eq!(route.path, "/users/");
	/// assert_eq!(route.handler_name, "UserListHandler");
	/// ```
	pub fn new(path: impl Into<String>, handler_name: impl Into<String>) -> Self {
		Self {
			path: path.into(),
			handler_name: handler_name.into(),
			name: None,
			namespace: None,
		}
	}

	/// Set the route name
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::RouteConfig;
	///
	/// let route = RouteConfig::new("/users/", "UserListHandler")
	///     .with_name("user-list");
	/// assert_eq!(route.name, Some("user-list".to_string()));
	/// ```
	pub fn with_name(mut self, name: impl Into<String>) -> Self {
		self.name = Some(name.into());
		self
	}

	/// Set the route namespace
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::RouteConfig;
	///
	/// let route = RouteConfig::new("/users/", "UserListHandler")
	///     .with_namespace("api");
	/// assert_eq!(route.namespace, Some("api".to_string()));
	/// ```
	pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
		self.namespace = Some(namespace.into());
		self
	}

	/// Get the full name including namespace
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::RouteConfig;
	///
	/// let route = RouteConfig::new("/users/", "UserListHandler")
	///     .with_namespace("api")
	///     .with_name("list");
	/// assert_eq!(route.full_name(), Some("api:list".to_string()));
	///
	/// let route = RouteConfig::new("/users/", "UserListHandler")
	///     .with_name("list");
	/// assert_eq!(route.full_name(), Some("list".to_string()));
	///
	/// let route = RouteConfig::new("/users/", "UserListHandler");
	/// assert_eq!(route.full_name(), None);
	/// ```
	pub fn full_name(&self) -> Option<String> {
		match (&self.namespace, &self.name) {
			(Some(ns), Some(name)) => Some(format!("{}:{}", ns, name)),
			(None, Some(name)) => Some(name.clone()),
			_ => None,
		}
	}
}

/// Database configuration for the application
#[derive(Clone, Debug)]
pub struct ApplicationDatabaseConfig {
	/// Database connection URL.
	pub url: String,
	/// Maximum number of connections in the pool.
	pub pool_size: Option<u32>,
	/// Maximum number of connections that can exceed `pool_size`.
	pub max_overflow: Option<u32>,
	/// Connection timeout in seconds.
	pub timeout: Option<u64>,
}

impl ApplicationDatabaseConfig {
	/// Create a new database configuration.
	///
	/// The URL is stored as-is at this stage; scheme validation is performed
	/// later by [`ApplicationBuilder::build`] so that
	/// [`ApplicationDatabaseConfig`] remains a plain data carrier. Build-time
	/// validation rejects unrecognized schemes (see issue
	/// [#485](https://github.com/kent8192/reinhardt-web/issues/485)) before any
	/// connection attempt is made.
	///
	/// A future major release may move this validation into the constructor
	/// itself; see issue
	/// [#4056](https://github.com/kent8192/reinhardt-web/issues/4056) for the
	/// breaking-change proposal.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationDatabaseConfig;
	///
	/// let db_config = ApplicationDatabaseConfig::new("postgresql://localhost/mydb");
	/// assert_eq!(db_config.url, "postgresql://localhost/mydb");
	/// ```
	pub fn new(url: impl Into<String>) -> Self {
		Self {
			url: url.into(),
			pool_size: None,
			max_overflow: None,
			timeout: None,
		}
	}

	/// Set the connection pool size
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationDatabaseConfig;
	///
	/// let db_config = ApplicationDatabaseConfig::new("postgresql://localhost/mydb")
	///     .with_pool_size(10);
	/// assert_eq!(db_config.pool_size, Some(10));
	/// ```
	pub fn with_pool_size(mut self, size: u32) -> Self {
		self.pool_size = Some(size);
		self
	}

	/// Set the maximum overflow connections
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationDatabaseConfig;
	///
	/// let db_config = ApplicationDatabaseConfig::new("postgresql://localhost/mydb")
	///     .with_max_overflow(5);
	/// assert_eq!(db_config.max_overflow, Some(5));
	/// ```
	pub fn with_max_overflow(mut self, overflow: u32) -> Self {
		self.max_overflow = Some(overflow);
		self
	}

	/// Set the connection timeout
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationDatabaseConfig;
	///
	/// let db_config = ApplicationDatabaseConfig::new("postgresql://localhost/mydb")
	///     .with_timeout(30);
	/// assert_eq!(db_config.timeout, Some(30));
	/// ```
	pub fn with_timeout(mut self, timeout: u64) -> Self {
		self.timeout = Some(timeout);
		self
	}
}

/// Builder for constructing Reinhardt applications
/// Inspired by Django's application configuration system
pub struct ApplicationBuilder {
	apps: Vec<AppConfig>,
	middleware: Vec<String>,
	url_patterns: Vec<RouteConfig>,
	database_config: Option<ApplicationDatabaseConfig>,
	settings: HashMap<String, String>,
}

impl ApplicationBuilder {
	/// Create a new application builder
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	///
	/// let builder = ApplicationBuilder::new();
	/// let app = builder.build().unwrap();
	/// assert_eq!(app.apps().len(), 0);
	/// ```
	pub fn new() -> Self {
		Self {
			apps: Vec::new(),
			middleware: Vec::new(),
			url_patterns: Vec::new(),
			database_config: None,
			settings: HashMap::new(),
		}
	}

	/// Add an application configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	/// use reinhardt_apps::AppConfig;
	///
	/// let app_config = AppConfig::new("myapp", "myapp");
	/// let builder = ApplicationBuilder::new()
	///     .add_app(app_config);
	/// let app = builder.build().unwrap();
	/// assert_eq!(app.apps().len(), 1);
	/// ```
	pub fn add_app(mut self, app: AppConfig) -> Self {
		self.apps.push(app);
		self
	}

	/// Add multiple application configurations
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	/// use reinhardt_apps::AppConfig;
	///
	/// let apps = vec![
	///     AppConfig::new("app1", "app1"),
	///     AppConfig::new("app2", "app2"),
	/// ];
	/// let builder = ApplicationBuilder::new()
	///     .add_apps(apps);
	/// let app = builder.build().unwrap();
	/// assert_eq!(app.apps().len(), 2);
	/// ```
	pub fn add_apps(mut self, apps: Vec<AppConfig>) -> Self {
		self.apps.extend(apps);
		self
	}

	/// Add a middleware
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	///
	/// let builder = ApplicationBuilder::new()
	///     .add_middleware("CorsMiddleware");
	/// let app = builder.build().unwrap();
	/// assert_eq!(app.middleware().len(), 1);
	/// ```
	pub fn add_middleware(mut self, middleware: impl Into<String>) -> Self {
		self.middleware.push(middleware.into());
		self
	}

	/// Add multiple middleware
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	///
	/// let middleware = vec!["CorsMiddleware", "AuthMiddleware"];
	/// let builder = ApplicationBuilder::new()
	///     .add_middlewares(middleware);
	/// let app = builder.build().unwrap();
	/// assert_eq!(app.middleware().len(), 2);
	/// ```
	pub fn add_middlewares<S: Into<String>>(mut self, middleware: Vec<S>) -> Self {
		self.middleware
			.extend(middleware.into_iter().map(|m| m.into()));
		self
	}

	/// Add a URL pattern
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::{ApplicationBuilder, RouteConfig};
	///
	/// let route = RouteConfig::new("/users/", "UserListHandler");
	/// let builder = ApplicationBuilder::new()
	///     .add_url_pattern(route);
	/// let app = builder.build().unwrap();
	/// assert_eq!(app.url_patterns().len(), 1);
	/// ```
	pub fn add_url_pattern(mut self, pattern: RouteConfig) -> Self {
		self.url_patterns.push(pattern);
		self
	}

	/// Add multiple URL patterns
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::{ApplicationBuilder, RouteConfig};
	///
	/// let patterns = vec![
	///     RouteConfig::new("/users/", "UserListHandler"),
	///     RouteConfig::new("/posts/", "PostListHandler"),
	/// ];
	/// let builder = ApplicationBuilder::new()
	///     .add_url_patterns(patterns);
	/// let app = builder.build().unwrap();
	/// assert_eq!(app.url_patterns().len(), 2);
	/// ```
	pub fn add_url_patterns(mut self, patterns: Vec<RouteConfig>) -> Self {
		self.url_patterns.extend(patterns);
		self
	}

	/// Set the database configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::{ApplicationBuilder, ApplicationDatabaseConfig};
	///
	/// let db_config = ApplicationDatabaseConfig::new("postgresql://localhost/mydb");
	/// let builder = ApplicationBuilder::new()
	///     .database(db_config);
	/// let app = builder.build().unwrap();
	/// assert!(app.database_config().is_some());
	/// ```
	pub fn database(mut self, config: ApplicationDatabaseConfig) -> Self {
		self.database_config = Some(config);
		self
	}

	/// Add a custom setting
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	///
	/// let builder = ApplicationBuilder::new()
	///     .add_setting("DEBUG", "true");
	/// let app = builder.build().unwrap();
	/// assert_eq!(app.settings().get("DEBUG"), Some(&"true".to_string()));
	/// ```
	pub fn add_setting(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
		self.settings.insert(key.into(), value.into());
		self
	}

	/// Add multiple custom settings
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	/// use std::collections::HashMap;
	///
	/// let mut settings = HashMap::new();
	/// settings.insert("DEBUG".to_string(), "true".to_string());
	/// settings.insert("SECRET_KEY".to_string(), "secret".to_string());
	///
	/// let builder = ApplicationBuilder::new()
	///     .add_settings(settings);
	/// let app = builder.build().unwrap();
	/// assert_eq!(app.settings().get("DEBUG"), Some(&"true".to_string()));
	/// ```
	pub fn add_settings(mut self, settings: HashMap<String, String>) -> Self {
		self.settings.extend(settings);
		self
	}

	/// Validate the configuration
	fn validate(&self) -> BuildResult<()> {
		// Validate all app configurations
		for app in &self.apps {
			app.validate_label()?;
		}

		// Check for duplicate app labels
		let mut labels = std::collections::HashSet::new();
		for app in &self.apps {
			if !labels.insert(&app.label) {
				return Err(BuildError::InvalidConfig(format!(
					"Duplicate app label: {}",
					app.label
				)));
			}
		}

		// Check for duplicate route names
		let mut route_names = std::collections::HashSet::new();
		for pattern in &self.url_patterns {
			if let Some(full_name) = pattern.full_name()
				&& !route_names.insert(full_name.clone())
			{
				return Err(BuildError::RouteError(format!(
					"Duplicate route name: {}",
					full_name
				)));
			}
		}

		// Validate the database URL scheme at build time so that obviously
		// malformed URLs surface as a clear configuration error rather than
		// later as an opaque connection failure (issue #485).
		if let Some(db_config) = &self.database_config {
			reinhardt_conf::settings::database_config::validate_database_url_scheme(&db_config.url)
				.map_err(BuildError::DatabaseError)?;
		}

		Ok(())
	}

	/// Build the application
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	/// use reinhardt_apps::AppConfig;
	///
	/// let app_config = AppConfig::new("myapp", "myapp");
	/// let builder = ApplicationBuilder::new()
	///     .add_app(app_config)
	///     .add_middleware("CorsMiddleware");
	///
	/// let app = builder.build().unwrap();
	/// assert_eq!(app.apps().len(), 1);
	/// assert_eq!(app.middleware().len(), 1);
	/// ```
	pub fn build(self) -> BuildResult<Application> {
		// Validate configuration
		self.validate()?;

		// Create the Apps registry
		let installed_apps: Vec<String> = self.apps.iter().map(|app| app.name.clone()).collect();
		let apps_registry = Apps::new(installed_apps);

		// Register all app configurations
		for app in &self.apps {
			apps_registry.register(app.clone())?;
		}

		// Populate the registry
		apps_registry.populate()?;

		Ok(Application {
			apps: self.apps,
			middleware: self.middleware,
			url_patterns: self.url_patterns,
			database_config: self.database_config,
			settings: self.settings,
			apps_registry: Arc::new(apps_registry),
		})
	}

	/// Build the application and register it with the DI system
	///
	/// This method builds the application and registers both the `Application`
	/// and `Apps` instances in the provided `SingletonScope`.
	///
	/// # Examples
	///
	/// ```no_run
	/// use reinhardt_apps::builder::ApplicationBuilder;
	/// use reinhardt_apps::AppConfig;
	/// use reinhardt_di::SingletonScope;
	/// use std::sync::Arc;
	///
	/// let singleton = Arc::new(SingletonScope::new());
	/// let app_config = AppConfig::new("myapp", "myapp");
	/// let app = ApplicationBuilder::new()
	///     .add_app(app_config)
	///     .build_with_di(singleton.clone())
	///     .unwrap();
	/// ```
	#[cfg(feature = "di")]
	pub fn build_with_di(
		self,
		singleton_scope: Arc<reinhardt_di::SingletonScope>,
	) -> BuildResult<Arc<Application>> {
		let app = self.build()?;
		let app = Arc::new(app);

		// Register Application in SingletonScope
		singleton_scope.set(app.clone());

		// Register Apps in SingletonScope
		singleton_scope.set(app.apps_registry.clone());

		Ok(app)
	}
}

impl Default for ApplicationBuilder {
	fn default() -> Self {
		Self::new()
	}
}

/// The built application
pub struct Application {
	apps: Vec<AppConfig>,
	middleware: Vec<String>,
	url_patterns: Vec<RouteConfig>,
	database_config: Option<ApplicationDatabaseConfig>,
	settings: HashMap<String, String>,
	apps_registry: Arc<Apps>,
}

impl Application {
	/// Get the registered applications
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	/// use reinhardt_apps::AppConfig;
	///
	/// let app_config = AppConfig::new("myapp", "myapp");
	/// let builder = ApplicationBuilder::new()
	///     .add_app(app_config);
	/// let app = builder.build().unwrap();
	///
	/// assert_eq!(app.apps().len(), 1);
	/// assert_eq!(app.apps()[0].label, "myapp");
	/// ```
	pub fn apps(&self) -> &[AppConfig] {
		&self.apps
	}

	/// Get the middleware stack
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	///
	/// let builder = ApplicationBuilder::new()
	///     .add_middleware("CorsMiddleware")
	///     .add_middleware("AuthMiddleware");
	/// let app = builder.build().unwrap();
	///
	/// assert_eq!(app.middleware().len(), 2);
	/// assert_eq!(app.middleware()[0], "CorsMiddleware");
	/// ```
	pub fn middleware(&self) -> &[String] {
		&self.middleware
	}

	/// Get the URL patterns
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::{ApplicationBuilder, RouteConfig};
	///
	/// let route = RouteConfig::new("/users/", "UserListHandler");
	/// let builder = ApplicationBuilder::new()
	///     .add_url_pattern(route);
	/// let app = builder.build().unwrap();
	///
	/// assert_eq!(app.url_patterns().len(), 1);
	/// assert_eq!(app.url_patterns()[0].path, "/users/");
	/// ```
	pub fn url_patterns(&self) -> &[RouteConfig] {
		&self.url_patterns
	}

	/// Get the database configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::{ApplicationBuilder, ApplicationDatabaseConfig};
	///
	/// let db_config = ApplicationDatabaseConfig::new("postgresql://localhost/mydb");
	/// let builder = ApplicationBuilder::new()
	///     .database(db_config);
	/// let app = builder.build().unwrap();
	///
	/// assert!(app.database_config().is_some());
	/// assert_eq!(app.database_config().unwrap().url, "postgresql://localhost/mydb");
	/// ```
	pub fn database_config(&self) -> Option<&ApplicationDatabaseConfig> {
		self.database_config.as_ref()
	}

	/// Get the custom settings
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	///
	/// let builder = ApplicationBuilder::new()
	///     .add_setting("DEBUG", "true");
	/// let app = builder.build().unwrap();
	///
	/// assert_eq!(app.settings().get("DEBUG"), Some(&"true".to_string()));
	/// ```
	pub fn settings(&self) -> &HashMap<String, String> {
		&self.settings
	}

	/// Get the apps registry
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_apps::builder::ApplicationBuilder;
	/// use reinhardt_apps::AppConfig;
	///
	/// let app_config = AppConfig::new("myapp", "myapp");
	/// let builder = ApplicationBuilder::new()
	///     .add_app(app_config);
	/// let app = builder.build().unwrap();
	///
	/// assert!(app.apps_registry().is_ready());
	/// assert!(app.apps_registry().is_installed("myapp"));
	/// ```
	pub fn apps_registry(&self) -> &Apps {
		&self.apps_registry
	}
}

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

	#[test]
	fn test_route_config_creation() {
		let route = RouteConfig::new("/users/", "UserListHandler")
			.with_name("user-list")
			.with_namespace("api");

		assert_eq!(route.path, "/users/");
		assert_eq!(route.handler_name, "UserListHandler");
		assert_eq!(route.name, Some("user-list".to_string()));
		assert_eq!(route.namespace, Some("api".to_string()));
	}

	#[test]
	fn test_route_config_full_name() {
		let route = RouteConfig::new("/users/", "UserListHandler")
			.with_namespace("api")
			.with_name("list");
		assert_eq!(route.full_name(), Some("api:list".to_string()));

		let route = RouteConfig::new("/users/", "UserListHandler").with_name("list");
		assert_eq!(route.full_name(), Some("list".to_string()));

		let route = RouteConfig::new("/users/", "UserListHandler");
		assert_eq!(route.full_name(), None);
	}

	#[test]
	fn test_database_config_creation() {
		let db_config = ApplicationDatabaseConfig::new("postgresql://localhost/mydb")
			.with_pool_size(10)
			.with_max_overflow(5)
			.with_timeout(30);

		assert_eq!(db_config.url, "postgresql://localhost/mydb");
		assert_eq!(db_config.pool_size, Some(10));
		assert_eq!(db_config.max_overflow, Some(5));
		assert_eq!(db_config.timeout, Some(30));
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_basic() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let app = ApplicationBuilder::new().build().unwrap();

		assert_eq!(app.apps().len(), 0);
		assert_eq!(app.middleware().len(), 0);
		assert_eq!(app.url_patterns().len(), 0);
		assert!(app.database_config().is_none());
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_with_apps() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let app_config = AppConfig::new("myapp", "myapp");
		let app = ApplicationBuilder::new()
			.add_app(app_config)
			.build()
			.unwrap();

		assert_eq!(app.apps().len(), 1);
		assert_eq!(app.apps()[0].label, "myapp");
		assert!(app.apps_registry().is_installed("myapp"));
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_with_multiple_apps() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let apps = vec![
			AppConfig::new("app1", "app1"),
			AppConfig::new("app2", "app2"),
		];
		let app = ApplicationBuilder::new().add_apps(apps).build().unwrap();

		assert_eq!(app.apps().len(), 2);
		assert!(app.apps_registry().is_installed("app1"));
		assert!(app.apps_registry().is_installed("app2"));
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_with_middleware() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let app = ApplicationBuilder::new()
			.add_middleware("CorsMiddleware")
			.add_middleware("AuthMiddleware")
			.build()
			.unwrap();

		assert_eq!(app.middleware().len(), 2);
		assert_eq!(app.middleware()[0], "CorsMiddleware");
		assert_eq!(app.middleware()[1], "AuthMiddleware");
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_with_middlewares() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let middleware = vec!["CorsMiddleware", "AuthMiddleware"];
		let app = ApplicationBuilder::new()
			.add_middlewares(middleware)
			.build()
			.unwrap();

		assert_eq!(app.middleware().len(), 2);
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_with_url_patterns() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let route = RouteConfig::new("/users/", "UserListHandler");
		let app = ApplicationBuilder::new()
			.add_url_pattern(route)
			.build()
			.unwrap();

		assert_eq!(app.url_patterns().len(), 1);
		assert_eq!(app.url_patterns()[0].path, "/users/");
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_with_database() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let db_config = ApplicationDatabaseConfig::new("postgresql://localhost/mydb");
		let app = ApplicationBuilder::new()
			.database(db_config)
			.build()
			.unwrap();

		assert!(app.database_config().is_some());
		assert_eq!(
			app.database_config().unwrap().url,
			"postgresql://localhost/mydb"
		);
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_with_settings() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let app = ApplicationBuilder::new()
			.add_setting("DEBUG", "true")
			.add_setting("SECRET_KEY", "secret")
			.build()
			.unwrap();

		assert_eq!(app.settings().get("DEBUG"), Some(&"true".to_string()));
		assert_eq!(
			app.settings().get("SECRET_KEY"),
			Some(&"secret".to_string())
		);
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_validation_duplicate_apps() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let result = ApplicationBuilder::new()
			.add_app(AppConfig::new("myapp", "myapp"))
			.add_app(AppConfig::new("another", "myapp"))
			.build();

		assert!(result.is_err());
		match result {
			Err(BuildError::InvalidConfig(msg)) => {
				assert_eq!(msg, "Duplicate app label: myapp");
			}
			_ => panic!("Expected InvalidConfig error"),
		}
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_validation_duplicate_routes() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let result = ApplicationBuilder::new()
			.add_url_pattern(RouteConfig::new("/users/", "Handler1").with_name("users"))
			.add_url_pattern(RouteConfig::new("/posts/", "Handler2").with_name("users"))
			.build();

		assert!(result.is_err());
		match result {
			Err(BuildError::RouteError(msg)) => {
				assert_eq!(msg, "Duplicate route name: users");
			}
			_ => panic!("Expected RouteError"),
		}
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_method_chaining() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let app = ApplicationBuilder::new()
			.add_app(AppConfig::new("app1", "app1"))
			.add_middleware("CorsMiddleware")
			.add_url_pattern(RouteConfig::new("/api/", "ApiHandler"))
			.database(ApplicationDatabaseConfig::new("postgresql://localhost/db"))
			.add_setting("DEBUG", "true")
			.build()
			.unwrap();

		assert_eq!(app.apps().len(), 1);
		assert_eq!(app.middleware().len(), 1);
		assert_eq!(app.url_patterns().len(), 1);
		assert!(app.database_config().is_some());
		assert_eq!(app.settings().get("DEBUG"), Some(&"true".to_string()));
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_apps_registry_ready() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let app = ApplicationBuilder::new()
			.add_app(AppConfig::new("myapp", "myapp"))
			.build()
			.unwrap();

		assert!(app.apps_registry().is_ready());
		assert!(app.apps_registry().is_apps_ready());
		assert!(app.apps_registry().is_models_ready());
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_invalid_app_label() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let result = ApplicationBuilder::new()
			.add_app(AppConfig::new("myapp", "my-app"))
			.build();

		assert!(result.is_err());
		match result {
			Err(BuildError::App(AppError::InvalidLabel(_))) => {}
			_ => panic!("Expected InvalidLabel error"),
		}
	}

	#[test]
	fn test_route_config_without_name() {
		let route = RouteConfig::new("/api/v1/users/", "UserHandler");
		assert_eq!(route.full_name(), None);
	}

	#[test]
	fn test_database_config_minimal() {
		let db_config = ApplicationDatabaseConfig::new("sqlite::memory:");
		assert_eq!(db_config.url, "sqlite::memory:");
		assert_eq!(db_config.pool_size, None);
		assert_eq!(db_config.max_overflow, None);
		assert_eq!(db_config.timeout, None);
	}

	// Issue #485: build-time validation of the database URL scheme. The
	// constructor stays infallible (data-carrier role); rejection happens
	// once, at build() time.

	#[rstest::rstest]
	#[case::postgres("postgres://localhost/db")]
	#[case::postgresql("postgresql://user:pass@localhost:5432/db")]
	#[case::sqlite_memory("sqlite::memory:")]
	#[case::sqlite_absolute("sqlite:///var/data/db.sqlite3")]
	#[case::sqlite_relative("sqlite:db.sqlite3")]
	#[case::mysql("mysql://root@localhost/db")]
	#[case::mariadb("mariadb://root@localhost/db")]
	#[serial(apps_registry)]
	fn test_application_builder_accepts_valid_database_url_scheme(#[case] url: &str) {
		// Arrange
		crate::registry::reset_global_registry();
		let db_config = ApplicationDatabaseConfig::new(url);

		// Act
		let result = ApplicationBuilder::new().database(db_config).build();

		// Assert
		assert!(
			result.is_ok(),
			"expected URL {:?} to be accepted but got {:?}",
			url,
			result.err()
		);
	}

	#[rstest::rstest]
	#[case::empty("")]
	#[case::not_a_url("not a url")]
	#[case::http("http://localhost/db")]
	#[case::ftp("ftp://localhost/db")]
	#[case::redis("redis://localhost")]
	#[case::missing_scheme("localhost/db")]
	fn test_application_builder_rejects_invalid_database_url_scheme(#[case] url: &str) {
		// Arrange
		let db_config = ApplicationDatabaseConfig::new(url);

		// Act
		// `Application` does not implement `Debug`, so we cannot use
		// `expect_err()` here (it would require `T: Debug`). Match instead.
		let result = ApplicationBuilder::new().database(db_config).build();

		// Assert
		match result {
			Err(BuildError::DatabaseError(msg)) => {
				assert!(
					msg.contains("Invalid database URL"),
					"unexpected error message for {:?}: {}",
					url,
					msg
				);
			}
			Err(other) => panic!("expected BuildError::DatabaseError, got {:?}", other),
			Ok(_) => panic!("expected build to fail for invalid URL: {:?}", url),
		}
	}

	#[test]
	#[serial(apps_registry)]
	fn test_application_builder_empty_settings() {
		// Arrange - Reset global state before test
		crate::registry::reset_global_registry();

		let app = ApplicationBuilder::new().build().unwrap();
		assert!(app.settings().is_empty());
	}
}