postmortem 0.1.1

A validation library that accumulates all errors for comprehensive feedback
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
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
//! Object schema validation.
//!
//! This module provides [`ObjectSchema`] for validating JSON objects with
//! typed fields, optional fields, default values, additional property handling,
//! and cross-field validation.

use indexmap::IndexMap;
use serde_json::{json, Map, Value};
use std::collections::HashMap;
use stillwater::Validation;

use crate::error::{SchemaError, SchemaErrors};
use crate::interop::ToJsonSchema;
use crate::path::JsonPath;

use super::traits::SchemaLike;

/// Type alias for cross-field validators.
///
/// A cross-field validator receives the validated object (after field validation)
/// and the current path, returning a validation result.
type CrossFieldValidator = Box<
    dyn Fn(&ValidatedObject, &JsonPath) -> Validation<(), SchemaErrors> + Send + Sync + 'static,
>;

/// Represents an object that has passed field-level validation.
///
/// All field values have been validated according to their schemas.
/// This type provides safe access to validated field values for cross-field validation.
pub struct ValidatedObject {
    fields: HashMap<String, Value>,
}

impl ValidatedObject {
    /// Get a field value by name. Returns None if field doesn't exist.
    pub fn get(&self, field: &str) -> Option<&Value> {
        self.fields.get(field)
    }

    /// Check if a field exists and is not null.
    ///
    /// Returns `false` for both missing fields and fields explicitly set to `null`.
    pub fn has(&self, field: &str) -> bool {
        self.get(field).is_some_and(|v| !v.is_null())
    }
}

/// Definition of a field within an object schema.
struct FieldDef {
    schema: Box<dyn super::traits::ValueValidator>,
    required: bool,
    default: Option<Value>,
}

/// How to handle properties not defined in the schema.
enum AdditionalProperties {
    /// Allow unknown properties (default behavior).
    Allow,
    /// Reject unknown properties.
    Deny,
    /// Validate unknown properties against a schema.
    Validate(Box<dyn super::traits::ValueValidator>),
}

/// A schema for validating JSON objects.
///
/// `ObjectSchema` validates that values are objects and optionally applies
/// constraints like required fields, optional fields with defaults, and
/// additional property handling. All field validation errors are accumulated
/// rather than short-circuiting on the first failure.
///
/// # Example
///
/// ```rust
/// use postmortem::{Schema, JsonPath};
/// use serde_json::json;
///
/// let schema = Schema::object()
///     .field("name", Schema::string().min_len(1))
///     .field("age", Schema::integer().positive())
///     .optional("email", Schema::string())
///     .additional_properties(false);
///
/// let result = schema.validate(&json!({
///     "name": "Alice",
///     "age": 30
/// }), &JsonPath::root());
/// assert!(result.is_success());
/// ```
pub struct ObjectSchema {
    fields: IndexMap<String, FieldDef>,
    additional_properties: AdditionalProperties,
    type_error_message: Option<String>,
    cross_field_validators: Vec<CrossFieldValidator>,
    skip_on_field_errors: bool,
}

impl ObjectSchema {
    /// Creates a new object schema with no fields.
    pub fn new() -> Self {
        Self {
            fields: IndexMap::new(),
            additional_properties: AdditionalProperties::Allow,
            type_error_message: None,
            cross_field_validators: Vec::new(),
            skip_on_field_errors: true,
        }
    }

    /// Adds a required field to the schema.
    ///
    /// The field must be present in the input object and its value must
    /// pass validation against the provided schema.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::{Schema, JsonPath};
    /// use serde_json::json;
    ///
    /// let schema = Schema::object()
    ///     .field("name", Schema::string().min_len(1));
    ///
    /// // Missing required field produces error
    /// let result = schema.validate(&json!({}), &JsonPath::root());
    /// assert!(result.is_failure());
    /// ```
    pub fn field<S>(mut self, name: impl Into<String>, schema: S) -> Self
    where
        S: SchemaLike + ToJsonSchema + 'static,
    {
        let name = name.into();
        self.fields.insert(
            name,
            FieldDef {
                schema: Box::new(SchemaWrapper(schema)),
                required: true,
                default: None,
            },
        );
        self
    }

    /// Adds an optional field to the schema.
    ///
    /// The field may be absent from the input object. If present, its value
    /// must pass validation against the provided schema.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::{Schema, JsonPath};
    /// use serde_json::json;
    ///
    /// let schema = Schema::object()
    ///     .optional("nickname", Schema::string());
    ///
    /// // Missing optional field is OK
    /// let result = schema.validate(&json!({}), &JsonPath::root());
    /// assert!(result.is_success());
    /// ```
    pub fn optional<S>(mut self, name: impl Into<String>, schema: S) -> Self
    where
        S: SchemaLike + ToJsonSchema + 'static,
    {
        let name = name.into();
        self.fields.insert(
            name,
            FieldDef {
                schema: Box::new(SchemaWrapper(schema)),
                required: false,
                default: None,
            },
        );
        self
    }

    /// Adds an optional field with a default value.
    ///
    /// If the field is absent from the input object, the default value is used.
    /// If present, its value must pass validation against the provided schema.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::{Schema, JsonPath};
    /// use serde_json::json;
    ///
    /// let schema = Schema::object()
    ///     .default("role", Schema::string(), json!("user"));
    ///
    /// let result = schema.validate(&json!({}), &JsonPath::root());
    /// assert!(result.is_success());
    /// // The validated object will include "role": "user"
    /// ```
    pub fn default<S>(mut self, name: impl Into<String>, schema: S, default: Value) -> Self
    where
        S: SchemaLike + ToJsonSchema + 'static,
    {
        let name = name.into();
        self.fields.insert(
            name,
            FieldDef {
                schema: Box::new(SchemaWrapper(schema)),
                required: false,
                default: Some(default),
            },
        );
        self
    }

    /// Configures how unknown properties are handled.
    ///
    /// By default, unknown properties are allowed. Use this method to reject
    /// unknown properties or validate them against a schema.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::{Schema, JsonPath};
    /// use serde_json::json;
    ///
    /// // Reject unknown properties
    /// let strict = Schema::object()
    ///     .field("name", Schema::string())
    ///     .additional_properties(false);
    ///
    /// let result = strict.validate(&json!({
    ///     "name": "Alice",
    ///     "unknown": "field"
    /// }), &JsonPath::root());
    /// assert!(result.is_failure());
    ///
    /// // Validate unknown properties against a schema
    /// let validated = Schema::object()
    ///     .field("name", Schema::string())
    ///     .additional_properties(Schema::string());
    /// ```
    pub fn additional_properties<S>(mut self, setting: S) -> Self
    where
        S: Into<AdditionalPropertiesSetting>,
    {
        self.additional_properties = setting.into().0;
        self
    }

    /// Sets a custom error message for type errors.
    ///
    /// This message is used when the input value is not an object.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::{Schema, JsonPath};
    /// use serde_json::json;
    ///
    /// let schema = Schema::object()
    ///     .error("must be a user object");
    ///
    /// let result = schema.validate(&json!("not an object"), &JsonPath::root());
    /// // Error message will be "must be a user object"
    /// ```
    pub fn error(mut self, message: impl Into<String>) -> Self {
        self.type_error_message = Some(message.into());
        self
    }

    /// Adds a custom cross-field validator.
    ///
    /// Cross-field validators run after all field-level validations pass (or fail,
    /// depending on `skip_on_field_errors` configuration). They receive a
    /// `ValidatedObject` containing all validated field values.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::{Schema, JsonPath};
    /// use serde_json::json;
    /// use stillwater::Validation;
    ///
    /// let schema = Schema::object()
    ///     .field("quantity", Schema::integer().positive())
    ///     .field("unit_price", Schema::integer().non_negative())
    ///     .field("total", Schema::integer().non_negative())
    ///     .custom(|obj, path| {
    ///         let qty = obj.get("quantity").and_then(|v| v.as_i64()).unwrap_or(0);
    ///         let price = obj.get("unit_price").and_then(|v| v.as_i64()).unwrap_or(0);
    ///         let total = obj.get("total").and_then(|v| v.as_i64()).unwrap_or(0);
    ///
    ///         if qty * price != total {
    ///             Validation::Failure(postmortem::SchemaErrors::single(
    ///                 postmortem::SchemaError::new(
    ///                     path.push_field("total"),
    ///                     "total must equal quantity * unit_price"
    ///                 ).with_code("invalid_total")
    ///             ))
    ///         } else {
    ///             Validation::Success(())
    ///         }
    ///     });
    /// ```
    pub fn custom<F>(self, validator: F) -> Self
    where
        F: Fn(&ValidatedObject, &JsonPath) -> Validation<(), SchemaErrors> + Send + Sync + 'static,
    {
        let mut schema = self;
        schema.cross_field_validators.push(Box::new(validator));
        schema
    }

    /// Configure whether to skip cross-field validation if field validation fails.
    ///
    /// Default: `true` (skip cross-field when fields are invalid).
    ///
    /// When `true`, cross-field validators only run if all field-level validations
    /// pass. This is usually the desired behavior since cross-field validators
    /// often assume fields have valid values.
    ///
    /// Set to `false` to always run cross-field validators, even if some field
    /// validations failed.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::Schema;
    ///
    /// let schema = Schema::object()
    ///     .field("name", Schema::string())
    ///     .skip_cross_field_on_errors(false);  // Always run cross-field validators
    /// ```
    pub fn skip_cross_field_on_errors(mut self, skip: bool) -> Self {
        self.skip_on_field_errors = skip;
        self
    }

    /// Requires a field when a condition is met.
    ///
    /// If the condition field matches the predicate, the required field must be present.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::Schema;
    /// use serde_json::json;
    ///
    /// let schema = Schema::object()
    ///     .field("method", Schema::string())
    ///     .optional("card_number", Schema::string())
    ///     .require_if("method", |v| v == &json!("card"), "card_number");
    /// ```
    pub fn require_if<P>(
        self,
        condition_field: impl Into<String>,
        predicate: P,
        required_field: impl Into<String>,
    ) -> Self
    where
        P: Fn(&Value) -> bool + Send + Sync + 'static,
    {
        let condition_field = condition_field.into();
        let required_field = required_field.into();

        self.custom(move |obj, path| {
            let condition_value = obj.get(&condition_field);
            let required_value = obj.get(&required_field);

            match (condition_value, required_value) {
                (Some(cv), None) if predicate(cv) => Validation::Failure(SchemaErrors::single(
                    SchemaError::new(
                        path.push_field(&required_field),
                        format!(
                            "'{}' is required when '{}' matches condition",
                            required_field, condition_field
                        ),
                    )
                    .with_code("conditional_required"),
                )),
                _ => Validation::Success(()),
            }
        })
    }

    /// Ensures two fields are mutually exclusive.
    ///
    /// At most one of the two fields can be present (non-null).
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::Schema;
    ///
    /// let schema = Schema::object()
    ///     .optional("email", Schema::string())
    ///     .optional("phone", Schema::string())
    ///     .mutually_exclusive("email", "phone");
    /// ```
    pub fn mutually_exclusive(self, field1: impl Into<String>, field2: impl Into<String>) -> Self {
        let field1 = field1.into();
        let field2 = field2.into();

        self.custom(move |obj, path| {
            let has_field1 = obj.has(&field1);
            let has_field2 = obj.has(&field2);

            if has_field1 && has_field2 {
                Validation::Failure(SchemaErrors::single(
                    SchemaError::new(
                        path.clone(),
                        format!("'{}' and '{}' are mutually exclusive", field1, field2),
                    )
                    .with_code("mutually_exclusive"),
                ))
            } else {
                Validation::Success(())
            }
        })
    }

    /// Requires at least one of the specified fields to be present.
    ///
    /// At least one field must exist and be non-null.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::Schema;
    ///
    /// let schema = Schema::object()
    ///     .optional("email", Schema::string())
    ///     .optional("phone", Schema::string())
    ///     .at_least_one_of(["email", "phone"]);
    /// ```
    pub fn at_least_one_of<I, S>(self, fields: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let fields: Vec<String> = fields.into_iter().map(Into::into).collect();

        self.custom(move |obj, path| {
            let has_any = fields.iter().any(|f| obj.has(f));

            if has_any {
                Validation::Success(())
            } else {
                Validation::Failure(SchemaErrors::single(
                    SchemaError::new(
                        path.clone(),
                        format!("at least one of {:?} is required", fields),
                    )
                    .with_code("at_least_one_required"),
                ))
            }
        })
    }

    /// Ensures two fields have equal values.
    ///
    /// If both fields are present, their values must be equal.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::Schema;
    ///
    /// let schema = Schema::object()
    ///     .field("password", Schema::string())
    ///     .field("confirm_password", Schema::string())
    ///     .equal_fields("password", "confirm_password");
    /// ```
    pub fn equal_fields(self, field1: impl Into<String>, field2: impl Into<String>) -> Self {
        let field1 = field1.into();
        let field2 = field2.into();

        self.custom(move |obj, path| {
            let value1 = obj.get(&field1);
            let value2 = obj.get(&field2);

            match (value1, value2) {
                (Some(v1), Some(v2)) if v1 != v2 => Validation::Failure(SchemaErrors::single(
                    SchemaError::new(
                        path.push_field(&field2),
                        format!("'{}' must match '{}'", field2, field1),
                    )
                    .with_code("fields_not_equal"),
                )),
                _ => Validation::Success(()),
            }
        })
    }

    /// Ensures field1 is less than field2.
    ///
    /// Works for numbers and strings (lexicographic comparison).
    /// Skips validation if fields are missing, null, or have incompatible types.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::Schema;
    ///
    /// let schema = Schema::object()
    ///     .field("start_date", Schema::string())
    ///     .field("end_date", Schema::string())
    ///     .field_less_than("start_date", "end_date");
    /// ```
    pub fn field_less_than(self, field1: impl Into<String>, field2: impl Into<String>) -> Self {
        let field1 = field1.into();
        let field2 = field2.into();

        self.custom(move |obj, path| {
            let value1 = obj.get(&field1);
            let value2 = obj.get(&field2);

            match (value1, value2) {
                (Some(Value::Number(n1)), Some(Value::Number(n2))) => {
                    let Some(f1) = n1.as_f64() else {
                        return Validation::Success(());
                    };
                    let Some(f2) = n2.as_f64() else {
                        return Validation::Success(());
                    };

                    if f1 >= f2 {
                        Validation::Failure(SchemaErrors::single(
                            SchemaError::new(
                                path.push_field(&field1),
                                format!("'{}' must be less than '{}'", field1, field2),
                            )
                            .with_code("field_not_less_than"),
                        ))
                    } else {
                        Validation::Success(())
                    }
                }
                (Some(Value::String(s1)), Some(Value::String(s2))) => {
                    if s1 >= s2 {
                        Validation::Failure(SchemaErrors::single(
                            SchemaError::new(
                                path.push_field(&field1),
                                format!("'{}' must be less than '{}'", field1, field2),
                            )
                            .with_code("field_not_less_than"),
                        ))
                    } else {
                        Validation::Success(())
                    }
                }
                _ => Validation::Success(()),
            }
        })
    }

    /// Ensures field1 is less than or equal to field2.
    ///
    /// Works for numbers and strings (lexicographic comparison).
    /// Skips validation if fields are missing, null, or have incompatible types.
    ///
    /// # Example
    ///
    /// ```rust
    /// use postmortem::Schema;
    ///
    /// let schema = Schema::object()
    ///     .field("min", Schema::integer())
    ///     .field("max", Schema::integer())
    ///     .field_less_or_equal("min", "max");
    /// ```
    pub fn field_less_or_equal(self, field1: impl Into<String>, field2: impl Into<String>) -> Self {
        let field1 = field1.into();
        let field2 = field2.into();

        self.custom(move |obj, path| {
            let value1 = obj.get(&field1);
            let value2 = obj.get(&field2);

            match (value1, value2) {
                (Some(Value::Number(n1)), Some(Value::Number(n2))) => {
                    let Some(f1) = n1.as_f64() else {
                        return Validation::Success(());
                    };
                    let Some(f2) = n2.as_f64() else {
                        return Validation::Success(());
                    };

                    if f1 > f2 {
                        Validation::Failure(SchemaErrors::single(
                            SchemaError::new(
                                path.push_field(&field1),
                                format!("'{}' must be less than or equal to '{}'", field1, field2),
                            )
                            .with_code("field_not_less_or_equal"),
                        ))
                    } else {
                        Validation::Success(())
                    }
                }
                (Some(Value::String(s1)), Some(Value::String(s2))) => {
                    if s1 > s2 {
                        Validation::Failure(SchemaErrors::single(
                            SchemaError::new(
                                path.push_field(&field1),
                                format!("'{}' must be less than or equal to '{}'", field1, field2),
                            )
                            .with_code("field_not_less_or_equal"),
                        ))
                    } else {
                        Validation::Success(())
                    }
                }
                _ => Validation::Success(()),
            }
        })
    }

    /// Validates a value against this schema.
    ///
    /// Returns `Validation::Success` with a `Map<String, Value>` containing
    /// the validated fields if all validations pass, or `Validation::Failure`
    /// with accumulated errors if any validations fail.
    pub fn validate(
        &self,
        value: &Value,
        path: &JsonPath,
    ) -> Validation<Map<String, Value>, SchemaErrors> {
        // Check if it's an object
        let obj = match value.as_object() {
            Some(o) => o,
            None => {
                let message = self
                    .type_error_message
                    .clone()
                    .unwrap_or_else(|| "expected object".to_string());
                return Validation::Failure(SchemaErrors::single(
                    SchemaError::new(path.clone(), message)
                        .with_code("invalid_type")
                        .with_got(value_type_name(value))
                        .with_expected("object"),
                ));
            }
        };

        let mut errors = Vec::new();
        let mut validated = Map::new();

        // Validate defined fields
        for (name, field_def) in &self.fields {
            let field_path = path.push_field(name);

            match obj.get(name) {
                Some(field_value) => {
                    match field_def.schema.validate_value(field_value, &field_path) {
                        Validation::Success(v) => {
                            validated.insert(name.clone(), v);
                        }
                        Validation::Failure(e) => {
                            errors.extend(e.into_iter());
                        }
                    }
                }
                None if field_def.required => {
                    errors.push(
                        SchemaError::new(
                            field_path,
                            format!("required field '{}' is missing", name),
                        )
                        .with_code("required")
                        .with_expected("value"),
                    );
                }
                None => {
                    // Optional field - use default if provided
                    if let Some(default) = &field_def.default {
                        validated.insert(name.clone(), default.clone());
                    }
                }
            }
        }

        // Handle additional properties
        for (key, value) in obj {
            if !self.fields.contains_key(key) {
                let field_path = path.push_field(key);
                match &self.additional_properties {
                    AdditionalProperties::Allow => {
                        // Allow and include in output
                        validated.insert(key.clone(), value.clone());
                    }
                    AdditionalProperties::Deny => {
                        errors.push(
                            SchemaError::new(field_path, format!("unknown field '{}'", key))
                                .with_code("additional_property"),
                        );
                    }
                    AdditionalProperties::Validate(schema) => {
                        match schema.validate_value(value, &field_path) {
                            Validation::Success(v) => {
                                validated.insert(key.clone(), v);
                            }
                            Validation::Failure(e) => {
                                errors.extend(e.into_iter());
                            }
                        }
                    }
                }
            }
        }

        // Run cross-field validation if configured
        if !self.skip_on_field_errors || errors.is_empty() {
            let validated_obj = ValidatedObject {
                fields: validated
                    .iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect(),
            };

            for validator in &self.cross_field_validators {
                if let Validation::Failure(e) = validator(&validated_obj, path) {
                    errors.extend(e.into_iter());
                }
            }
        }

        if errors.is_empty() {
            Validation::Success(validated)
        } else {
            Validation::Failure(SchemaErrors::from_vec(errors))
        }
    }
}

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

impl SchemaLike for ObjectSchema {
    type Output = Map<String, Value>;

    fn validate(&self, value: &Value, path: &JsonPath) -> Validation<Self::Output, SchemaErrors> {
        self.validate(value, path)
    }

    fn validate_to_value(&self, value: &Value, path: &JsonPath) -> Validation<Value, SchemaErrors> {
        self.validate(value, path).map(Value::Object)
    }

    fn validate_with_context(
        &self,
        value: &Value,
        path: &JsonPath,
        context: &crate::validation::ValidationContext,
    ) -> Validation<Self::Output, SchemaErrors> {
        // Check if it's an object
        let obj = match value.as_object() {
            Some(o) => o,
            None => {
                let message = self
                    .type_error_message
                    .clone()
                    .unwrap_or_else(|| "expected object".to_string());
                return Validation::Failure(SchemaErrors::single(
                    SchemaError::new(path.clone(), message)
                        .with_code("invalid_type")
                        .with_got(value_type_name(value))
                        .with_expected("object"),
                ));
            }
        };

        let mut errors = Vec::new();
        let mut validated = Map::new();

        // Validate defined fields using context
        for (name, field_def) in &self.fields {
            let field_path = path.push_field(name);

            match obj.get(name) {
                Some(field_value) => {
                    match field_def.schema.validate_value_with_context(
                        field_value,
                        &field_path,
                        context,
                    ) {
                        Validation::Success(v) => {
                            validated.insert(name.clone(), v);
                        }
                        Validation::Failure(e) => {
                            errors.extend(e.into_iter());
                        }
                    }
                }
                None if field_def.required => {
                    errors.push(
                        SchemaError::new(
                            field_path,
                            format!("required field '{}' is missing", name),
                        )
                        .with_code("required")
                        .with_expected("value"),
                    );
                }
                None => {
                    // Optional field - use default if provided
                    if let Some(default) = &field_def.default {
                        validated.insert(name.clone(), default.clone());
                    }
                }
            }
        }

        // Handle additional properties
        for (key, value) in obj {
            if !self.fields.contains_key(key) {
                let field_path = path.push_field(key);
                match &self.additional_properties {
                    AdditionalProperties::Allow => {
                        // Allow and include in output
                        validated.insert(key.clone(), value.clone());
                    }
                    AdditionalProperties::Deny => {
                        errors.push(
                            SchemaError::new(field_path, format!("unknown field '{}'", key))
                                .with_code("additional_property"),
                        );
                    }
                    AdditionalProperties::Validate(schema) => {
                        match schema.validate_value_with_context(value, &field_path, context) {
                            Validation::Success(v) => {
                                validated.insert(key.clone(), v);
                            }
                            Validation::Failure(e) => {
                                errors.extend(e.into_iter());
                            }
                        }
                    }
                }
            }
        }

        // Run cross-field validation if configured
        if !self.skip_on_field_errors || errors.is_empty() {
            let validated_obj = ValidatedObject {
                fields: validated
                    .iter()
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect(),
            };

            for validator in &self.cross_field_validators {
                if let Validation::Failure(e) = validator(&validated_obj, path) {
                    errors.extend(e.into_iter());
                }
            }
        }

        if errors.is_empty() {
            Validation::Success(validated)
        } else {
            Validation::Failure(SchemaErrors::from_vec(errors))
        }
    }

    fn validate_to_value_with_context(
        &self,
        value: &Value,
        path: &JsonPath,
        context: &crate::validation::ValidationContext,
    ) -> Validation<Value, SchemaErrors> {
        self.validate_with_context(value, path, context)
            .map(Value::Object)
    }

    fn collect_refs(&self, refs: &mut Vec<String>) {
        // Collect refs from all field schemas
        for field_def in self.fields.values() {
            field_def.schema.collect_refs(refs);
        }

        // Collect refs from additional properties schema if present
        if let AdditionalProperties::Validate(schema) = &self.additional_properties {
            schema.collect_refs(refs);
        }
    }
}

/// A wrapper to adapt any `SchemaLike` to be a `ValueValidator`.
///
/// This is necessary because we store field schemas as `Box<dyn ValueValidator>`
/// but accept `SchemaLike` in the builder methods.
struct SchemaWrapper<S>(S);

impl<S: SchemaLike + ToJsonSchema> SchemaLike for SchemaWrapper<S> {
    type Output = Value;

    fn validate(&self, value: &Value, path: &JsonPath) -> Validation<Value, SchemaErrors> {
        self.0.validate_to_value(value, path)
    }

    fn validate_to_value(&self, value: &Value, path: &JsonPath) -> Validation<Value, SchemaErrors> {
        self.0.validate_to_value(value, path)
    }

    fn validate_with_context(
        &self,
        value: &Value,
        path: &JsonPath,
        context: &crate::validation::ValidationContext,
    ) -> Validation<Value, SchemaErrors> {
        self.0.validate_to_value_with_context(value, path, context)
    }

    fn validate_to_value_with_context(
        &self,
        value: &Value,
        path: &JsonPath,
        context: &crate::validation::ValidationContext,
    ) -> Validation<Value, SchemaErrors> {
        self.0.validate_to_value_with_context(value, path, context)
    }

    fn collect_refs(&self, refs: &mut Vec<String>) {
        self.0.collect_refs(refs);
    }
}

impl<S: SchemaLike + ToJsonSchema> ToJsonSchema for SchemaWrapper<S> {
    fn to_json_schema(&self) -> Value {
        self.0.to_json_schema()
    }
}

/// A type that can be converted into an `AdditionalProperties` setting.
///
/// This allows `additional_properties()` to accept different types:
/// - `bool`: `true` for Allow, `false` for Deny
/// - Any schema type: Validate additional properties against the schema
pub struct AdditionalPropertiesSetting(AdditionalProperties);

impl From<bool> for AdditionalPropertiesSetting {
    fn from(allow: bool) -> Self {
        if allow {
            AdditionalPropertiesSetting(AdditionalProperties::Allow)
        } else {
            AdditionalPropertiesSetting(AdditionalProperties::Deny)
        }
    }
}

impl<S: SchemaLike + ToJsonSchema + 'static> From<S> for AdditionalPropertiesSetting {
    fn from(schema: S) -> Self {
        AdditionalPropertiesSetting(AdditionalProperties::Validate(Box::new(SchemaWrapper(
            schema,
        ))))
    }
}

/// Returns the JSON type name for a value.
fn value_type_name(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

impl ToJsonSchema for ObjectSchema {
    fn to_json_schema(&self) -> Value {
        let mut properties = serde_json::Map::new();
        let mut required = Vec::new();

        for (name, field_def) in &self.fields {
            properties.insert(name.clone(), field_def.schema.to_json_schema());
            if field_def.required {
                required.push(name.clone());
            }
        }

        let mut schema = json!({
            "type": "object",
            "properties": properties,
        });

        if !required.is_empty() {
            schema["required"] = json!(required);
        }

        match &self.additional_properties {
            AdditionalProperties::Deny => {
                schema["additionalProperties"] = json!(false);
            }
            AdditionalProperties::Allow => {}
            AdditionalProperties::Validate(s) => {
                schema["additionalProperties"] = s.to_json_schema();
            }
        }

        schema
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{IntegerSchema, StringSchema};
    use serde_json::json;

    fn unwrap_success<T, E: std::fmt::Debug>(v: Validation<T, E>) -> T {
        v.into_result().unwrap()
    }

    fn unwrap_failure<T: std::fmt::Debug, E>(v: Validation<T, E>) -> E {
        v.into_result().unwrap_err()
    }

    #[test]
    fn test_empty_object_schema() {
        let schema = ObjectSchema::new();
        let result = schema.validate(&json!({}), &JsonPath::root());
        assert!(result.is_success());
    }

    #[test]
    fn test_object_schema_rejects_non_object() {
        let schema = ObjectSchema::new();

        let result = schema.validate(&json!("not an object"), &JsonPath::root());
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.first().code, "invalid_type");
        assert_eq!(errors.first().got, Some("string".to_string()));

        let result = schema.validate(&json!(42), &JsonPath::root());
        assert!(result.is_failure());

        let result = schema.validate(&json!(null), &JsonPath::root());
        assert!(result.is_failure());

        let result = schema.validate(&json!([1, 2, 3]), &JsonPath::root());
        assert!(result.is_failure());
    }

    #[test]
    fn test_required_field() {
        let schema = ObjectSchema::new().field("name", StringSchema::new());

        // Present and valid
        let result = schema.validate(&json!({"name": "Alice"}), &JsonPath::root());
        assert!(result.is_success());
        let obj = unwrap_success(result);
        assert_eq!(obj.get("name"), Some(&json!("Alice")));

        // Missing required field
        let result = schema.validate(&json!({}), &JsonPath::root());
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.first().code, "required");
        assert!(errors.first().message.contains("name"));
    }

    #[test]
    fn test_required_field_invalid_value() {
        let schema = ObjectSchema::new().field("age", IntegerSchema::new().positive());

        let result = schema.validate(&json!({"age": -5}), &JsonPath::root());
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.first().code, "positive");
    }

    #[test]
    fn test_optional_field() {
        let schema = ObjectSchema::new().optional("nickname", StringSchema::new());

        // Without optional field
        let result = schema.validate(&json!({}), &JsonPath::root());
        assert!(result.is_success());
        let obj = unwrap_success(result);
        assert!(obj.get("nickname").is_none());

        // With optional field
        let result = schema.validate(&json!({"nickname": "Bob"}), &JsonPath::root());
        assert!(result.is_success());
        let obj = unwrap_success(result);
        assert_eq!(obj.get("nickname"), Some(&json!("Bob")));
    }

    #[test]
    fn test_optional_field_invalid_value() {
        let schema = ObjectSchema::new().optional("age", IntegerSchema::new());

        // Invalid optional field value
        let result = schema.validate(&json!({"age": "not a number"}), &JsonPath::root());
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.first().code, "invalid_type");
    }

    #[test]
    fn test_default_field() {
        let schema = ObjectSchema::new().default("role", StringSchema::new(), json!("user"));

        // Without default field - uses default
        let result = schema.validate(&json!({}), &JsonPath::root());
        assert!(result.is_success());
        let obj = unwrap_success(result);
        assert_eq!(obj.get("role"), Some(&json!("user")));

        // With default field - uses provided value
        let result = schema.validate(&json!({"role": "admin"}), &JsonPath::root());
        assert!(result.is_success());
        let obj = unwrap_success(result);
        assert_eq!(obj.get("role"), Some(&json!("admin")));
    }

    #[test]
    fn test_additional_properties_allow() {
        let schema = ObjectSchema::new()
            .field("name", StringSchema::new())
            .additional_properties(true);

        let result = schema.validate(
            &json!({"name": "Alice", "extra": "field"}),
            &JsonPath::root(),
        );
        assert!(result.is_success());
        let obj = unwrap_success(result);
        assert_eq!(obj.get("extra"), Some(&json!("field")));
    }

    #[test]
    fn test_additional_properties_deny() {
        let schema = ObjectSchema::new()
            .field("name", StringSchema::new())
            .additional_properties(false);

        let result = schema.validate(
            &json!({"name": "Alice", "extra": "field"}),
            &JsonPath::root(),
        );
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.first().code, "additional_property");
        assert!(errors.first().message.contains("extra"));
    }

    #[test]
    fn test_additional_properties_validate() {
        let schema = ObjectSchema::new()
            .field("name", StringSchema::new())
            .additional_properties(IntegerSchema::new());

        // Valid additional property
        let result = schema.validate(&json!({"name": "Alice", "count": 42}), &JsonPath::root());
        assert!(result.is_success());

        // Invalid additional property
        let result = schema.validate(
            &json!({"name": "Alice", "count": "not a number"}),
            &JsonPath::root(),
        );
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.first().code, "invalid_type");
    }

    #[test]
    fn test_multiple_fields() {
        let schema = ObjectSchema::new()
            .field("name", StringSchema::new().min_len(1))
            .field("age", IntegerSchema::new().positive())
            .optional("email", StringSchema::new());

        let result = schema.validate(
            &json!({"name": "Alice", "age": 30, "email": "alice@example.com"}),
            &JsonPath::root(),
        );
        assert!(result.is_success());
    }

    #[test]
    fn test_error_accumulation() {
        let schema = ObjectSchema::new()
            .field("name", StringSchema::new().min_len(5))
            .field("age", IntegerSchema::new().positive());

        // Both fields invalid
        let result = schema.validate(&json!({"name": "AB", "age": -5}), &JsonPath::root());
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.len(), 2);
        assert!(errors.with_code("min_length").len() == 1);
        assert!(errors.with_code("positive").len() == 1);
    }

    #[test]
    fn test_error_accumulation_with_missing_fields() {
        let schema = ObjectSchema::new()
            .field("name", StringSchema::new())
            .field("age", IntegerSchema::new());

        // Both fields missing
        let result = schema.validate(&json!({}), &JsonPath::root());
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.len(), 2);
        assert_eq!(errors.with_code("required").len(), 2);
    }

    #[test]
    fn test_path_tracking() {
        let schema = ObjectSchema::new().field("user", StringSchema::new().min_len(5));

        let result = schema.validate(&json!({"user": "AB"}), &JsonPath::root());
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.first().path.to_string(), "user");
    }

    #[test]
    fn test_nested_object() {
        let address_schema = ObjectSchema::new()
            .field("street", StringSchema::new().min_len(1))
            .field("city", StringSchema::new().min_len(1));

        let user_schema = ObjectSchema::new()
            .field("name", StringSchema::new())
            .field("address", address_schema);

        // Valid nested object
        let result = user_schema.validate(
            &json!({
                "name": "Alice",
                "address": {"street": "123 Main St", "city": "NYC"}
            }),
            &JsonPath::root(),
        );
        assert!(result.is_success());

        // Invalid nested object
        let result = user_schema.validate(
            &json!({
                "name": "Alice",
                "address": {"street": "", "city": ""}
            }),
            &JsonPath::root(),
        );
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.len(), 2);
    }

    #[test]
    fn test_deeply_nested_path_tracking() {
        let inner = ObjectSchema::new().field("value", IntegerSchema::new().positive());
        let middle = ObjectSchema::new().field("inner", inner);
        let outer = ObjectSchema::new().field("middle", middle);

        let result = outer.validate(
            &json!({
                "middle": {
                    "inner": {
                        "value": -5
                    }
                }
            }),
            &JsonPath::root(),
        );
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.first().path.to_string(), "middle.inner.value");
    }

    #[test]
    fn test_custom_type_error_message() {
        let schema = ObjectSchema::new().error("must be a user object");

        let result = schema.validate(&json!("not an object"), &JsonPath::root());
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.first().message, "must be a user object");
    }

    #[test]
    fn test_unicode_field_names() {
        let schema = ObjectSchema::new()
            .field("名前", StringSchema::new())
            .field("年齢", IntegerSchema::new());

        let result = schema.validate(&json!({"名前": "太郎", "年齢": 25}), &JsonPath::root());
        assert!(result.is_success());

        let result = schema.validate(&json!({}), &JsonPath::root());
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.len(), 2);
    }

    #[test]
    fn test_empty_input_with_required_fields() {
        let schema = ObjectSchema::new()
            .field("a", StringSchema::new())
            .field("b", IntegerSchema::new());

        let result = schema.validate(&json!({}), &JsonPath::root());
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        assert_eq!(errors.len(), 2);
    }

    #[test]
    fn test_field_order_preserved() {
        let schema = ObjectSchema::new()
            .field("z", StringSchema::new())
            .field("a", StringSchema::new())
            .field("m", StringSchema::new());

        // Errors should be reported in field definition order
        let result = schema.validate(&json!({}), &JsonPath::root());
        assert!(result.is_failure());
        let errors = unwrap_failure(result);
        let paths: Vec<_> = errors.iter().map(|e| e.path.to_string()).collect();
        assert_eq!(paths, vec!["z", "a", "m"]);
    }

    #[test]
    fn test_schema_like_trait_validate_to_value() {
        let schema = ObjectSchema::new().field("name", StringSchema::new());

        let result = schema.validate_to_value(&json!({"name": "Alice"}), &JsonPath::root());
        assert!(result.is_success());
        match result.into_result().unwrap() {
            Value::Object(obj) => {
                assert_eq!(obj.get("name"), Some(&json!("Alice")));
            }
            _ => panic!("Expected object"),
        }
    }
}