wellformed 0.1.1

Declarative form validation schemas with transforms, constraints, and codegen
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
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
//! Type layer definitions for the IR.
//!
//! This module defines the type system for form schemas, including
//! primitives, domain types, and composite types.

use super::predicate::Constraint;
use super::transform::Transform;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// A type schema defining the structure and validation rules for a value.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TypeSchema {
    // ========================================================================
    // Primitive types
    // ========================================================================
    /// String type with optional transforms and constraints.
    String(StringSchema),

    /// Number type (floating point).
    Number(NumberSchema),

    /// Integer type (platform-dependent, use specific types for precision).
    Integer(IntegerSchema),

    /// Signed 32-bit integer (-2,147,483,648 to 2,147,483,647).
    Int32(Int32Schema),

    /// Signed 64-bit integer (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807).
    Int64(Int64Schema),

    /// Unsigned 32-bit integer (0 to 4,294,967,295).
    Uint32(Uint32Schema),

    /// Unsigned 64-bit integer (0 to 18,446,744,073,709,551,615).
    Uint64(Uint64Schema),

    /// Boolean type.
    Boolean(BooleanSchema),

    // ========================================================================
    // Domain-specific types
    // ========================================================================
    /// Money type (fixed-point decimal, stored as cents).
    Money(MoneySchema),

    /// Currency type with ISO 4217 code.
    Currency(CurrencySchema),

    /// Decimal type with configurable precision and scale.
    Decimal(DecimalSchema),

    /// Percentage type (0-100 or 0-1 format).
    Percentage(PercentageSchema),

    /// Date type (validated format).
    Date(DateSchema),

    // ========================================================================
    // Composite types
    // ========================================================================
    /// Object type with named properties.
    Object(ObjectSchema),

    /// Array type with item schema.
    Array(ArraySchema),

    /// Tuple type with fixed-position item schemas.
    Tuple(TupleSchema),

    /// Enum type (one of a fixed set of values).
    Enum(EnumSchema),

    /// Literal type matching exactly one value.
    Literal(LiteralSchema),

    /// Never type (no value is valid).
    Never(NeverSchema),

    /// Union type (one of several schemas).
    Union(UnionSchema),

    /// Intersection type (must satisfy all schemas).
    Intersection(IntersectionSchema),

    /// Record type (object with dynamic keys and uniform value schema).
    Record(RecordSchema),

    /// Preprocess wrapper (applies transforms before validating nested schema).
    Preprocess(PreprocessSchema),

    /// Catch wrapper (returns fallback value if nested schema validation fails).
    Catch(CatchSchema),

    // ========================================================================
    // Reference type
    // ========================================================================
    /// Reference to a named type definition.
    Ref {
        /// Name of the referenced type.
        #[serde(rename = "$ref")]
        name: String,
    },

    // ========================================================================
    // Any type (for extensibility)
    // ========================================================================
    /// Any JSON value (minimal validation).
    Any(AnySchema),
}

// ============================================================================
// String Schema
// ============================================================================

/// Schema for string values.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct StringSchema {
    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description for documentation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Optional example value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub example: Option<String>,
}

impl StringSchema {
    /// Create a new empty string schema.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a transform.
    pub fn transform(mut self, t: Transform) -> Self {
        self.transforms.push(t);
        self
    }

    /// Add a constraint.
    pub fn constraint(mut self, c: Constraint) -> Self {
        self.constraints.push(c);
        self
    }

    /// Set description.
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }
}

// ============================================================================
// Number Schema
// ============================================================================

/// Schema for number (floating-point) values.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct NumberSchema {
    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl NumberSchema {
    pub fn new() -> Self {
        Self::default()
    }
}

// ============================================================================
// Integer Schema
// ============================================================================

/// Schema for integer values.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct IntegerSchema {
    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl IntegerSchema {
    pub fn new() -> Self {
        Self::default()
    }
}

// ============================================================================
// Specific Integer Schemas
// ============================================================================

/// Schema for signed 32-bit integer values.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Int32Schema {
    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl Int32Schema {
    pub fn new() -> Self {
        Self::default()
    }
}

/// Schema for signed 64-bit integer values.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Int64Schema {
    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl Int64Schema {
    pub fn new() -> Self {
        Self::default()
    }
}

/// Schema for unsigned 32-bit integer values.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Uint32Schema {
    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl Uint32Schema {
    pub fn new() -> Self {
        Self::default()
    }
}

/// Schema for unsigned 64-bit integer values.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Uint64Schema {
    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl Uint64Schema {
    pub fn new() -> Self {
        Self::default()
    }
}

// ============================================================================
// Boolean Schema
// ============================================================================

/// Schema for boolean values.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct BooleanSchema {
    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl BooleanSchema {
    pub fn new() -> Self {
        Self::default()
    }
}

// ============================================================================
// Money Schema
// ============================================================================

/// Schema for money values (fixed-point decimal).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MoneySchema {
    /// Number of decimal places (default 2).
    #[serde(default = "default_scale")]
    pub scale: u8,

    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

fn default_scale() -> u8 {
    2
}

impl Default for MoneySchema {
    fn default() -> Self {
        Self {
            scale: 2,
            transforms: Vec::new(),
            constraints: Vec::new(),
            description: None,
        }
    }
}

impl MoneySchema {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_scale(mut self, scale: u8) -> Self {
        self.scale = scale;
        self
    }
}

// ============================================================================
// Currency Schema
// ============================================================================

/// Schema for currency values with ISO 4217 currency code.
///
/// Unlike Money (which just stores a numeric value in cents), Currency
/// includes the currency code for multi-currency support.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CurrencySchema {
    /// ISO 4217 currency code (e.g., "USD", "EUR", "GBP", "JPY").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,

    /// Number of decimal places (default 2, varies by currency: JPY=0, BHD=3).
    #[serde(default = "default_scale")]
    pub scale: u8,

    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl Default for CurrencySchema {
    fn default() -> Self {
        Self {
            code: None,
            scale: 2,
            transforms: Vec::new(),
            constraints: Vec::new(),
            description: None,
        }
    }
}

impl CurrencySchema {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the ISO 4217 currency code.
    pub fn with_code(mut self, code: impl Into<String>) -> Self {
        self.code = Some(code.into());
        self
    }

    /// Set the number of decimal places.
    pub fn with_scale(mut self, scale: u8) -> Self {
        self.scale = scale;
        self
    }
}

// ============================================================================
// Decimal Schema
// ============================================================================

/// Schema for decimal values with configurable precision.
///
/// This is useful for financial calculations where exact decimal
/// representation is required (unlike floating point).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct DecimalSchema {
    /// Maximum number of digits in total (precision).
    /// For example, precision=10 allows up to 10 total digits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub precision: Option<u8>,

    /// Number of digits after the decimal point (scale).
    /// For example, scale=4 allows up to 4 decimal places (e.g., tax rates like 0.0625).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scale: Option<u8>,

    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl DecimalSchema {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set precision (total digits).
    pub fn with_precision(mut self, precision: u8) -> Self {
        self.precision = Some(precision);
        self
    }

    /// Set scale (decimal places).
    pub fn with_scale(mut self, scale: u8) -> Self {
        self.scale = Some(scale);
        self
    }
}

// ============================================================================
// Percentage Schema
// ============================================================================

/// Format for percentage values.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PercentageFormat {
    /// Percentage as 0-100 (e.g., 6.25 means 6.25%)
    Whole,
    /// Percentage as 0-1 decimal (e.g., 0.0625 means 6.25%)
    #[default]
    Decimal,
}

/// Schema for percentage values.
///
/// Useful for tax rates, ownership percentages, withholding rates, etc.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PercentageSchema {
    /// The format for the percentage value.
    #[serde(default)]
    pub format: PercentageFormat,

    /// Whether to allow values over 100% (or 1.0 in decimal format).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub allow_over_100: bool,

    /// Number of decimal places for precision (e.g., 4 for 0.0625).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scale: Option<u8>,

    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl PercentageSchema {
    pub fn new() -> Self {
        Self::default()
    }

    /// Use whole number format (0-100).
    pub fn whole() -> Self {
        Self {
            format: PercentageFormat::Whole,
            ..Self::default()
        }
    }

    /// Use decimal format (0-1).
    pub fn decimal() -> Self {
        Self {
            format: PercentageFormat::Decimal,
            ..Self::default()
        }
    }

    /// Allow values over 100%.
    pub fn allow_over_100(mut self) -> Self {
        self.allow_over_100 = true;
        self
    }

    /// Set decimal precision.
    pub fn with_scale(mut self, scale: u8) -> Self {
        self.scale = Some(scale);
        self
    }
}

// ============================================================================
// Date Schema
// ============================================================================

/// Schema for date values.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct DateSchema {
    /// Expected input format (strftime-style). If set, input will be parsed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,

    /// Transforms to apply before validation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// Validation constraints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl DateSchema {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_format(mut self, format: impl Into<String>) -> Self {
        self.format = Some(format.into());
        self
    }
}

// ============================================================================
// Object Schema
// ============================================================================

/// Schema for object (struct) values.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ObjectSchema {
    /// Field definitions (ordered map for deterministic output).
    /// Serialized as `properties` to match the portable JSON IR.
    /// Also accepts legacy `fields` on input.
    #[serde(
        rename = "properties",
        default,
        alias = "fields",
        skip_serializing_if = "IndexMap::is_empty"
    )]
    pub fields: IndexMap<String, PropertySchema>,

    /// Page definitions for PDF rendering.
    /// Each page can specify which fields to render and their positions.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub pages: IndexMap<String, PageSchema>,

    /// AcroForm field mappings for PDF form filling.
    /// Maps schema fields to PDF AcroForm field IDs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub acroform_mappings: Vec<AcroFormFieldComposition>,

    /// Whether additional properties are allowed.
    #[serde(default = "default_false", skip_serializing_if = "is_false")]
    pub additional_properties: bool,

    /// Behavior for unknown keys not defined in `fields`.
    ///
    /// If omitted, runtime behavior falls back to `additional_properties`
    /// for backwards compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unknown_keys: Option<UnknownKeysBehavior>,

    /// Schema for unknown keys (equivalent to Zod's catchall).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub catchall: Option<Box<TypeSchema>>,

    /// Cross-field validation rules.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub rules: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Schema for a PDF page defining which fields appear and their render positions.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PageSchema {
    /// Human-readable name for this page (e.g., "Copy A", "Copy B").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Fields to render on this page, with their render metadata.
    /// Keys are field names from the parent object's `fields`.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub fields: IndexMap<String, RenderMetadata>,
}

/// Defines how schema fields compose into a single AcroForm PDF field.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct AcroFormFieldComposition {
    /// AcroForm field ID in the PDF, for example `f1_1[0]`.
    pub field_id: String,

    /// Page number (1-indexed).
    pub page: u32,

    /// Copy identifier (e.g., "A", "B", "C").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub copy: Option<String>,

    /// Schema field keys that compose into this AcroForm field.
    /// Usually a single field, but can be multiple for concatenated values.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub compose: Vec<String>,

    /// Separator to use when composing multiple fields (simple join).
    /// Ignored if `format` is specified.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub separator: String,

    /// Format string for composing multiple fields.
    /// Uses `{field_key}` placeholders, e.g., "{F}\n{G}\n{M}\n{N}\n{O}, {P} {Q}".
    /// Takes precedence over `separator` when specified.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,
}

fn default_false() -> bool {
    false
}

fn is_false(b: &bool) -> bool {
    !*b
}

/// Behavior for unknown keys on object schemas.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UnknownKeysBehavior {
    /// Reject unknown keys with validation errors.
    Strict,
    /// Keep unknown keys as-is.
    Passthrough,
    /// Remove unknown keys from the normalized value.
    Strip,
}

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

    /// Add a required field.
    pub fn field(mut self, name: impl Into<String>, schema: TypeSchema) -> Self {
        self.fields.insert(
            name.into(),
            PropertySchema {
                schema,
                required: true,
                description: None,
                label: None,
                render: None,
                acroform: None,
                section: None,
            },
        );
        self
    }

    /// Add a required property (alias for field, for backwards compatibility).
    pub fn property(self, name: impl Into<String>, schema: TypeSchema) -> Self {
        self.field(name, schema)
    }

    /// Add an optional field.
    pub fn optional_field(mut self, name: impl Into<String>, schema: TypeSchema) -> Self {
        self.fields.insert(
            name.into(),
            PropertySchema {
                schema,
                required: false,
                description: None,
                label: None,
                render: None,
                acroform: None,
                section: None,
            },
        );
        self
    }

    /// Add an optional property (alias for optional_field, for backwards compatibility).
    pub fn optional_property(self, name: impl Into<String>, schema: TypeSchema) -> Self {
        self.optional_field(name, schema)
    }

    /// Add a page definition for PDF rendering.
    pub fn page(mut self, page_num: impl Into<String>, page_schema: PageSchema) -> Self {
        self.pages.insert(page_num.into(), page_schema);
        self
    }

    /// Add a cross-field rule.
    pub fn rule(mut self, constraint: Constraint) -> Self {
        self.rules.push(constraint);
        self
    }

    /// Allow additional properties.
    pub fn allow_additional(mut self) -> Self {
        self.additional_properties = true;
        self.unknown_keys = Some(UnknownKeysBehavior::Passthrough);
        self
    }

    /// Reject unknown keys.
    pub fn strict(mut self) -> Self {
        self.additional_properties = false;
        self.unknown_keys = Some(UnknownKeysBehavior::Strict);
        self
    }

    /// Keep unknown keys.
    pub fn passthrough(mut self) -> Self {
        self.additional_properties = true;
        self.unknown_keys = Some(UnknownKeysBehavior::Passthrough);
        self
    }

    /// Remove unknown keys.
    pub fn strip(mut self) -> Self {
        self.additional_properties = false;
        self.unknown_keys = Some(UnknownKeysBehavior::Strip);
        self
    }

    /// Validate unknown keys with a catchall schema.
    pub fn catchall(mut self, schema: TypeSchema) -> Self {
        self.catchall = Some(Box::new(schema));
        self.additional_properties = true;
        self.unknown_keys = Some(UnknownKeysBehavior::Passthrough);
        self
    }
}

impl PageSchema {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the page name.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Add a field with its render metadata.
    pub fn field(mut self, name: impl Into<String>, render: RenderMetadata) -> Self {
        self.fields.insert(name.into(), render);
        self
    }
}

/// A property in an object schema.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PropertySchema {
    /// The schema for this property's value.
    #[serde(flatten)]
    pub schema: TypeSchema,

    /// Whether this property is required.
    #[serde(default = "default_true", skip_serializing_if = "is_true")]
    pub required: bool,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Human-readable label for the field (used for Rust field name generation).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,

    /// Optional rendering metadata for PDF overlay.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub render: Option<RenderMetadata>,

    /// Optional AcroForm field metadata.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub acroform: Option<AcroFormMetadata>,

    /// Optional section identifier for UI grouping.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub section: Option<String>,
}

/// Metadata for rendering a field on a PDF.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RenderMetadata {
    /// Render type: "text" or "checkbox"
    #[serde(rename = "type")]
    pub render_type: String,

    /// Page number (0-indexed)
    #[serde(default)]
    pub page: u32,

    /// X position in PDF points
    pub x: f32,

    /// Y position in PDF points
    pub y: f32,

    /// Font size in points (for text)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font_size: Option<f32>,

    /// Font type: "regular", "bold", "italic", "ocr_a"
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font: Option<String>,

    /// Color as hex string, e.g., "#000000"
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,

    /// Horizontal alignment: "left", "right", "center"
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub align: Option<String>,

    /// Vertical alignment: "baseline", "top", "bottom"
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub v_align: Option<String>,

    /// Horizontal scale (1.0 = 100%)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub h_scale: Option<f32>,

    /// Width (for checkboxes)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub width: Option<f32>,

    /// Height (for checkboxes)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub height: Option<f32>,

    /// Maximum width before text wraps
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_width: Option<f32>,

    /// Whether text can span multiple lines
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub multiline: Option<bool>,

    /// Line height for multiline text
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_height: Option<f32>,

    /// Box number on form (e.g., "1", "2a")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub box_number: Option<String>,
}

/// Metadata for AcroForm field mapping.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AcroFormMetadata {
    /// The AcroForm field ID (e.g., "f1_2", "c1_1")
    pub field_id: String,

    /// Field type: "text", "checkbox", "radio", etc.
    pub field_type: String,

    /// Optional copy suffix for multi-copy forms (e.g., "CopyA", "CopyB")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub copy_suffix: Option<String>,
}

fn default_true() -> bool {
    true
}

fn is_true(b: &bool) -> bool {
    *b
}

// ============================================================================
// Array Schema
// ============================================================================

/// Schema for array values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ArraySchema {
    /// Schema for array items.
    pub items: Box<TypeSchema>,

    /// Minimum number of items.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_items: Option<usize>,

    /// Maximum number of items.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_items: Option<usize>,

    /// Validation constraints on the array itself.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<Constraint>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl ArraySchema {
    pub fn new(items: TypeSchema) -> Self {
        Self {
            items: Box::new(items),
            min_items: None,
            max_items: None,
            constraints: Vec::new(),
            description: None,
        }
    }

    pub fn min_items(mut self, n: usize) -> Self {
        self.min_items = Some(n);
        self
    }

    pub fn max_items(mut self, n: usize) -> Self {
        self.max_items = Some(n);
        self
    }
}

// ============================================================================
// Tuple Schema
// ============================================================================

/// Schema for tuple values (fixed-length arrays with per-index types).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TupleSchema {
    /// Schemas for tuple items, in order.
    pub items: Vec<TypeSchema>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl TupleSchema {
    pub fn new(items: Vec<TypeSchema>) -> Self {
        Self {
            items,
            description: None,
        }
    }
}

// ============================================================================
// Enum Schema
// ============================================================================

/// Schema for enum values (one of a fixed set).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnumSchema {
    /// Allowed values.
    pub values: Vec<Value>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl EnumSchema {
    pub fn new(values: Vec<Value>) -> Self {
        Self {
            values,
            description: None,
        }
    }

    pub fn from_strings(values: &[&str]) -> Self {
        Self {
            values: values
                .iter()
                .map(|s| Value::String(s.to_string()))
                .collect(),
            description: None,
        }
    }
}

// ============================================================================
// Literal Schema
// ============================================================================

/// Schema for literal values (must match exactly).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LiteralSchema {
    /// The literal value to match.
    pub value: Value,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl LiteralSchema {
    pub fn new(value: Value) -> Self {
        Self {
            value,
            description: None,
        }
    }
}

// ============================================================================
// Never Schema
// ============================================================================

/// Schema for never values (always invalid).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct NeverSchema {
    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl NeverSchema {
    pub fn new() -> Self {
        Self::default()
    }
}

// ============================================================================
// Union Schema
// ============================================================================

/// Schema for union types (one of several schemas).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UnionSchema {
    /// Possible schemas.
    #[serde(rename = "oneOf")]
    pub variants: Vec<TypeSchema>,

    /// Optional discriminator field for tagged unions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub discriminator: Option<String>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl UnionSchema {
    pub fn new(variants: Vec<TypeSchema>) -> Self {
        Self {
            variants,
            discriminator: None,
            description: None,
        }
    }

    pub fn discriminated(variants: Vec<TypeSchema>, discriminator: impl Into<String>) -> Self {
        Self {
            variants,
            discriminator: Some(discriminator.into()),
            description: None,
        }
    }
}

// ============================================================================
// Intersection Schema
// ============================================================================

/// Schema for intersection types (all schemas must match).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IntersectionSchema {
    /// Schemas that must all validate.
    #[serde(rename = "allOf")]
    pub variants: Vec<TypeSchema>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl IntersectionSchema {
    pub fn new(variants: Vec<TypeSchema>) -> Self {
        Self {
            variants,
            description: None,
        }
    }
}

// ============================================================================
// Record Schema
// ============================================================================

/// Schema for record/object maps with dynamic keys.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RecordSchema {
    /// Schema for record values.
    pub value: Box<TypeSchema>,

    /// Optional schema for record keys (validated against each key string).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key: Option<Box<TypeSchema>>,

    /// Whether known-key records should be treated as partial.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub partial: bool,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl RecordSchema {
    pub fn new(value: TypeSchema) -> Self {
        Self {
            value: Box::new(value),
            key: None,
            partial: false,
            description: None,
        }
    }

    pub fn with_key(mut self, key: TypeSchema) -> Self {
        self.key = Some(Box::new(key));
        self
    }

    pub fn partial(mut self) -> Self {
        self.partial = true;
        self
    }
}

// ============================================================================
// Preprocess/Catch Schema
// ============================================================================

/// Schema wrapper that applies transforms before validating an inner schema.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PreprocessSchema {
    /// Transforms to apply to the incoming value.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub transforms: Vec<Transform>,

    /// The nested schema to validate after preprocessing.
    pub schema: Box<TypeSchema>,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl PreprocessSchema {
    pub fn new(schema: TypeSchema) -> Self {
        Self {
            transforms: Vec::new(),
            schema: Box::new(schema),
            description: None,
        }
    }

    pub fn transform(mut self, transform: Transform) -> Self {
        self.transforms.push(transform);
        self
    }
}

/// Schema wrapper that provides a fallback value when validation fails.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CatchSchema {
    /// The nested schema to validate.
    pub schema: Box<TypeSchema>,

    /// Fallback value returned if nested validation fails.
    pub value: Value,

    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl CatchSchema {
    pub fn new(schema: TypeSchema, value: Value) -> Self {
        Self {
            schema: Box::new(schema),
            value,
            description: None,
        }
    }
}

// ============================================================================
// Any Schema
// ============================================================================

/// Schema for any JSON value.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct AnySchema {
    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl AnySchema {
    pub fn new() -> Self {
        Self::default()
    }
}

// ============================================================================
// TypeSchema constructors
// ============================================================================

impl TypeSchema {
    /// Create a string schema.
    pub fn string() -> Self {
        Self::String(StringSchema::new())
    }

    /// Create a number schema.
    pub fn number() -> Self {
        Self::Number(NumberSchema::new())
    }

    /// Create an integer schema.
    pub fn integer() -> Self {
        Self::Integer(IntegerSchema::new())
    }

    /// Create a signed 32-bit integer schema.
    pub fn int32() -> Self {
        Self::Int32(Int32Schema::new())
    }

    /// Create a signed 64-bit integer schema.
    pub fn int64() -> Self {
        Self::Int64(Int64Schema::new())
    }

    /// Create an unsigned 32-bit integer schema.
    pub fn uint32() -> Self {
        Self::Uint32(Uint32Schema::new())
    }

    /// Create an unsigned 64-bit integer schema.
    pub fn uint64() -> Self {
        Self::Uint64(Uint64Schema::new())
    }

    /// Create a boolean schema.
    pub fn boolean() -> Self {
        Self::Boolean(BooleanSchema::new())
    }

    /// Create a money schema.
    pub fn money() -> Self {
        Self::Money(MoneySchema::new())
    }

    /// Create a currency schema.
    pub fn currency() -> Self {
        Self::Currency(CurrencySchema::new())
    }

    /// Create a currency schema with a specific ISO 4217 code.
    pub fn currency_with_code(code: impl Into<String>) -> Self {
        Self::Currency(CurrencySchema::new().with_code(code))
    }

    /// Create a decimal schema.
    pub fn decimal() -> Self {
        Self::Decimal(DecimalSchema::new())
    }

    /// Create a decimal schema with specific precision and scale.
    pub fn decimal_with(precision: u8, scale: u8) -> Self {
        Self::Decimal(
            DecimalSchema::new()
                .with_precision(precision)
                .with_scale(scale),
        )
    }

    /// Create a percentage schema (decimal format 0-1).
    pub fn percentage() -> Self {
        Self::Percentage(PercentageSchema::new())
    }

    /// Create a percentage schema with whole number format (0-100).
    pub fn percentage_whole() -> Self {
        Self::Percentage(PercentageSchema::whole())
    }

    /// Create a date schema.
    pub fn date() -> Self {
        Self::Date(DateSchema::new())
    }

    /// Create an object schema.
    pub fn object() -> Self {
        Self::Object(ObjectSchema::new())
    }

    /// Create an array schema.
    pub fn array(items: TypeSchema) -> Self {
        Self::Array(ArraySchema::new(items))
    }

    /// Create a tuple schema.
    pub fn tuple(items: Vec<TypeSchema>) -> Self {
        Self::Tuple(TupleSchema::new(items))
    }

    /// Create an enum schema from strings.
    pub fn enum_values(values: &[&str]) -> Self {
        Self::Enum(EnumSchema::from_strings(values))
    }

    /// Create an intersection schema.
    pub fn intersection(variants: Vec<TypeSchema>) -> Self {
        Self::Intersection(IntersectionSchema::new(variants))
    }

    /// Create a record schema with a value schema.
    pub fn record(value: TypeSchema) -> Self {
        Self::Record(RecordSchema::new(value))
    }

    /// Create a preprocess wrapper for a schema.
    pub fn preprocess(schema: TypeSchema, transforms: Vec<Transform>) -> Self {
        Self::Preprocess(PreprocessSchema {
            transforms,
            schema: Box::new(schema),
            description: None,
        })
    }

    /// Create a catch wrapper for a schema with fallback value.
    pub fn catch(schema: TypeSchema, value: Value) -> Self {
        Self::Catch(CatchSchema::new(schema, value))
    }

    /// Create a literal schema.
    pub fn literal(value: Value) -> Self {
        Self::Literal(LiteralSchema::new(value))
    }

    /// Create a nullable schema (`schema | null`).
    pub fn nullable(schema: TypeSchema) -> Self {
        Self::Union(UnionSchema::new(vec![
            schema,
            TypeSchema::literal(Value::Null),
        ]))
    }

    /// Create a never schema.
    pub fn never() -> Self {
        Self::Never(NeverSchema::new())
    }

    /// Create a reference to a named type.
    pub fn ref_to(name: impl Into<String>) -> Self {
        Self::Ref { name: name.into() }
    }

    /// Create an any schema.
    pub fn any() -> Self {
        Self::Any(AnySchema::new())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::error::ErrorMeta;
    use crate::ir::predicate::Predicate;

    #[test]
    fn test_string_schema_serde() {
        let schema =
            TypeSchema::String(StringSchema::new().transform(Transform::trim()).constraint(
                Constraint::new(
                    Predicate::regex(r"^\d{9}$"),
                    ErrorMeta::new("INVALID", "Invalid format"),
                ),
            ));

        let json = serde_json::to_string_pretty(&schema).unwrap();
        assert!(json.contains("string"));
        assert!(json.contains("trim"));

        let parsed: TypeSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, schema);
    }

    #[test]
    fn test_object_schema_serde() {
        let schema = TypeSchema::Object(
            ObjectSchema::new()
                .property("name", TypeSchema::string())
                .optional_property("age", TypeSchema::integer())
                .strip()
                .catchall(TypeSchema::integer()),
        );

        let json = serde_json::to_string_pretty(&schema).unwrap();
        let parsed: TypeSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, schema);
    }

    #[test]
    fn test_object_schema_serializes_properties_key() {
        let schema = TypeSchema::Object(ObjectSchema::new().property("name", TypeSchema::string()));

        let json = serde_json::to_string(&schema).unwrap();
        assert!(json.contains("\"properties\""));
        assert!(!json.contains("\"fields\""));

        let legacy = r#"{"type":"object","fields":{"name":{"type":"string"}}}"#;
        let parsed: TypeSchema = serde_json::from_str(legacy).unwrap();
        assert_eq!(parsed, schema);
    }

    #[test]
    fn test_array_schema_serde() {
        let schema = TypeSchema::array(TypeSchema::string());
        let json = serde_json::to_string(&schema).unwrap();
        let parsed: TypeSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, schema);
    }

    #[test]
    fn test_ref_schema_serde() {
        let schema = TypeSchema::ref_to("Payee");
        let json = serde_json::to_string(&schema).unwrap();
        assert!(json.contains("$ref"));
        assert!(json.contains("Payee"));
    }

    #[test]
    fn test_enum_schema() {
        let schema = TypeSchema::enum_values(&["SSN", "EIN", "ITIN"]);
        let json = serde_json::to_string(&schema).unwrap();
        assert!(json.contains("SSN"));
        assert!(json.contains("EIN"));
    }

    #[test]
    fn test_literal_schema_serde() {
        let schema = TypeSchema::literal(serde_json::json!("active"));
        let json = serde_json::to_string(&schema).unwrap();
        let parsed: TypeSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, schema);
    }

    #[test]
    fn test_never_schema_serde() {
        let schema = TypeSchema::never();
        let json = serde_json::to_string(&schema).unwrap();
        let parsed: TypeSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, schema);
    }

    #[test]
    fn test_tuple_schema_serde() {
        let schema = TypeSchema::tuple(vec![TypeSchema::string(), TypeSchema::integer()]);
        let json = serde_json::to_string(&schema).unwrap();
        let parsed: TypeSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, schema);
    }

    #[test]
    fn test_nullable_schema() {
        let schema = TypeSchema::nullable(TypeSchema::string());
        let json = serde_json::to_string(&schema).unwrap();
        let parsed: TypeSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, schema);
    }

    #[test]
    fn test_intersection_schema_serde() {
        let schema =
            TypeSchema::intersection(vec![TypeSchema::string(), TypeSchema::literal(Value::Null)]);
        let json = serde_json::to_string(&schema).unwrap();
        let parsed: TypeSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, schema);
    }

    #[test]
    fn test_record_schema_serde() {
        let schema = TypeSchema::Record(
            RecordSchema::new(TypeSchema::integer()).with_key(TypeSchema::string()),
        );
        let json = serde_json::to_string(&schema).unwrap();
        let parsed: TypeSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, schema);
    }

    #[test]
    fn test_preprocess_catch_schema_serde() {
        let schema = TypeSchema::catch(
            TypeSchema::preprocess(TypeSchema::string(), vec![Transform::trim()]),
            serde_json::json!("fallback"),
        );
        let json = serde_json::to_string(&schema).unwrap();
        let parsed: TypeSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, schema);
    }
}