reinhardt-db 0.1.1

Django-style database layer 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
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
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
/// Field validators similar to Django's validators
use once_cell::sync::Lazy;
use regex::Regex;
use reinhardt_core::exception::Result;
use reinhardt_core::validators::{
	self as validators_crate, OrmValidator, ValidationError as BaseValidationError,
	ValidationResult,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Validation error
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationError {
	/// The field.
	pub field: String,
	/// The message.
	pub message: String,
	/// The code.
	pub code: String,
}

impl ValidationError {
	/// Create a new validation error
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::ValidationError;
	///
	/// let error = ValidationError::new(
	///     "email",
	///     "Enter a valid email address",
	///     "invalid_email"
	/// );
	/// assert_eq!(error.field, "email");
	/// assert_eq!(error.code, "invalid_email");
	/// ```
	pub fn new(
		field: impl Into<String>,
		message: impl Into<String>,
		code: impl Into<String>,
	) -> Self {
		Self {
			field: field.into(),
			message: message.into(),
			code: code.into(),
		}
	}
}

impl std::fmt::Display for ValidationError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "{}: {} ({})", self.field, self.message, self.code)
	}
}

impl std::error::Error for ValidationError {}

/// Base trait for validators
///
/// This is the ORM-specific validator trait. For the base validator trait,
/// see `reinhardt_core::validators::Validator`.
pub trait Validator: Send + Sync {
	/// Validates the given value and returns an error if invalid.
	fn validate(&self, value: &str) -> Result<()>;
	/// Returns the error message for this validator.
	fn message(&self) -> String;
}

/// Required field validator
#[derive(Debug, Clone)]
pub struct RequiredValidator {
	/// The message.
	pub message: String,
}

impl RequiredValidator {
	/// Create a new required field validator
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{RequiredValidator, Validator};
	///
	/// let validator = RequiredValidator::new();
	/// assert!(validator.validate("some text").is_ok());
	/// assert!(validator.validate("").is_err());
	/// assert!(validator.validate("   ").is_err());
	/// ```
	pub fn new() -> Self {
		Self {
			message: "This field is required".to_string(),
		}
	}
	/// Create a required validator with custom error message
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{RequiredValidator, Validator};
	///
	/// let validator = RequiredValidator::with_message("Username is required");
	/// assert_eq!(validator.message(), "Username is required");
	/// ```
	pub fn with_message(message: impl Into<String>) -> Self {
		Self {
			message: message.into(),
		}
	}
}

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

impl Validator for RequiredValidator {
	fn validate(&self, value: &str) -> Result<()> {
		if value.trim().is_empty() {
			return Err(reinhardt_core::exception::Error::Validation(
				self.message.clone(),
			));
		}
		Ok(())
	}

	fn message(&self) -> String {
		self.message.clone()
	}
}

impl validators_crate::Validator<str> for RequiredValidator {
	fn validate(&self, value: &str) -> ValidationResult<()> {
		if value.trim().is_empty() {
			return Err(BaseValidationError::Custom(self.message.clone()));
		}
		Ok(())
	}
}

impl OrmValidator for RequiredValidator {
	fn message(&self) -> String {
		self.message.clone()
	}
}

/// Max length validator
#[derive(Debug, Clone)]
pub struct MaxLengthValidator {
	/// The max length.
	pub max_length: usize,
	/// The message.
	pub message: String,
}

impl MaxLengthValidator {
	/// Create a new max length validator
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{MaxLengthValidator, Validator};
	///
	/// let validator = MaxLengthValidator::new(10);
	/// assert!(validator.validate("hello").is_ok());
	/// assert!(validator.validate("hello world").is_err());
	/// ```
	pub fn new(max_length: usize) -> Self {
		Self {
			max_length,
			message: format!("Ensure this value has at most {} characters", max_length),
		}
	}
	/// Create a max length validator with custom error message
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{MaxLengthValidator, Validator};
	///
	/// let validator = MaxLengthValidator::with_message(20, "Name too long");
	/// assert_eq!(validator.message(), "Name too long");
	/// ```
	pub fn with_message(max_length: usize, message: impl Into<String>) -> Self {
		Self {
			max_length,
			message: message.into(),
		}
	}
}

impl Validator for MaxLengthValidator {
	fn validate(&self, value: &str) -> Result<()> {
		if value.len() > self.max_length {
			return Err(reinhardt_core::exception::Error::Validation(
				self.message.clone(),
			));
		}
		Ok(())
	}

	fn message(&self) -> String {
		self.message.clone()
	}
}

impl validators_crate::Validator<str> for MaxLengthValidator {
	fn validate(&self, value: &str) -> ValidationResult<()> {
		if value.len() > self.max_length {
			return Err(BaseValidationError::Custom(self.message.clone()));
		}
		Ok(())
	}
}

impl OrmValidator for MaxLengthValidator {
	fn message(&self) -> String {
		self.message.clone()
	}
}

/// Min length validator
#[derive(Debug, Clone)]
pub struct MinLengthValidator {
	/// The min length.
	pub min_length: usize,
	/// The message.
	pub message: String,
}

impl MinLengthValidator {
	/// Create a new min length validator
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{MinLengthValidator, Validator};
	///
	/// let validator = MinLengthValidator::new(3);
	/// assert!(validator.validate("hello").is_ok());
	/// assert!(validator.validate("hi").is_err());
	/// ```
	pub fn new(min_length: usize) -> Self {
		Self {
			min_length,
			message: format!("Ensure this value has at least {} characters", min_length),
		}
	}
	/// Create a min length validator with custom error message
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{MinLengthValidator, Validator};
	///
	/// let validator = MinLengthValidator::with_message(8, "Password too short");
	/// assert_eq!(validator.message(), "Password too short");
	/// ```
	pub fn with_message(min_length: usize, message: impl Into<String>) -> Self {
		Self {
			min_length,
			message: message.into(),
		}
	}
}

impl Validator for MinLengthValidator {
	fn validate(&self, value: &str) -> Result<()> {
		if value.len() < self.min_length {
			return Err(reinhardt_core::exception::Error::Validation(
				self.message.clone(),
			));
		}
		Ok(())
	}

	fn message(&self) -> String {
		self.message.clone()
	}
}

impl validators_crate::Validator<str> for MinLengthValidator {
	fn validate(&self, value: &str) -> ValidationResult<()> {
		if value.len() < self.min_length {
			return Err(BaseValidationError::Custom(self.message.clone()));
		}
		Ok(())
	}
}

impl OrmValidator for MinLengthValidator {
	fn message(&self) -> String {
		self.message.clone()
	}
}

/// Email validator
#[derive(Debug, Clone)]
pub struct EmailValidator {
	/// The message.
	pub message: String,
}

impl EmailValidator {
	/// Create a new RFC 5322 compliant email validator
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{EmailValidator, Validator};
	///
	/// let validator = EmailValidator::new();
	/// assert!(validator.validate("user@example.com").is_ok());
	/// assert!(validator.validate("user.name+tag@example.co.uk").is_ok());
	/// assert!(validator.validate("invalid-email").is_err());
	/// assert!(validator.validate("@example.com").is_err());
	/// ```
	pub fn new() -> Self {
		Self {
			message: "Enter a valid email address".to_string(),
		}
	}
	/// Create an email validator with custom error message
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{EmailValidator, Validator};
	///
	/// let validator = EmailValidator::with_message("Please provide a valid email");
	/// assert_eq!(validator.message(), "Please provide a valid email");
	/// ```
	pub fn with_message(message: impl Into<String>) -> Self {
		Self {
			message: message.into(),
		}
	}
}

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

impl Validator for EmailValidator {
	fn validate(&self, value: &str) -> Result<()> {
		// RFC 5322 compliant email validation
		// This implementation follows the addr-spec format from RFC 5322
		// See: https://datatracker.ietf.org/doc/html/rfc5322#section-3.4.1

		// Split email into local and domain parts
		let parts: Vec<&str> = value.rsplitn(2, '@').collect();
		if parts.len() != 2 {
			return Err(reinhardt_core::exception::Error::Validation(
				self.message.clone(),
			));
		}

		let domain = parts[0];
		let local = parts[1];

		// Validate local part (before @)
		if !Self::validate_local_part(local) {
			return Err(reinhardt_core::exception::Error::Validation(
				self.message.clone(),
			));
		}

		// Validate domain part (after @)
		if !Self::validate_domain_part(domain) {
			return Err(reinhardt_core::exception::Error::Validation(
				self.message.clone(),
			));
		}

		Ok(())
	}

	fn message(&self) -> String {
		self.message.clone()
	}
}

impl validators_crate::Validator<str> for EmailValidator {
	fn validate(&self, value: &str) -> ValidationResult<()> {
		let parts: Vec<&str> = value.rsplitn(2, '@').collect();
		if parts.len() != 2 {
			return Err(BaseValidationError::Custom(self.message.clone()));
		}

		let domain = parts[0];
		let local = parts[1];

		if !Self::validate_local_part(local) || !Self::validate_domain_part(domain) {
			return Err(BaseValidationError::Custom(self.message.clone()));
		}

		Ok(())
	}
}

impl OrmValidator for EmailValidator {
	fn message(&self) -> String {
		self.message.clone()
	}
}

impl EmailValidator {
	/// Validate the local part of an email (before @)
	/// RFC 5322: local-part = dot-atom / quoted-string / obs-local-part
	fn validate_local_part(local: &str) -> bool {
		if local.is_empty() || local.len() > 64 {
			return false;
		}

		// Check for quoted strings
		if local.starts_with('"') && local.ends_with('"') {
			return Self::validate_quoted_string(local);
		}

		// Validate dot-atom format
		Self::validate_dot_atom(local)
	}

	/// Validate quoted string format
	fn validate_quoted_string(s: &str) -> bool {
		if s.len() < 2 {
			return false;
		}

		let inner = &s[1..s.len() - 1];
		let mut escaped = false;

		for ch in inner.chars() {
			if escaped {
				// After backslash, any ASCII char is allowed
				if !ch.is_ascii() {
					return false;
				}
				escaped = false;
			} else if ch == '\\' {
				escaped = true;
			} else if ch == '"' {
				// Unescaped quote inside quoted string is invalid
				return false;
			} else if !Self::is_qtext(ch) {
				return false;
			}
		}

		// Must not end with an escape character
		!escaped
	}

	/// Check if character is valid qtext (RFC 5322)
	fn is_qtext(ch: char) -> bool {
		ch == ' ' || ch == '\t' || (('!'..='~').contains(&ch) && ch != '"' && ch != '\\')
	}

	/// Validate dot-atom format (RFC 5322)
	fn validate_dot_atom(s: &str) -> bool {
		if s.is_empty() || s.starts_with('.') || s.ends_with('.') {
			return false;
		}

		// Check for consecutive dots
		if s.contains("..") {
			return false;
		}

		// Each atom must be valid
		s.split('.').all(Self::validate_atom)
	}

	/// Validate atom characters (RFC 5322)
	fn validate_atom(atom: &str) -> bool {
		if atom.is_empty() {
			return false;
		}

		atom.chars().all(Self::is_atext)
	}

	/// Check if character is valid atext (RFC 5322)
	fn is_atext(ch: char) -> bool {
		ch.is_ascii_alphanumeric() || "!#$%&'*+-/=?^_`{|}~".contains(ch)
	}

	/// Validate domain part (after @)
	/// RFC 5322: domain = dot-atom / domain-literal / obs-domain
	fn validate_domain_part(domain: &str) -> bool {
		if domain.is_empty() || domain.len() > 255 {
			return false;
		}

		// Check for domain literal [IPv4 or IPv6]
		if domain.starts_with('[') && domain.ends_with(']') {
			return Self::validate_domain_literal(domain);
		}

		// Validate dot-atom domain format
		Self::validate_domain_name(domain)
	}

	/// Validate domain literal (IP address in brackets)
	fn validate_domain_literal(domain: &str) -> bool {
		if domain.len() < 3 {
			return false;
		}

		let inner = &domain[1..domain.len() - 1];

		// Check for IPv6 prefix
		if inner.to_lowercase().starts_with("ipv6:") {
			// Basic IPv6 validation - can be enhanced
			return inner.len() > 5 && inner[5..].contains(':');
		}

		// IPv4 validation
		Self::validate_ipv4(inner)
	}

	/// Basic IPv4 validation
	fn validate_ipv4(s: &str) -> bool {
		let parts: Vec<&str> = s.split('.').collect();
		if parts.len() != 4 {
			return false;
		}

		parts.iter().all(|part| part.parse::<u8>().is_ok())
	}

	/// Validate domain name (dot-separated labels)
	fn validate_domain_name(domain: &str) -> bool {
		if domain.starts_with('.') || domain.ends_with('.') || domain.contains("..") {
			return false;
		}

		let labels: Vec<&str> = domain.split('.').collect();

		// Must have at least 2 labels (e.g., example.com)
		if labels.len() < 2 {
			return false;
		}

		// Each label must be valid
		labels
			.iter()
			.all(|label| Self::validate_domain_label(label))
	}

	/// Validate a single domain label
	fn validate_domain_label(label: &str) -> bool {
		if label.is_empty() || label.len() > 63 {
			return false;
		}

		// Label cannot start or end with hyphen
		if label.starts_with('-') || label.ends_with('-') {
			return false;
		}

		// Label must contain only alphanumeric and hyphen
		label
			.chars()
			.all(|ch| ch.is_ascii_alphanumeric() || ch == '-')
	}
}

/// URL validator
#[derive(Debug, Clone)]
pub struct URLValidator {
	/// The message.
	pub message: String,
}

impl URLValidator {
	/// Create a new URL validator
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{URLValidator, Validator};
	///
	/// let validator = URLValidator::new();
	/// assert!(validator.validate("https://example.com").is_ok());
	/// assert!(validator.validate("http://example.com/path").is_ok());
	/// assert!(validator.validate("ftp://example.com").is_err());
	/// assert!(validator.validate("example.com").is_err());
	/// ```
	pub fn new() -> Self {
		Self {
			message: "Enter a valid URL".to_string(),
		}
	}
	/// Create a URL validator with custom error message
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{URLValidator, Validator};
	///
	/// let validator = URLValidator::with_message("Please provide a valid URL");
	/// assert_eq!(validator.message(), "Please provide a valid URL");
	/// ```
	pub fn with_message(message: impl Into<String>) -> Self {
		Self {
			message: message.into(),
		}
	}
}

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

impl Validator for URLValidator {
	fn validate(&self, value: &str) -> Result<()> {
		// URL validation with proper scheme, domain, and optional path
		static URL_REGEX: Lazy<Regex> = Lazy::new(|| {
			Regex::new(r"^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(/.*)?$")
				.expect("Invalid URL regex pattern")
		});

		if !URL_REGEX.is_match(value) {
			return Err(reinhardt_core::exception::Error::Validation(
				self.message.clone(),
			));
		}
		Ok(())
	}

	fn message(&self) -> String {
		self.message.clone()
	}
}

impl validators_crate::Validator<str> for URLValidator {
	fn validate(&self, value: &str) -> ValidationResult<()> {
		static URL_REGEX: Lazy<Regex> = Lazy::new(|| {
			Regex::new(r"^https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(/.*)?$")
				.expect("Invalid URL regex pattern")
		});

		if !URL_REGEX.is_match(value) {
			return Err(BaseValidationError::Custom(self.message.clone()));
		}
		Ok(())
	}
}

impl OrmValidator for URLValidator {
	fn message(&self) -> String {
		self.message.clone()
	}
}

/// Regex validator with compile-time pattern validation and runtime caching
#[derive(Debug)]
pub struct RegexValidator {
	pattern: String,
	compiled_regex: Regex,
	message: String,
}

impl Clone for RegexValidator {
	fn clone(&self) -> Self {
		Self {
			pattern: self.pattern.clone(),
			compiled_regex: Regex::new(&self.pattern)
				.expect("Regex should be valid since it was validated at construction"),
			message: self.message.clone(),
		}
	}
}

impl RegexValidator {
	/// Create a new RegexValidator with compile-time pattern validation
	///
	/// # Panics
	/// Panics if the regex pattern is invalid. This is intentional to catch
	/// regex errors at initialization time rather than at validation time.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{RegexValidator, Validator};
	///
	/// let validator = RegexValidator::new(r"^\d{3}-\d{4}$");
	/// assert!(validator.validate("123-4567").is_ok());
	/// assert!(validator.validate("abc-defg").is_err());
	/// ```
	pub fn new(pattern: impl Into<String>) -> Self {
		let pattern = pattern.into();
		let compiled_regex = Regex::new(&pattern)
			.unwrap_or_else(|e| panic!("Invalid regex pattern '{}': {}", pattern, e));

		Self {
			message: format!("Value does not match pattern: {}", pattern),
			pattern,
			compiled_regex,
		}
	}
	/// Create a new RegexValidator with a custom error message
	///
	/// # Panics
	/// Panics if the regex pattern is invalid.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{RegexValidator, Validator};
	///
	/// let validator = RegexValidator::with_message(r"^\d{5}$", "ZIP code must be 5 digits");
	/// assert_eq!(validator.message(), "ZIP code must be 5 digits");
	/// assert!(validator.validate("12345").is_ok());
	/// assert!(validator.validate("1234").is_err());
	/// ```
	pub fn with_message(pattern: impl Into<String>, message: impl Into<String>) -> Self {
		let pattern = pattern.into();
		let compiled_regex = Regex::new(&pattern)
			.unwrap_or_else(|e| panic!("Invalid regex pattern '{}': {}", pattern, e));

		Self {
			pattern,
			compiled_regex,
			message: message.into(),
		}
	}
	/// Try to create a new RegexValidator, returning an error if the pattern is invalid
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::RegexValidator;
	///
	/// // Valid pattern
	/// let result = RegexValidator::try_new(r"^\d+$");
	/// assert!(result.is_ok());
	///
	/// // Invalid pattern
	/// let result = RegexValidator::try_new(r"[invalid(regex");
	/// assert!(result.is_err());
	/// ```
	pub fn try_new(pattern: impl Into<String>) -> std::result::Result<Self, regex::Error> {
		let pattern = pattern.into();
		let compiled_regex = Regex::new(&pattern)?;

		Ok(Self {
			message: format!("Value does not match pattern: {}", pattern),
			pattern,
			compiled_regex,
		})
	}
	/// Get the regex pattern
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::RegexValidator;
	///
	/// let validator = RegexValidator::new(r"^\d{3}-\d{4}$");
	/// assert_eq!(validator.pattern(), r"^\d{3}-\d{4}$");
	/// ```
	pub fn pattern(&self) -> &str {
		&self.pattern
	}
}

impl Validator for RegexValidator {
	fn validate(&self, value: &str) -> Result<()> {
		if !self.compiled_regex.is_match(value) {
			return Err(reinhardt_core::exception::Error::Validation(
				self.message.clone(),
			));
		}
		Ok(())
	}

	fn message(&self) -> String {
		self.message.clone()
	}
}

impl validators_crate::Validator<str> for RegexValidator {
	fn validate(&self, value: &str) -> ValidationResult<()> {
		if !self.compiled_regex.is_match(value) {
			return Err(BaseValidationError::Custom(self.message.clone()));
		}
		Ok(())
	}
}

impl OrmValidator for RegexValidator {
	fn message(&self) -> String {
		self.message.clone()
	}
}

/// Numeric range validator
#[derive(Debug, Clone)]
pub struct RangeValidator {
	/// The min.
	pub min: Option<i64>,
	/// The max.
	pub max: Option<i64>,
	/// The message.
	pub message: String,
}

impl RangeValidator {
	/// Create a new numeric range validator
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{RangeValidator, Validator};
	///
	/// let validator = RangeValidator::new(Some(0), Some(100));
	/// assert!(validator.validate("50").is_ok());
	/// assert!(validator.validate("0").is_ok());
	/// assert!(validator.validate("100").is_ok());
	/// assert!(validator.validate("-1").is_err());
	/// assert!(validator.validate("101").is_err());
	/// ```
	pub fn new(min: Option<i64>, max: Option<i64>) -> Self {
		let message = match (min, max) {
			(Some(min), Some(max)) => format!("Value must be between {} and {}", min, max),
			(Some(min), None) => format!("Value must be at least {}", min),
			(None, Some(max)) => format!("Value must be at most {}", max),
			(None, None) => "Invalid range".to_string(),
		};
		Self { min, max, message }
	}
	/// Create a range validator with custom error message
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{RangeValidator, Validator};
	///
	/// let validator = RangeValidator::with_message(Some(18), Some(65), "Age must be 18-65");
	/// assert_eq!(validator.message(), "Age must be 18-65");
	/// ```
	pub fn with_message(min: Option<i64>, max: Option<i64>, message: impl Into<String>) -> Self {
		Self {
			min,
			max,
			message: message.into(),
		}
	}
}

impl Validator for RangeValidator {
	fn validate(&self, value: &str) -> Result<()> {
		let num: i64 = value.parse().map_err(|_| {
			reinhardt_core::exception::Error::Validation("Invalid number".to_string())
		})?;

		if let Some(min) = self.min
			&& num < min
		{
			return Err(reinhardt_core::exception::Error::Validation(
				self.message.clone(),
			));
		}

		if let Some(max) = self.max
			&& num > max
		{
			return Err(reinhardt_core::exception::Error::Validation(
				self.message.clone(),
			));
		}

		Ok(())
	}

	fn message(&self) -> String {
		self.message.clone()
	}
}

impl validators_crate::Validator<str> for RangeValidator {
	fn validate(&self, value: &str) -> ValidationResult<()> {
		let num: i64 = value
			.parse()
			.map_err(|_| BaseValidationError::Custom("Invalid number".to_string()))?;

		if let Some(min) = self.min
			&& num < min
		{
			return Err(BaseValidationError::Custom(self.message.clone()));
		}

		if let Some(max) = self.max
			&& num > max
		{
			return Err(BaseValidationError::Custom(self.message.clone()));
		}

		Ok(())
	}
}

impl OrmValidator for RangeValidator {
	fn message(&self) -> String {
		self.message.clone()
	}
}

/// Validator collection for a field
pub struct FieldValidators {
	/// The validators.
	pub validators: Vec<Box<dyn Validator>>,
}

impl FieldValidators {
	/// Create a new empty field validators collection
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{FieldValidators, RequiredValidator};
	///
	/// let validators = FieldValidators::new()
	///     .with_validator(Box::new(RequiredValidator::new()));
	/// // Verify validator was added (type check passes)
	/// let _: FieldValidators = validators;
	/// ```
	pub fn new() -> Self {
		Self {
			validators: Vec::new(),
		}
	}
	/// Add a validator to this field's validator chain
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{FieldValidators, RequiredValidator, MaxLengthValidator};
	///
	/// let validators = FieldValidators::new()
	///     .with_validator(Box::new(RequiredValidator::new()))
	///     .with_validator(Box::new(MaxLengthValidator::new(100)));
	/// // Verify both validators were added successfully
	/// assert!(validators.validate("hello").is_ok());
	/// assert!(validators.validate("").is_err()); // Fails RequiredValidator
	/// ```
	pub fn with_validator(mut self, validator: Box<dyn Validator>) -> Self {
		self.validators.push(validator);
		self
	}
	/// Validate a value against all validators in this collection
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{FieldValidators, RequiredValidator, MaxLengthValidator, Validator};
	///
	/// let validators = FieldValidators::new()
	///     .with_validator(Box::new(RequiredValidator::new()))
	///     .with_validator(Box::new(MaxLengthValidator::new(10)));
	///
	/// assert!(validators.validate("hello").is_ok());
	/// assert!(validators.validate("").is_err()); // Required
	/// assert!(validators.validate("hello world long text").is_err()); // Too long
	/// ```
	pub fn validate(&self, value: &str) -> Result<()> {
		for validator in &self.validators {
			validator.validate(value)?;
		}
		Ok(())
	}
}

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

/// Model validators collection
pub struct ModelValidators {
	/// The field validators.
	pub field_validators: HashMap<String, FieldValidators>,
}

impl ModelValidators {
	/// Create a new model validators collection
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::ModelValidators;
	///
	/// let mut model_validators = ModelValidators::new();
	/// assert_eq!(model_validators.field_validators.len(), 0);
	/// ```
	pub fn new() -> Self {
		Self {
			field_validators: HashMap::new(),
		}
	}
	/// Register validators for a specific field
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{ModelValidators, FieldValidators, EmailValidator};
	///
	/// let mut model_validators = ModelValidators::new();
	/// let email_validators = FieldValidators::new()
	///     .with_validator(Box::new(EmailValidator::new()));
	/// model_validators.add_field_validator("email".to_string(), email_validators);
	/// assert_eq!(model_validators.field_validators.len(), 1);
	/// assert!(model_validators.field_validators.contains_key("email"));
	/// ```
	pub fn add_field_validator(&mut self, field: String, validators: FieldValidators) {
		self.field_validators.insert(field, validators);
	}
	/// Validate a single field's value
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::validators::{ModelValidators, FieldValidators, EmailValidator};
	///
	/// let mut model_validators = ModelValidators::new();
	/// let email_validators = FieldValidators::new()
	///     .with_validator(Box::new(EmailValidator::new()));
	/// model_validators.add_field_validator("email".to_string(), email_validators);
	///
	/// assert!(model_validators.validate("email", "test@example.com").is_ok());
	/// assert!(model_validators.validate("email", "invalid").is_err());
	/// ```
	pub fn validate(&self, field: &str, value: &str) -> Result<()> {
		if let Some(validators) = self.field_validators.get(field) {
			validators.validate(value)?;
		}
		Ok(())
	}
	/// Validate all fields in a data map and return all validation errors
	///
	/// # Examples
	///
	/// ```
	/// use std::collections::HashMap;
	/// use reinhardt_db::orm::validators::{ModelValidators, FieldValidators, MinLengthValidator, EmailValidator};
	///
	/// let mut model_validators = ModelValidators::new();
	///
	/// let username_validators = FieldValidators::new()
	///     .with_validator(Box::new(MinLengthValidator::new(3)));
	/// let email_validators = FieldValidators::new()
	///     .with_validator(Box::new(EmailValidator::new()));
	///
	/// model_validators.add_field_validator("username".to_string(), username_validators);
	/// model_validators.add_field_validator("email".to_string(), email_validators);
	///
	/// let mut data = HashMap::new();
	/// data.insert("username".to_string(), "ab".to_string());
	/// data.insert("email".to_string(), "invalid".to_string());
	///
	/// let errors = model_validators.validate_all(&data);
	/// assert_eq!(errors.len(), 2);
	/// ```
	pub fn validate_all(&self, data: &HashMap<String, String>) -> Vec<ValidationError> {
		let mut errors = Vec::new();

		for (field, validators) in &self.field_validators {
			if let Some(value) = data.get(field)
				&& let Err(e) = validators.validate(value)
			{
				errors.push(ValidationError::new(
					field,
					e.to_string(),
					"validation_error",
				));
			}
		}

		errors
	}
}

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

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

	#[test]
	fn test_orm_validators_required() {
		let validator = RequiredValidator::new();
		assert!(validator.validate("test").is_ok());
		assert!(validator.validate("").is_err());
		assert!(validator.validate("   ").is_err());
	}

	#[test]
	fn test_orm_validators_max_length() {
		let validator = MaxLengthValidator::new(5);
		assert!(validator.validate("test").is_ok());
		assert!(validator.validate("test1").is_ok());
		assert!(validator.validate("test12").is_err());
	}

	#[test]
	fn test_orm_validators_min_length() {
		let validator = MinLengthValidator::new(3);
		assert!(validator.validate("test").is_ok());
		assert!(validator.validate("te").is_err());
	}

	#[test]
	fn test_email_validator() {
		let validator = EmailValidator::new();

		// Valid emails - standard format
		assert!(validator.validate("test@example.com").is_ok());
		assert!(validator.validate("user.name@example.com").is_ok());
		assert!(validator.validate("user+tag@example.co.uk").is_ok());
		assert!(validator.validate("first.last@sub.example.com").is_ok());

		// Valid emails - special characters allowed in local part
		assert!(validator.validate("user!tag@example.com").is_ok());
		assert!(validator.validate("user#tag@example.com").is_ok());
		assert!(validator.validate("user$tag@example.com").is_ok());
		assert!(validator.validate("user%tag@example.com").is_ok());
		assert!(validator.validate("user&tag@example.com").is_ok());
		assert!(validator.validate("user*tag@example.com").is_ok());
		assert!(validator.validate("user=tag@example.com").is_ok());
		assert!(validator.validate("user?tag@example.com").is_ok());
		assert!(validator.validate("user^tag@example.com").is_ok());
		assert!(validator.validate("user_tag@example.com").is_ok());
		assert!(validator.validate("user`tag@example.com").is_ok());
		assert!(validator.validate("user{tag@example.com").is_ok());
		assert!(validator.validate("user|tag@example.com").is_ok());
		assert!(validator.validate("user}tag@example.com").is_ok());
		assert!(validator.validate("user~tag@example.com").is_ok());

		// Valid emails - quoted strings
		assert!(validator.validate(r#""user name"@example.com"#).is_ok());
		assert!(validator.validate(r#""user@name"@example.com"#).is_ok());
		assert!(validator.validate(r#""user\"name"@example.com"#).is_ok());

		// Valid emails - IP addresses
		assert!(validator.validate("user@[192.168.1.1]").is_ok());
		assert!(validator.validate("user@[127.0.0.1]").is_ok());

		// Valid emails - IPv6 (basic)
		assert!(validator.validate("user@[IPv6:2001:db8::1]").is_ok());

		// Invalid emails - basic format errors
		assert!(validator.validate("invalid").is_err());
		assert!(validator.validate("no-at-sign.com").is_err());
		assert!(validator.validate("@example.com").is_err());
		assert!(validator.validate("user@").is_err());
		assert!(validator.validate("user @example.com").is_err());

		// Invalid emails - dot-atom errors
		assert!(validator.validate(".user@example.com").is_err());
		assert!(validator.validate("user.@example.com").is_err());
		assert!(validator.validate("user..name@example.com").is_err());

		// Invalid emails - domain errors
		assert!(validator.validate("user@.example.com").is_err());
		assert!(validator.validate("user@example.com.").is_err());
		assert!(validator.validate("user@example..com").is_err());
		assert!(validator.validate("user@-example.com").is_err());
		assert!(validator.validate("user@example-.com").is_err());
		assert!(validator.validate("user@example").is_err()); // Must have at least 2 labels

		// Invalid emails - length errors
		let long_local = "a".repeat(65);
		assert!(
			validator
				.validate(&format!("{}@example.com", long_local))
				.is_err()
		);

		// Invalid emails - quoted string errors
		assert!(validator.validate(r#""user"name"@example.com"#).is_err()); // Unescaped quote
		assert!(validator.validate(r#""user\"@example.com"#).is_err()); // Unclosed quote
	}

	#[test]
	fn test_url_validator() {
		let validator = URLValidator::new();
		// Valid URLs
		assert!(validator.validate("http://example.com").is_ok());
		assert!(validator.validate("https://example.com").is_ok());
		assert!(validator.validate("https://example.com/path").is_ok());
		assert!(validator.validate("http://sub.example.com").is_ok());

		// Invalid URLs
		assert!(validator.validate("example.com").is_err());
		assert!(validator.validate("ftp://example.com").is_err());
		assert!(validator.validate("http://").is_err());
	}

	#[test]
	fn test_regex_validator_valid_pattern() {
		let validator = RegexValidator::new(r"^\d{3}-\d{4}$");
		assert!(validator.validate("123-4567").is_ok());
		assert!(validator.validate("999-0000").is_ok());
		assert!(validator.validate("12-4567").is_err());
		assert!(validator.validate("123-45678").is_err());
		assert!(validator.validate("abc-defg").is_err());
	}

	#[test]
	fn test_regex_validator_alphanumeric() {
		let validator = RegexValidator::new(r"^[a-zA-Z0-9]+$");
		assert!(validator.validate("abc123").is_ok());
		assert!(validator.validate("ABC").is_ok());
		assert!(validator.validate("123").is_ok());
		assert!(validator.validate("abc-123").is_err());
		assert!(validator.validate("abc 123").is_err());
	}

	#[test]
	#[should_panic(expected = "Invalid regex pattern")]
	fn test_regex_validator_invalid_pattern() {
		// This should panic at construction time
		RegexValidator::new(r"[invalid(regex");
	}

	#[test]
	fn test_regex_validator_try_new_valid() {
		let result = RegexValidator::try_new(r"^\d+$");
		let validator = result.unwrap();
		assert!(validator.validate("123").is_ok());
		assert!(validator.validate("abc").is_err());
	}

	#[test]
	fn test_regex_validator_try_new_invalid() {
		let result = RegexValidator::try_new(r"[invalid(regex");
		assert!(result.is_err());
	}

	#[test]
	fn test_regex_validator_with_message() {
		use reinhardt_core::validators::OrmValidator;
		let validator = RegexValidator::with_message(r"^\d{5}$", "ZIP code must be 5 digits");
		assert_eq!(
			OrmValidator::message(&validator),
			"ZIP code must be 5 digits"
		);
		assert!(validator.validate("12345").is_ok());
		assert!(validator.validate("1234").is_err());
	}

	#[test]
	fn test_regex_validator_pattern() {
		let validator = RegexValidator::new(r"^\d+$");
		assert_eq!(validator.pattern(), r"^\d+$");
	}

	#[test]
	fn test_orm_range_validator() {
		let validator = RangeValidator::new(Some(0), Some(100));
		assert!(validator.validate("50").is_ok());
		assert!(validator.validate("0").is_ok());
		assert!(validator.validate("100").is_ok());
		assert!(validator.validate("-1").is_err());
		assert!(validator.validate("101").is_err());
	}

	#[test]
	fn test_field_validators() {
		let validators = FieldValidators::new()
			.with_validator(Box::new(RequiredValidator::new()))
			.with_validator(Box::new(MaxLengthValidator::new(10)));

		assert!(validators.validate("test").is_ok());
		assert!(validators.validate("").is_err());
		assert!(validators.validate("12345678901").is_err());
	}

	#[test]
	fn test_model_validators() {
		let mut model_validators = ModelValidators::new();

		let email_validators = FieldValidators::new()
			.with_validator(Box::new(RequiredValidator::new()))
			.with_validator(Box::new(EmailValidator::new()));

		model_validators.add_field_validator("email".to_string(), email_validators);

		assert!(
			model_validators
				.validate("email", "test@example.com")
				.is_ok()
		);
		assert!(model_validators.validate("email", "invalid").is_err());
	}

	#[test]
	fn test_validate_all() {
		let mut model_validators = ModelValidators::new();

		let username_validators = FieldValidators::new()
			.with_validator(Box::new(MinLengthValidator::new(3)))
			.with_validator(Box::new(MaxLengthValidator::new(20)));

		let email_validators =
			FieldValidators::new().with_validator(Box::new(EmailValidator::new()));

		model_validators.add_field_validator("username".to_string(), username_validators);
		model_validators.add_field_validator("email".to_string(), email_validators);

		let mut data = HashMap::new();
		data.insert("username".to_string(), "ab".to_string());
		data.insert("email".to_string(), "invalid".to_string());

		let errors = model_validators.validate_all(&data);
		assert_eq!(errors.len(), 2);
	}
}