reinhardt-rest 0.1.2

REST API framework aggregator for Reinhardt
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
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
//! # Reinhardt Versioning
//!
//! API versioning strategies for Reinhardt framework.
//!
//! ## Features
//!
//! - **AcceptHeaderVersioning**: Version from Accept header (e.g., `Accept: application/json; version=1.0`)
//! - **URLPathVersioning**: Version from URL path (e.g., `/v1/users/`)
//! - **NamespaceVersioning**: Version from URL namespace
//! - **HostNameVersioning**: Version from subdomain (e.g., `v1.api.example.com`)
//! - **QueryParameterVersioning**: Version from query parameter (e.g., `?version=1.0`)
//! - **VersioningMiddleware**: Automatic version detection middleware
//!
//! ## Example
//!
//! ```rust
//! use reinhardt_rest::versioning::{BaseVersioning, AcceptHeaderVersioning, QueryParameterVersioning};
//! use reinhardt_rest::versioning::{VersioningMiddleware, RequestVersionExt};
//!
//! // Accept header versioning
//! let accept_versioning = AcceptHeaderVersioning::new()
//!     .with_default_version("1.0")
//!     .with_allowed_versions(vec!["1.0", "2.0"]);
//!
//! // Query parameter versioning
//! let query_versioning = QueryParameterVersioning::new()
//!     .with_version_param("v")
//!     .with_default_version("1.0");
//!
//! // Middleware for automatic version detection
//! let middleware = VersioningMiddleware::new(accept_versioning);
//! ```

pub mod config;
pub mod handler;
pub mod middleware;
pub mod reverse;
pub mod settings;

use async_trait::async_trait;
pub use config::{VersioningConfig, VersioningManager, VersioningStrategy};
pub use handler::{
	ConfigurableVersionedHandler, SimpleVersionedHandler, VersionResponseBuilder, VersionedHandler,
	VersionedHandlerBuilder, VersionedHandlerWrapper,
};
pub use middleware::{ApiVersion, RequestVersionExt, VersioningMiddleware};
use regex::Regex;
use reinhardt_core::exception::{Error, Result};
use reinhardt_http::Request;
pub use reverse::{
	ApiDocFormat, ApiDocUrlBuilder, UrlReverseManager, VersionedUrlBuilder,
	VersioningStrategy as ReverseVersioningStrategy,
};
pub use settings::VersioningSettings;
use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;
use thiserror::Error as ThisError;

/// Errors that can occur during API version determination.
#[derive(Debug, ThisError)]
pub enum VersioningError {
	/// The Accept header does not contain a valid version.
	#[error("Invalid version in Accept header")]
	InvalidAcceptHeader,

	/// The URL path does not contain a valid version segment.
	#[error("Invalid version in URL path")]
	InvalidURLPath,

	/// The URL namespace does not contain a valid version.
	#[error("Invalid version in URL namespace")]
	InvalidNamespace,

	/// The hostname does not contain a valid version subdomain.
	#[error("Invalid version in hostname")]
	InvalidHostname,

	/// The query parameter does not contain a valid version.
	#[error("Invalid version in query parameter")]
	InvalidQueryParameter,

	/// The requested version is not in the allowed versions list.
	#[error("Version not allowed: {0}")]
	VersionNotAllowed(String),
}

/// Base trait for API versioning strategies
#[async_trait]
pub trait BaseVersioning: Send + Sync {
	/// Determine the API version from the request
	async fn determine_version(&self, request: &Request) -> Result<String>;

	/// Get the default version
	fn default_version(&self) -> Option<&str>;

	/// Get allowed versions
	fn allowed_versions(&self) -> Option<&HashSet<String>>;

	/// Check if a version is allowed
	fn is_allowed_version(&self, version: &str) -> bool {
		if let Some(allowed) = self.allowed_versions() {
			if allowed.is_empty() {
				return true;
			}
			return allowed.contains(version) || (self.default_version() == Some(version));
		}
		true
	}

	/// Get the version parameter name
	fn version_param(&self) -> &str {
		"version"
	}
}

/// Accept header versioning
///
/// Example: `Accept: application/json; version=1.0`
#[derive(Debug, Clone)]
pub struct AcceptHeaderVersioning {
	/// The fallback version when no version is specified in the Accept header.
	pub default_version: Option<String>,
	/// The set of allowed API versions.
	pub allowed_versions: HashSet<String>,
	/// The parameter name to look for in the Accept header (default: `"version"`).
	pub version_param: String,
}

impl AcceptHeaderVersioning {
	/// Create a new AcceptHeaderVersioning instance
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::{AcceptHeaderVersioning, BaseVersioning};
	///
	/// let versioning = AcceptHeaderVersioning::new();
	/// assert_eq!(versioning.default_version.as_deref(), None);
	/// assert_eq!(versioning.version_param.as_str(), "version");
	/// ```
	pub fn new() -> Self {
		Self {
			default_version: None,
			allowed_versions: HashSet::new(),
			version_param: "version".to_string(),
		}
	}
	/// Set the default version to use when no version is specified
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::{AcceptHeaderVersioning, BaseVersioning};
	///
	/// let versioning = AcceptHeaderVersioning::new()
	///     .with_default_version("1.0");
	/// assert_eq!(versioning.default_version.as_deref(), Some("1.0"));
	/// ```
	pub fn with_default_version(mut self, version: impl Into<String>) -> Self {
		self.default_version = Some(version.into());
		self
	}
	/// Set the allowed versions
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::{AcceptHeaderVersioning, BaseVersioning};
	///
	/// let versioning = AcceptHeaderVersioning::new()
	///     .with_allowed_versions(vec!["1.0", "2.0", "3.0"]);
	/// assert!(versioning.is_allowed_version("1.0"));
	/// assert!(versioning.is_allowed_version("2.0"));
	/// assert!(!versioning.is_allowed_version("4.0"));
	/// ```
	pub fn with_allowed_versions(mut self, versions: Vec<impl Into<String>>) -> Self {
		self.allowed_versions = versions.into_iter().map(|v| v.into()).collect();
		self
	}
	/// Set the version parameter name to look for in the Accept header
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::{AcceptHeaderVersioning, BaseVersioning};
	///
	/// let versioning = AcceptHeaderVersioning::new()
	///     .with_version_param("api-version");
	/// assert_eq!(versioning.version_param.as_str(), "api-version");
	/// ```
	pub fn with_version_param(mut self, param: impl Into<String>) -> Self {
		self.version_param = param.into();
		self
	}
}

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

#[async_trait]
impl BaseVersioning for AcceptHeaderVersioning {
	async fn determine_version(&self, request: &Request) -> Result<String> {
		// Parse Accept header for version parameter
		if let Some(accept) = request.headers.get("accept") {
			let accept_str = accept
				.to_str()
				.map_err(|_| Error::Validation(VersioningError::InvalidAcceptHeader.to_string()))?;

			// Parse media type parameters
			if let Some(params_start) = accept_str.find(';') {
				let params = &accept_str[params_start + 1..];
				for param in params.split(';') {
					let param = param.trim();
					if let Some((key, value)) = param.split_once('=')
						&& key.trim() == self.version_param
					{
						let version = value.trim().trim_matches('"');
						if self.is_allowed_version(version) {
							return Ok(version.to_owned());
						} else {
							// Avoid intermediate String allocation from VersionNotAllowed(String).to_string()
							return Err(Error::Validation(format!(
								"Version not allowed: {version}"
							)));
						}
					}
				}
			}
		}

		// Return default version if no version in header.
		// Use as_deref().to_owned() instead of clone().unwrap_or_else(...) to skip
		// cloning the Option<String> wrapper. The final String allocation to satisfy
		// the Result<String> return type is unavoidable.
		Ok(self.default_version.as_deref().unwrap_or("1.0").to_owned())
	}

	fn default_version(&self) -> Option<&str> {
		self.default_version.as_deref()
	}

	fn allowed_versions(&self) -> Option<&HashSet<String>> {
		Some(&self.allowed_versions)
	}

	fn version_param(&self) -> &str {
		&self.version_param
	}
}

/// URL path versioning
///
/// Example: `/v1/users/` or `/api/v2/users/`
#[derive(Debug, Clone)]
pub struct URLPathVersioning {
	/// The fallback version when no version is found in the URL path.
	pub default_version: Option<String>,
	/// The set of allowed API versions.
	pub allowed_versions: HashSet<String>,
	/// The parameter name for version (default: `"version"`).
	pub version_param: String,
	/// The regex pattern used to extract the version from the URL path.
	pub path_regex: Regex,
}

impl URLPathVersioning {
	/// Create a new URLPathVersioning instance
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::{URLPathVersioning, BaseVersioning};
	///
	/// let versioning = URLPathVersioning::new();
	/// assert_eq!(versioning.default_version.as_deref(), None);
	/// ```
	pub fn new() -> Self {
		Self {
			default_version: None,
			allowed_versions: HashSet::new(),
			version_param: "version".to_string(),
			path_regex: Regex::new(r"/v(\d+\.?\d*)(?:/|$)").unwrap(),
		}
	}
	/// Set the default version to use when no version is found in the path
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::{URLPathVersioning, BaseVersioning};
	///
	/// let versioning = URLPathVersioning::new()
	///     .with_default_version("1.0");
	/// assert_eq!(versioning.default_version.as_deref(), Some("1.0"));
	/// ```
	pub fn with_default_version(mut self, version: impl Into<String>) -> Self {
		self.default_version = Some(version.into());
		self
	}
	/// Set the allowed versions
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::{URLPathVersioning, BaseVersioning};
	///
	/// let versioning = URLPathVersioning::new()
	///     .with_allowed_versions(vec!["1", "2", "3"]);
	/// assert!(versioning.is_allowed_version("1"));
	/// assert!(!versioning.is_allowed_version("99"));
	/// ```
	pub fn with_allowed_versions(mut self, versions: Vec<impl Into<String>>) -> Self {
		self.allowed_versions = versions.into_iter().map(|v| v.into()).collect();
		self
	}
	/// Set the version parameter name (for trait compatibility)
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::{URLPathVersioning, BaseVersioning};
	///
	/// let versioning = URLPathVersioning::new()
	///     .with_version_param("v");
	/// assert_eq!(versioning.version_param.as_str(), "v");
	/// ```
	pub fn with_version_param(mut self, param: impl Into<String>) -> Self {
		self.version_param = param.into();
		self
	}
	/// Set a custom regex pattern for extracting version from path
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::URLPathVersioning;
	/// use regex::Regex;
	///
	/// let custom_regex = Regex::new(r"/api/v(\d+)").unwrap();
	/// let versioning = URLPathVersioning::new()
	///     .with_path_regex(custom_regex);
	/// // The versioning will now match paths like /api/v1, /api/v2, etc.
	/// ```
	pub fn with_path_regex(mut self, regex: Regex) -> Self {
		self.path_regex = regex;
		self
	}

	/// Set a custom pattern for extracting version from path (for configuration compatibility)
	///
	/// This converts a pattern like "/v{version}/" into a regex pattern.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::URLPathVersioning;
	///
	/// let versioning = URLPathVersioning::new()
	///     .with_pattern("/v{version}/");
	/// // The versioning will now match paths like /v1/, /v2/, etc.
	/// ```
	pub fn with_pattern(mut self, pattern: &str) -> Self {
		// Convert pattern like "/v{version}/" to regex "/v?([^/]+)"
		let regex_pattern = pattern.replace("{version}", "([^/]+)");
		if let Ok(regex) = Regex::new(&regex_pattern) {
			self.path_regex = regex;
		}
		self
	}
}

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

#[async_trait]
impl BaseVersioning for URLPathVersioning {
	async fn determine_version(&self, request: &Request) -> Result<String> {
		let path = request.uri.path();

		// Try to extract version from path using regex
		if let Some(captures) = self.path_regex.captures(path)
			&& let Some(version_match) = captures.get(1)
		{
			let version = version_match.as_str();
			if self.is_allowed_version(version) {
				return Ok(version.to_owned());
			} else {
				// Avoid intermediate String allocation from VersionNotAllowed(String).to_string()
				return Err(Error::Validation(format!("Version not allowed: {version}")));
			}
		}

		// Return default version if no version in path.
		// Skip cloning the Option<String> wrapper; final String alloc is unavoidable.
		Ok(self.default_version.as_deref().unwrap_or("1.0").to_owned())
	}

	fn default_version(&self) -> Option<&str> {
		self.default_version.as_deref()
	}

	fn allowed_versions(&self) -> Option<&HashSet<String>> {
		Some(&self.allowed_versions)
	}

	fn version_param(&self) -> &str {
		&self.version_param
	}
}

/// Hostname versioning
///
/// Example: `v1.api.example.com` or `api-v2.example.com`
#[derive(Debug, Clone)]
pub struct HostNameVersioning {
	/// The fallback version when no version is found in the hostname.
	pub default_version: Option<String>,
	/// The set of allowed API versions.
	pub allowed_versions: HashSet<String>,
	/// The regex pattern used to extract the version from the hostname.
	pub hostname_regex: Regex,
	/// Maps specific hostnames to their API versions.
	/// Takes precedence over regex extraction.
	pub hostname_to_version: HashMap<String, String>,
}

impl HostNameVersioning {
	/// Create a new HostNameVersioning instance
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::HostNameVersioning;
	///
	/// let versioning = HostNameVersioning::new();
	/// assert_eq!(versioning.default_version.as_deref(), None);
	/// ```
	pub fn new() -> Self {
		Self {
			default_version: None,
			allowed_versions: HashSet::new(),
			hostname_regex: Regex::new(r"^([a-zA-Z0-9]+)\.").unwrap(),
			hostname_to_version: HashMap::new(),
		}
	}
	/// Set the default version to use when no version is found in hostname
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::HostNameVersioning;
	///
	/// let versioning = HostNameVersioning::new()
	///     .with_default_version("1.0");
	/// assert_eq!(versioning.default_version.as_deref(), Some("1.0"));
	/// ```
	pub fn with_default_version(mut self, version: impl Into<String>) -> Self {
		self.default_version = Some(version.into());
		self
	}
	/// Set the allowed versions
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::{HostNameVersioning, BaseVersioning};
	///
	/// let versioning = HostNameVersioning::new()
	///     .with_allowed_versions(vec!["v1", "v2", "v3"]);
	/// assert!(versioning.is_allowed_version("v1"));
	/// assert!(!versioning.is_allowed_version("v99"));
	/// ```
	pub fn with_allowed_versions(mut self, versions: Vec<impl Into<String>>) -> Self {
		self.allowed_versions = versions.into_iter().map(|v| v.into()).collect();
		self
	}
	/// Set a custom regex pattern for extracting version from hostname
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::HostNameVersioning;
	/// use regex::Regex;
	///
	/// let custom_regex = Regex::new(r"^v(\d+)-api\.").unwrap();
	/// let versioning = HostNameVersioning::new()
	///     .with_hostname_regex(custom_regex);
	/// // The versioning will now match hostnames like v1-api.example.com
	/// ```
	pub fn with_hostname_regex(mut self, regex: Regex) -> Self {
		self.hostname_regex = regex;
		self
	}

	/// Set a host format pattern (for configuration compatibility)
	///
	/// This converts a host format like "{version}.api.example.com" into a regex pattern.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::HostNameVersioning;
	///
	/// let versioning = HostNameVersioning::new()
	///     .with_host_format("{version}.api.example.com");
	/// // The versioning will match hostnames like v1.api.example.com
	/// ```
	pub fn with_host_format(mut self, format: &str) -> Self {
		// Convert format like "{version}.api.example.com" to regex "^([^.]+)\.api\.example\.com"
		// Escape dots first, then replace placeholder to prevent regex corruption
		const PLACEHOLDER: &str = "__REINHARDT_VERSION_PLACEHOLDER__";
		let pattern = format.replace("{version}", PLACEHOLDER);
		let pattern = pattern.replace(".", "\\.");
		let pattern = pattern.replace(PLACEHOLDER, "([^.]+)");
		let pattern = format!("^{}", pattern);
		if let Ok(regex) = Regex::new(&pattern) {
			self.hostname_regex = regex;
		}
		self
	}

	/// Set hostname patterns for version mapping (for configuration compatibility)
	///
	/// This allows mapping specific hostnames to their API versions.
	/// The hostname mapping takes precedence over regex extraction when determining version.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::HostNameVersioning;
	///
	/// let versioning = HostNameVersioning::new()
	///     .with_hostname_pattern("v1", "v1.api.example.com")
	///     .with_hostname_pattern("v2", "v2.api.example.com");
	/// // Request to v1.api.example.com will resolve to version "v1"
	/// // Request to v2.api.example.com will resolve to version "v2"
	/// ```
	pub fn with_hostname_pattern(mut self, version: &str, hostname: &str) -> Self {
		self.allowed_versions.insert(version.to_string());
		self.hostname_to_version
			.insert(hostname.to_string(), version.to_string());
		self
	}
}

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

#[async_trait]
impl BaseVersioning for HostNameVersioning {
	async fn determine_version(&self, request: &Request) -> Result<String> {
		// Extract hostname from request
		if let Some(host) = request.headers.get("host") {
			let host_str = host
				.to_str()
				.map_err(|_| Error::Validation(VersioningError::InvalidHostname.to_string()))?;

			// Remove port if present
			let hostname = host_str.split(':').next().unwrap_or(host_str);

			// Priority 1: Check explicit hostname→version mapping
			if let Some(version) = self.hostname_to_version.get(hostname)
				&& self.is_allowed_version(version)
			{
				return Ok(version.clone());
			}

			// Priority 2: Try to extract version from hostname using regex
			if let Some(captures) = self.hostname_regex.captures(hostname)
				&& let Some(version_match) = captures.get(1)
			{
				let version = version_match.as_str();
				if self.is_allowed_version(version) {
					return Ok(version.to_string());
				}
			}
		}

		// Return default version if no version in hostname.
		// Skip cloning the Option<String> wrapper; final String alloc is unavoidable.
		Ok(self.default_version.as_deref().unwrap_or("1.0").to_owned())
	}

	fn default_version(&self) -> Option<&str> {
		self.default_version.as_deref()
	}

	fn allowed_versions(&self) -> Option<&HashSet<String>> {
		Some(&self.allowed_versions)
	}
}

/// Query parameter versioning
///
/// Example: `/users/?version=1.0` or `/users/?v=2.0`
#[derive(Debug, Clone)]
pub struct QueryParameterVersioning {
	/// The fallback version when no version query parameter is present.
	pub default_version: Option<String>,
	/// The set of allowed API versions.
	pub allowed_versions: HashSet<String>,
	/// The query parameter name for the version (default: `"version"`).
	pub version_param: String,
}

impl QueryParameterVersioning {
	/// Create a new QueryParameterVersioning instance
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::QueryParameterVersioning;
	///
	/// let versioning = QueryParameterVersioning::new();
	/// assert_eq!(versioning.default_version.as_deref(), None);
	/// assert_eq!(versioning.version_param.as_str(), "version");
	/// ```
	pub fn new() -> Self {
		Self {
			default_version: None,
			allowed_versions: HashSet::new(),
			version_param: "version".to_string(),
		}
	}
	/// Set the default version to use when no version is in query parameters
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::QueryParameterVersioning;
	///
	/// let versioning = QueryParameterVersioning::new()
	///     .with_default_version("1.0");
	/// assert_eq!(versioning.default_version.as_deref(), Some("1.0"));
	/// ```
	pub fn with_default_version(mut self, version: impl Into<String>) -> Self {
		self.default_version = Some(version.into());
		self
	}
	/// Set the allowed versions
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::{QueryParameterVersioning, BaseVersioning};
	///
	/// let versioning = QueryParameterVersioning::new()
	///     .with_allowed_versions(vec!["1.0", "2.0", "3.0"]);
	/// assert!(versioning.is_allowed_version("1.0"));
	/// assert!(!versioning.is_allowed_version("4.0"));
	/// ```
	pub fn with_allowed_versions(mut self, versions: Vec<impl Into<String>>) -> Self {
		self.allowed_versions = versions.into_iter().map(|v| v.into()).collect();
		self
	}
	/// Set the query parameter name to use for version detection
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::QueryParameterVersioning;
	///
	/// let versioning = QueryParameterVersioning::new()
	///     .with_version_param("v");
	/// assert_eq!(versioning.version_param.as_str(), "v");
	/// // This will now look for ?v=1.0 instead of ?version=1.0
	/// ```
	pub fn with_version_param(mut self, param: impl Into<String>) -> Self {
		self.version_param = param.into();
		self
	}
}

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

#[async_trait]
impl BaseVersioning for QueryParameterVersioning {
	async fn determine_version(&self, request: &Request) -> Result<String> {
		// Parse query string for version parameter
		if let Some(query) = request.uri.query() {
			for param in query.split('&') {
				if let Some((key, value)) = param.split_once('=')
					&& key == self.version_param
				{
					if self.is_allowed_version(value) {
						return Ok(value.to_owned());
					} else {
						// Avoid intermediate String allocation from VersionNotAllowed(String).to_string()
						return Err(Error::Validation(format!("Version not allowed: {value}")));
					}
				}
			}
		}

		// Return default version if no version in query.
		// Skip cloning the Option<String> wrapper; final String alloc is unavoidable.
		Ok(self.default_version.as_deref().unwrap_or("1.0").to_owned())
	}

	fn default_version(&self) -> Option<&str> {
		self.default_version.as_deref()
	}

	fn allowed_versions(&self) -> Option<&HashSet<String>> {
		Some(&self.allowed_versions)
	}

	fn version_param(&self) -> &str {
		&self.version_param
	}
}

/// Namespace versioning (URL namespace-based)
///
/// Extracts version from URL namespace patterns (e.g., /v1/, /v2/)
/// Now fully implemented with router namespace support
#[derive(Debug)]
pub struct NamespaceVersioning {
	/// The fallback version when no version is found in the namespace.
	pub default_version: Option<String>,
	/// The set of allowed API versions.
	pub allowed_versions: HashSet<String>,
	/// Pattern for extracting version from namespace (e.g., "/v{version}/")
	pub pattern: String,
	/// Namespace prefix (e.g., "api")
	pub namespace_prefix: Option<String>,
	/// Cached compiled regex for version extraction
	compiled_regex: OnceLock<Option<Regex>>,
}

impl Clone for NamespaceVersioning {
	fn clone(&self) -> Self {
		Self {
			default_version: self.default_version.clone(),
			allowed_versions: self.allowed_versions.clone(),
			pattern: self.pattern.clone(),
			namespace_prefix: self.namespace_prefix.clone(),
			// Reset compiled_regex so it will be recompiled on first use
			compiled_regex: OnceLock::new(),
		}
	}
}

impl NamespaceVersioning {
	/// Create a new NamespaceVersioning instance
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::NamespaceVersioning;
	///
	/// let versioning = NamespaceVersioning::new();
	/// assert_eq!(versioning.default_version.as_deref(), None);
	/// assert_eq!(versioning.pattern, "/v{version}/");
	/// ```
	pub fn new() -> Self {
		Self {
			default_version: None,
			allowed_versions: HashSet::new(),
			pattern: "/v{version}/".to_string(),
			namespace_prefix: None,
			compiled_regex: OnceLock::new(),
		}
	}
	/// Set the default version to use when no version is found in namespace
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::NamespaceVersioning;
	///
	/// let versioning = NamespaceVersioning::new()
	///     .with_default_version("1.0");
	/// assert_eq!(versioning.default_version.as_deref(), Some("1.0"));
	/// ```
	pub fn with_default_version(mut self, version: impl Into<String>) -> Self {
		self.default_version = Some(version.into());
		self
	}
	/// Set the allowed versions
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::{NamespaceVersioning, BaseVersioning};
	///
	/// let versioning = NamespaceVersioning::new()
	///     .with_allowed_versions(vec!["1", "1.0", "2", "2.0"]);
	/// assert!(versioning.is_allowed_version("1"));
	/// assert!(versioning.is_allowed_version("2.0"));
	/// assert!(!versioning.is_allowed_version("99"));
	/// ```
	pub fn with_allowed_versions(mut self, versions: Vec<impl Into<String>>) -> Self {
		self.allowed_versions = versions.into_iter().map(|v| v.into()).collect();
		self
	}

	/// Set the namespace prefix (e.g., "api")
	///
	/// This prefix is used when constructing full namespace patterns for version detection.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::NamespaceVersioning;
	///
	/// let versioning = NamespaceVersioning::new()
	///     .with_namespace_prefix("api");
	/// assert_eq!(versioning.namespace_prefix, Some("api".to_string()));
	/// ```
	pub fn with_namespace_prefix(mut self, prefix: &str) -> Self {
		self.namespace_prefix = Some(prefix.to_string());
		self
	}

	/// Set a custom pattern for extracting version from namespace
	///
	/// This converts a pattern like "/v{version}/" into a regex pattern for matching
	/// namespaces like /v1/, /v2/, etc.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::NamespaceVersioning;
	///
	/// let versioning = NamespaceVersioning::new()
	///     .with_pattern("/api/v{version}/");
	/// assert_eq!(versioning.pattern, "/api/v{version}/");
	/// ```
	pub fn with_pattern(mut self, pattern: &str) -> Self {
		self.pattern = pattern.to_string();
		// Reset cached regex since the pattern changed
		self.compiled_regex = OnceLock::new();
		self
	}
}

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

#[async_trait]
impl BaseVersioning for NamespaceVersioning {
	async fn determine_version(&self, request: &Request) -> Result<String> {
		let path = request.uri.path();

		// Use the configured pattern to extract version
		if let Some(version) = self.extract_version_from_path(path)
			&& self.is_allowed_version(&version)
		{
			return Ok(version);
		}

		// Fallback to default version.
		// Skip cloning the Option<String> wrapper; final String alloc is unavoidable.
		Ok(self.default_version.as_deref().unwrap_or("1.0").to_owned())
	}

	fn default_version(&self) -> Option<&str> {
		self.default_version.as_deref()
	}

	fn allowed_versions(&self) -> Option<&HashSet<String>> {
		Some(&self.allowed_versions)
	}
}

impl NamespaceVersioning {
	/// Get or compile the regex for version extraction from the configured pattern
	fn get_compiled_regex(&self) -> Option<&Regex> {
		self.compiled_regex
			.get_or_init(|| {
				let regex_pattern = self
					.pattern
					.replace("{version}", r"([^/]+)")
					.replace("/", r"\/");
				let full_pattern = format!("^{}", regex_pattern);
				regex::Regex::new(&full_pattern).ok()
			})
			.as_ref()
	}

	/// Extract version from a path using the configured pattern
	fn extract_version_from_path(&self, path: &str) -> Option<String> {
		if let Some(regex) = self.get_compiled_regex()
			&& let Some(captures) = regex.captures(path)
			&& let Some(version_match) = captures.get(1)
		{
			return Some(version_match.as_str().to_string());
		}
		None
	}

	/// Check if a version is allowed
	fn is_allowed_version(&self, version: &str) -> bool {
		self.allowed_versions.is_empty() || self.allowed_versions.contains(version)
	}

	/// Extract a version from a router-aware path, applying the
	/// configured pattern.
	///
	/// Unlike `extract_version_from_path` (private helper), this method is
	/// router-aware: it returns `Some(version)` only if `path` matches
	/// (starts with) at least one `path_prefix` registered on the
	/// router AND the configured pattern successfully extracts a
	/// version from that prefix. Otherwise it returns `None`. This
	/// prevents reporting a version for paths that no route on
	/// `router` actually serves.
	///
	/// The trait bound on [`reinhardt_router::VersionedRouter`] is what
	/// finally lets this method live in `reinhardt-rest` without
	/// pulling in `reinhardt-urls` (issue #4321).
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::NamespaceVersioning;
	/// use reinhardt_router::{RouteVersionInfo, VersionedRouter};
	///
	/// struct FakeRouter;
	/// impl VersionedRouter for FakeRouter {
	///     fn route_version_infos(&self) -> Vec<RouteVersionInfo> {
	///         vec![RouteVersionInfo::new(Some("v1".into()), "/v1/")]
	///     }
	/// }
	///
	/// let versioning = NamespaceVersioning::new()
	///     .with_pattern("/v{version}/")
	///     .with_allowed_versions(vec!["1", "2"]);
	///
	/// let router = FakeRouter;
	/// // "/v1/users/" matches the "/v1/" prefix registered on the router.
	/// let version = versioning.extract_version_from_router(&router, "/v1/users/");
	/// assert_eq!(version, Some("1".to_string()));
	///
	/// // "/v9/users/" does NOT match any registered prefix → None.
	/// let unknown = versioning.extract_version_from_router(&router, "/v9/users/");
	/// assert_eq!(unknown, None);
	/// ```
	pub fn extract_version_from_router<R: reinhardt_router::VersionedRouter + ?Sized>(
		&self,
		router: &R,
		path: &str,
	) -> Option<String> {
		// Find the first registered route whose `path_prefix` matches
		// the incoming `path`, then extract the version from that
		// prefix. If no route matches, the path is not served by this
		// router and we return None.
		router
			.route_version_infos()
			.into_iter()
			.find(|info| path.starts_with(&info.path_prefix))
			.and_then(|info| self.extract_version_from_path(&info.path_prefix))
	}

	/// Enumerate the versions currently registered on `router`.
	///
	/// The router exposes its routes through
	/// [`reinhardt_router::VersionedRouter`]; this method then applies
	/// the configured pattern to each route's `path_prefix` and filters
	/// by `allowed_versions` (when configured).
	///
	/// # Ordering
	///
	/// The returned `Vec<String>` is sorted **ascending in
	/// lexicographic (string) order** and deduplicated. Lexicographic
	/// order coincides with numeric order for single-digit versions
	/// (e.g. `"1" < "2"`) but diverges for multi-digit versions
	/// (e.g. `"10"` sorts before `"2"`). Callers that need a different
	/// ordering must re-sort the result themselves.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_rest::versioning::NamespaceVersioning;
	/// use reinhardt_router::{RouteVersionInfo, VersionedRouter};
	///
	/// struct FakeRouter;
	/// impl VersionedRouter for FakeRouter {
	///     fn route_version_infos(&self) -> Vec<RouteVersionInfo> {
	///         vec![
	///             RouteVersionInfo::new(Some("v1".into()), "/v1/users/"),
	///             RouteVersionInfo::new(Some("v2".into()), "/v2/users/"),
	///         ]
	///     }
	/// }
	///
	/// let versioning = NamespaceVersioning::new().with_pattern("/v{version}/");
	/// let router = FakeRouter;
	///
	/// let versions = versioning.get_available_versions_from_router(&router);
	/// assert!(versions.contains(&"1".to_string()));
	/// assert!(versions.contains(&"2".to_string()));
	/// ```
	pub fn get_available_versions_from_router<R: reinhardt_router::VersionedRouter + ?Sized>(
		&self,
		router: &R,
	) -> Vec<String> {
		let mut versions: Vec<String> = router
			.route_version_infos()
			.into_iter()
			.filter_map(|info| self.extract_version_from_path(&info.path_prefix))
			.filter(|version| self.is_allowed_version(version))
			.collect();
		versions.sort();
		versions.dedup();
		versions
	}
}

#[cfg(test)]
pub mod test_utils {
	use bytes::Bytes;
	use hyper::header::HeaderName;
	use hyper::{HeaderMap, Method, Uri, Version};
	use reinhardt_http::Request;

	pub fn create_test_request(uri: &str, headers: Vec<(String, String)>) -> Request {
		let uri = uri.parse::<Uri>().unwrap();
		let mut header_map = HeaderMap::new();
		for (key, value) in headers {
			let header_name: HeaderName = key.parse().unwrap();
			header_map.insert(header_name, value.parse().unwrap());
		}

		Request::builder()
			.method(Method::GET)
			.uri(uri)
			.version(Version::HTTP_11)
			.headers(header_map)
			.body(Bytes::new())
			.build()
			.unwrap()
	}
}

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

	#[tokio::test]
	async fn test_accept_header_versioning() {
		let versioning = AcceptHeaderVersioning::new()
			.with_default_version("1.0")
			.with_allowed_versions(vec!["1.0", "2.0"]);

		// Test with version in Accept header
		let request = create_test_request(
			"/users/",
			vec![(
				"accept".to_string(),
				"application/json; version=2.0".to_string(),
			)],
		);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "2.0");

		// Test without version (should return default)
		let request = create_test_request(
			"/users/",
			vec![("accept".to_string(), "application/json".to_string())],
		);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "1.0");
	}

	#[tokio::test]
	async fn test_url_path_versioning() {
		let versioning = URLPathVersioning::new()
			.with_default_version("1.0")
			.with_allowed_versions(vec!["1.0", "2.0", "2"]);

		// Test with version in path
		let request = create_test_request("/v2/users/", vec![]);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "2");

		// Test without version (should return default)
		let request = create_test_request("/users/", vec![]);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "1.0");
	}

	#[tokio::test]
	async fn test_hostname_versioning() {
		let versioning = HostNameVersioning::new()
			.with_default_version("1.0")
			.with_allowed_versions(vec!["v1", "v2"]);

		// Test with version in hostname
		let request = create_test_request(
			"/users/",
			vec![("host".to_string(), "v2.api.example.com".to_string())],
		);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "v2");

		// Test without version (should return default)
		let request = create_test_request(
			"/users/",
			vec![("host".to_string(), "api.example.com".to_string())],
		);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "1.0");
	}

	#[tokio::test]
	async fn test_query_parameter_versioning() {
		let versioning = QueryParameterVersioning::new()
			.with_default_version("1.0")
			.with_allowed_versions(vec!["1.0", "2.0"]);

		// Test with version in query parameter
		let request = create_test_request("/users/?version=2.0", vec![]);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "2.0");

		// Test without version (should return default)
		let request = create_test_request("/users/", vec![]);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "1.0");
	}

	#[tokio::test]
	async fn test_namespace_versioning() {
		let versioning = NamespaceVersioning::new()
			.with_default_version("1.0")
			.with_allowed_versions(vec!["1", "1.0", "2", "2.0", "3.0"]);

		// Test with version in namespace (v1 format)
		let request = create_test_request("/v1/users/", vec![]);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "1");

		// Test with version in namespace (v2.0 format)
		let request = create_test_request("/v2.0/users/", vec![]);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "2.0");

		// Test without version (should return default)
		let request = create_test_request("/users/", vec![]);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "1.0");

		// Test with non-version namespace
		let request = create_test_request("/api/users/", vec![]);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "1.0");
	}

	#[tokio::test]
	async fn test_namespace_versioning_with_custom_pattern() {
		let versioning = NamespaceVersioning::new()
			.with_default_version("1.0")
			.with_pattern("/api/v{version}/")
			.with_allowed_versions(vec!["1", "2"]);

		// Test with custom pattern
		let request = create_test_request("/api/v1/users/", vec![]);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "1");

		// Test with different version
		let request = create_test_request("/api/v2/users/", vec![]);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "2");

		// Test with old pattern (should not match)
		let request = create_test_request("/v1/users/", vec![]);
		let version = versioning.determine_version(&request).await.unwrap();
		assert_eq!(version, "1.0"); // Falls back to default
	}

	#[tokio::test]
	async fn test_hostname_versioning_with_host_format_dots_not_corrupted() {
		// Arrange - format with dots that would be corrupted by the old implementation
		let versioning = HostNameVersioning::new()
			.with_host_format("{version}.api.v2.example.com")
			.with_allowed_versions(vec!["v1", "v3"]);

		// Act
		let request = create_test_request(
			"/users/",
			vec![("host".to_string(), "v1.api.v2.example.com".to_string())],
		);
		let version = versioning.determine_version(&request).await.unwrap();

		// Assert
		assert_eq!(version, "v1");

		// Act - different version
		let request = create_test_request(
			"/users/",
			vec![("host".to_string(), "v3.api.v2.example.com".to_string())],
		);
		let version = versioning.determine_version(&request).await.unwrap();

		// Assert
		assert_eq!(version, "v3");
	}

	// Note: Router integration test removed to avoid circular dependency with reinhardt-urls.
	// Router integration tests should be placed in /tests/integration crate.
}