jmap-calendars-types 0.4.2

JMAP Calendars extension data types (draft-ietf-jmap-calendars-*)
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
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
//! Integration tests for jmap-calendars-types.
//!
//! Test oracles are hand-written JSON fixtures constructed directly from:
//!   - draft-ietf-jmap-calendars-33 §4 (Calendar), §5 (CalendarEvent),
//!     §7 (CalendarEventNotification), §3 (ParticipantIdentity)
//!   - RFC 8984 §4 (JSCalendar sub-objects), §5.1 (Event-specific properties)
//!
//! No expected values are derived from the code under test.
//!
//! NOTE: JSON containing the sequence `"#` (e.g. CSS hex colors) requires
//! `r##"..."##` raw string delimiters because `"#` would terminate `r#"..."#`.

mod common;

use jmap_calendars_types::{
    Alert, AlertTrigger, BusyPeriod, BusyStatus, Calendar, CalendarAlert, CalendarEvent,
    CalendarEventFilterCondition, CalendarEventNotification, CalendarRights,
    CalendarsAccountCapability, CalendarsCapability, IncludeInAvailability, JMAP_CALENDARS_URI,
    Link, Participant, ParticipantIdentity, Person, PrincipalCalendarsCapability,
    PrincipalsAvailabilityAccountCapability, VirtualLocation,
};
use jmap_types::Id;

// ─── Calendar ────────────────────────────────────────────────────────────────

/// Deserialize a full Calendar from hand-written JSON and verify key fields.
/// Oracle derived from draft-ietf-jmap-calendars-33 §4 field descriptions.
#[test]
fn calendar_deserialize_full() {
    // r##"..."## needed because color value contains `"#`.
    let json = &common::fixture("calendar_deserialize_full.json");

    let cal: Calendar = serde_json::from_str(json).expect("Calendar deserialize");

    let id_val = cal.id.as_ref().expect("id present");
    assert_eq!(id_val.as_ref(), "cal-001");
    assert_eq!(cal.name, "Personal");
    assert_eq!(cal.description.as_deref(), Some("My personal calendar"));
    assert_eq!(cal.color.as_deref(), Some("#4287f5"));
    assert_eq!(cal.sort_order, 5);
    assert!(cal.is_subscribed);
    assert!(cal.is_visible);
    assert!(cal.is_default);
    assert_eq!(cal.include_in_availability, IncludeInAvailability::All);
    assert!(cal.default_alerts_with_time.is_none());
    assert!(cal.default_alerts_without_time.is_none());
    assert_eq!(cal.time_zone.as_deref(), Some("America/New_York"));
    assert!(cal.share_with.is_none());
    assert!(cal.my_rights.may_read_free_busy);
    assert!(cal.my_rights.may_write_all);
    assert!(cal.my_rights.may_share);
    assert!(cal.my_rights.may_delete);
}

/// Calendar round-trip: serialize then re-deserialize, verify equality.
#[test]
fn calendar_roundtrip() {
    let json = &common::fixture("calendar_roundtrip.json");
    let original: Calendar = serde_json::from_str(json).expect("first deserialize");
    let serialized = serde_json::to_string(&original).expect("serialize");
    let recovered: Calendar = serde_json::from_str(&serialized).expect("second deserialize");
    assert_eq!(original, recovered);
}

/// `Calendar.id` is `Option<Id>` with `skip_serializing_if` so a typed
/// /set create payload (where the caller has no server-assigned id yet)
/// does NOT emit `id` on the wire.
///
/// Oracle: RFC 8620 §5.3 — "The id property MUST NOT be set in the
/// create object." This test asserts the wire shape directly: a Calendar
/// deserialized from JSON without `id` must serialize back without `id`.
/// Independent of the code under test — the JSON input is hand-written.
#[test]
fn calendar_id_absent_when_none() {
    // JSON without an `id` field (matches /set create payload shape).
    let json = &common::fixture("calendar_id_absent_when_none.json");
    let cal: Calendar = serde_json::from_str(json).expect("Calendar must deserialize without id");
    assert!(cal.id.is_none(), "id must be None when absent from input");

    let out = serde_json::to_value(&cal).expect("serialize");
    let obj = out.as_object().expect("object");
    assert!(
        !obj.contains_key("id"),
        "id must be absent from wire when None (RFC 8620 §5.3 create payload contract): {out}"
    );
}

/// shareWith with actual rights deserializes correctly.
#[test]
fn calendar_share_with() {
    let json = &common::fixture("calendar_share_with.json");
    let cal: Calendar = serde_json::from_str(json).expect("calendar with shareWith");
    let share = cal.share_with.as_ref().expect("shareWith not None");
    let rights = share.values().next().expect("at least one entry");
    assert!(rights.may_read_free_busy);
    assert!(rights.may_read_items);
    assert!(!rights.may_write_all);
}

// ─── CalendarRights ───────────────────────────────────────────────────────────

/// `Default` produces all-false (most restrictive).
#[test]
fn calendar_rights_default_all_false() {
    let r = CalendarRights::default();
    assert!(!r.may_read_free_busy);
    assert!(!r.may_read_items);
    assert!(!r.may_write_all);
    assert!(!r.may_write_own);
    assert!(!r.may_update_private);
    assert!(!r.may_rsvp);
    assert!(!r.may_share);
    assert!(!r.may_delete);
}

/// All eight boolean fields serialize to the correct camelCase wire names.
/// Oracle: field names from draft-ietf-jmap-calendars-33 §4.
#[test]
fn calendar_rights_wire_names() {
    // Deserialize from known-good JSON then re-serialize to check wire names.
    let json = &common::fixture("calendar_rights_wire_names.json");
    let rights: CalendarRights = serde_json::from_str(json).expect("deserialize rights");
    let out = serde_json::to_value(&rights).expect("serialize");

    // Verify every wire field name against the spec.
    assert_eq!(out["mayReadFreeBusy"], true);
    assert_eq!(out["mayReadItems"], true);
    assert_eq!(out["mayWriteAll"], true);
    assert_eq!(out["mayWriteOwn"], true);
    assert_eq!(out["mayUpdatePrivate"], true);
    assert_eq!(out["mayRSVP"], true);
    assert_eq!(out["mayShare"], true);
    assert_eq!(out["mayDelete"], true);
}

// ─── IncludeInAvailability ────────────────────────────────────────────────────

/// All three known values serialize to the correct lowercase wire strings.
/// Oracle: spec §4 field description.
#[test]
fn include_in_availability_known_values() {
    let all = serde_json::to_string(&IncludeInAvailability::All).expect("serialize All");
    let attending =
        serde_json::to_string(&IncludeInAvailability::Attending).expect("serialize Attending");
    let none = serde_json::to_string(&IncludeInAvailability::None).expect("serialize None");

    assert_eq!(all, r#""all""#);
    assert_eq!(attending, r#""attending""#);
    assert_eq!(none, r#""none""#);
}

/// All three known values deserialize from the correct wire strings.
#[test]
fn include_in_availability_deserialize() {
    let all: IncludeInAvailability = serde_json::from_str(r#""all""#).expect("all");
    let attending: IncludeInAvailability =
        serde_json::from_str(r#""attending""#).expect("attending");
    let none: IncludeInAvailability = serde_json::from_str(r#""none""#).expect("none");

    assert_eq!(all, IncludeInAvailability::All);
    assert_eq!(attending, IncludeInAvailability::Attending);
    assert_eq!(none, IncludeInAvailability::None);
}

// ─── CalendarEvent ────────────────────────────────────────────────────────────

/// Minimal CalendarEvent with only id and calendarIds deserializes without error.
/// Oracle: draft §5 mandatory fields.
#[test]
fn calendar_event_minimal() {
    let json = &common::fixture("calendar_event_minimal.json");
    let ev: CalendarEvent = serde_json::from_str(json).expect("minimal CalendarEvent");
    let id_val = ev.id.as_ref().expect("id present");
    assert_eq!(id_val.as_ref(), "event-001");
    let cals = ev.calendar_ids.as_ref().expect("calendarIds");
    assert_eq!(cals.len(), 1);
    assert!(*cals.values().next().expect("first value"));
}

/// An all-fields-None (empty) CalendarEvent deserializes without error
/// (partial response per RFC 8620 §5.1).
#[test]
fn calendar_event_all_none() {
    let ev: CalendarEvent = serde_json::from_str("{}").expect("empty CalendarEvent");
    assert!(ev.id.is_none());
    assert!(ev.calendar_ids.is_none());
    assert!(ev.title.is_none());
    assert!(ev.start.is_none());
    assert!(ev.recurrence_rules.is_none());
}

/// Unset `isDraft` / `useDefaultAlerts` serialize as their `false` default.
///
/// Oracle: draft-ietf-jmap-calendars-33 §5.7: "In addition, the "id",
/// "calendarIds", "isOrigin", "isDraft", and "useDefaultAlerts" properties
/// MUST be included on each object." §5 types both as
/// "Boolean (default: false)".
#[test]
fn calendar_event_is_draft_and_use_default_alerts_always_serialized() {
    let ev: CalendarEvent = serde_json::from_str(&common::fixture(
        "calendar_event_is_draft_and_use_default_alerts_always_serialized.json",
    ))
    .unwrap();
    let out = serde_json::to_value(&ev).unwrap();
    assert_eq!(out["isDraft"], serde_json::Value::Bool(false), "{out}");
    assert_eq!(
        out["useDefaultAlerts"],
        serde_json::Value::Bool(false),
        "{out}"
    );
}

/// A richer CalendarEvent with JSCalendar scalar fields deserializes correctly.
/// Oracle: RFC 8984 §6.1 simple event example (adapted).
#[test]
fn calendar_event_scalar_fields() {
    let json = &common::fixture("calendar_event_scalar_fields.json");

    let ev: CalendarEvent = serde_json::from_str(json).expect("CalendarEvent deserialize");

    assert_eq!(ev.at_type.as_deref(), Some("Event"));
    assert_eq!(
        ev.uid.as_deref(),
        Some("2a358cee-6489-4f14-a57f-c104db4dc357")
    );
    assert_eq!(ev.title.as_deref(), Some("Team meeting"));
    assert_eq!(ev.description.as_deref(), Some("Monthly all-hands"));
    assert_eq!(ev.start.as_deref(), Some("2024-06-15T09:00:00"));
    assert_eq!(ev.duration.as_deref(), Some("PT1H"));
    assert_eq!(ev.time_zone.as_deref(), Some("America/New_York"));
    assert_eq!(ev.status.as_deref(), Some("confirmed"));
    assert_eq!(ev.is_draft, Some(false));
    assert_eq!(ev.is_origin, Some(true));
    assert_eq!(ev.show_without_time, Some(false));
    assert_eq!(ev.priority, Some(5));
    assert_eq!(ev.free_busy_status.as_deref(), Some("busy"));
    assert_eq!(ev.privacy.as_deref(), Some("public"));
    assert_eq!(ev.sequence, Some(0));
    assert_eq!(ev.color.as_deref(), Some("red"));
}

/// `keywords`, `categories` and `replyTo` decode as typed maps.
/// Oracle: RFC 8984 §4.2.10 `keywords: String[Boolean]`, §4.2.11
/// `categories: String[Boolean]`, §4.4.4 `replyTo: String[String]`;
/// a non-Boolean keyword value does not match the declared type.
#[test]
fn calendar_event_keywords_categories_reply_to_typed() {
    let ev: CalendarEvent = serde_json::from_str(
        r#"{
            "keywords": { "work": true },
            "categories": { "http://example.com/cat/meeting": true },
            "replyTo": { "imip": "mailto:organizer@example.com" }
        }"#,
    )
    .expect("CalendarEvent deserialize");

    assert_eq!(
        ev.keywords.as_ref().and_then(|m| m.get("work")),
        Some(&true)
    );
    assert_eq!(
        ev.categories
            .as_ref()
            .and_then(|m| m.get("http://example.com/cat/meeting")),
        Some(&true)
    );
    assert_eq!(
        ev.reply_to
            .as_ref()
            .and_then(|m| m.get("imip"))
            .map(String::as_str),
        Some("mailto:organizer@example.com")
    );

    let bad = serde_json::from_str::<CalendarEvent>(r#"{ "keywords": { "work": "yes" } }"#);
    assert!(bad.is_err(), "non-Boolean keyword value must be rejected");
}

/// CalendarEvent with recurrenceOverrides round-trips through the typed
/// `BTreeMap<String, PatchObject>` envelope.
/// Oracle: RFC 8984 §4.3.2 recurrenceOverrides description.
#[test]
fn calendar_event_recurrence_overrides_passthrough() {
    let json = &common::fixture("calendar_event_recurrence_overrides_passthrough.json");

    let ev: CalendarEvent = serde_json::from_str(json).expect("recurrence CalendarEvent");
    let overrides = ev
        .recurrence_overrides
        .as_ref()
        .expect("recurrenceOverrides");
    // Verify the key exists in the typed PatchObject envelope.
    let patch = overrides
        .get("2024-06-22T09:00:00")
        .expect("override key present");
    assert_eq!(
        patch.as_map().get("title"),
        Some(&serde_json::Value::String("Rescheduled meeting".to_owned()))
    );
}

/// Wire format for `recurrenceOverrides` is byte-identical between the old
/// `Option<Value>` shape and the new `Option<BTreeMap<String, PatchObject>>`
/// shape, because `PatchObject` is `#[serde(transparent)]`.
/// Oracle: hand-written JSON literal (independent of the type under test).
#[test]
fn calendar_event_recurrence_overrides_wire_format_is_object_map() {
    let json =
        &common::fixture("calendar_event_recurrence_overrides_wire_format_is_object_map.json");
    let ev: CalendarEvent = serde_json::from_str(json).expect("deserialize");
    let out: serde_json::Value = serde_json::to_value(&ev).expect("serialize");
    let expected: serde_json::Value = serde_json::from_str(json).expect("expected as Value");
    // Compare structurally — both serializations carry the same JSON object map.
    assert_eq!(
        out["recurrenceOverrides"], expected["recurrenceOverrides"],
        "wire format must be byte-identical for object-map input"
    );
}

/// RFC 8984 §4.7.2 — `CalendarEvent.timeZones` is `Map<TimeZoneId, TimeZone>`.
///
/// The field is modelled here as `Option<serde_json::Value>` for wire-shape
/// preservation. Each entry of the map can be typed-decoded into
/// `jmap_jscalendar_types::TimeZone` (re-exported from this crate). This
/// test verifies both wire round-trip and typed decode.
///
/// Oracle: hand-written JSON literal mirroring the RFC 8984 §4.7.2 wire shape.
#[test]
fn calendar_event_time_zones_value_and_typed_roundtrip() {
    use jmap_calendars_types::TimeZone;

    let json = &common::fixture("calendar_event_time_zones_value_and_typed_roundtrip.json");

    let ev: CalendarEvent = serde_json::from_str(json).expect("CalendarEvent must deserialize");
    let tz_field = ev.time_zones.as_ref().expect("timeZones must be Some");
    let tz_map = tz_field
        .as_object()
        .expect("timeZones must be a JSON object");
    let entry = tz_map
        .get("/example/custom/UTC+05:30:00")
        .expect("custom tz entry");

    // Typed decode: the per-zone Value parses into `TimeZone`.
    let tz: TimeZone = serde_json::from_value(entry.clone()).expect("typed TimeZone decode");
    assert_eq!(tz.at_type, "TimeZone");
    assert_eq!(tz.tz_id, "/example/custom/UTC+05:30:00");
    let standard = tz.standard.as_ref().expect("standard rule present");
    assert_eq!(standard.len(), 1);
    assert_eq!(standard[0].at_type, "TimeZoneRule");
    assert_eq!(standard[0].offset_from.as_ref(), "+0530");
    assert_eq!(standard[0].offset_to.as_ref(), "+0530");

    // Wire round-trip: serialize the CalendarEvent back and verify the
    // `timeZones` field is byte-identical to the input.
    let out: serde_json::Value = serde_json::to_value(&ev).expect("serialize");
    let expected: serde_json::Value = serde_json::from_str(json).expect("expected Value");
    assert_eq!(
        out["timeZones"], expected["timeZones"],
        "wire format must be byte-identical"
    );
}

/// CalendarEvent with localizations round-trips through the typed
/// `BTreeMap<String, PatchObject>` envelope.
/// Oracle: RFC 8984 §4.6 localizations description.
#[test]
fn calendar_event_localizations_passthrough() {
    let json = &common::fixture("calendar_event_localizations_passthrough.json");
    let ev: CalendarEvent = serde_json::from_str(json).expect("localizations CalendarEvent");
    let locs = ev.localizations.as_ref().expect("localizations");
    let fr = locs.get("fr").expect("fr override");
    assert_eq!(
        fr.as_map().get("title"),
        Some(&serde_json::Value::String("Déjeuner".to_owned()))
    );
    let es = locs.get("es").expect("es override");
    assert_eq!(
        es.as_map().get("title"),
        Some(&serde_json::Value::String("Almuerzo".to_owned()))
    );
    // Wire format byte-identical via PatchObject's #[serde(transparent)].
    let out: serde_json::Value = serde_json::to_value(&ev).expect("serialize");
    let expected: serde_json::Value = serde_json::from_str(json).expect("expected as Value");
    assert_eq!(out["localizations"], expected["localizations"]);
}

/// CalendarEvent round-trip preserves all present fields.
#[test]
fn calendar_event_roundtrip() {
    let json = &common::fixture("calendar_event_roundtrip.json");
    let original: CalendarEvent = serde_json::from_str(json).expect("first deserialize");
    let serialized = serde_json::to_string(&original).expect("serialize");
    let recovered: CalendarEvent = serde_json::from_str(&serialized).expect("second deserialize");
    assert_eq!(original, recovered);
}

// ─── CalendarEventFilterCondition ─────────────────────────────────────────────

/// An empty CalendarEventFilterCondition deserializes from `{}`.
#[test]
fn calendar_event_filter_condition_empty() {
    let fc: CalendarEventFilterCondition =
        serde_json::from_str("{}").expect("empty FilterCondition");
    assert!(fc.in_calendar.is_none());
    assert!(fc.after.is_none());
    assert!(fc.before.is_none());
    assert!(fc.text.is_none());
    assert!(fc.title.is_none());
    assert!(fc.description.is_none());
    assert!(fc.location.is_none());
    assert!(fc.owner.is_none());
    assert!(fc.participant.is_none());
    assert!(fc.uid.is_none());
}

/// CalendarEventFilterCondition serializes set fields to correct wire names.
/// Oracle: draft §5.11.1 filter field names.
#[test]
fn calendar_event_filter_condition_wire_names() {
    let json = &common::fixture("calendar_event_filter_condition_wire_names.json");
    let fc: CalendarEventFilterCondition = serde_json::from_str(json).expect("filter condition");

    assert_eq!(
        fc.in_calendar.as_ref().map(|id| id.as_ref()),
        Some("cal-001")
    );
    assert_eq!(
        fc.after.as_ref().map(AsRef::as_ref),
        Some("2024-01-01T00:00:00")
    );
    assert_eq!(
        fc.before.as_ref().map(AsRef::as_ref),
        Some("2024-12-31T23:59:59")
    );
    assert_eq!(fc.text.as_deref(), Some("meeting"));
    assert_eq!(fc.title.as_deref(), Some("team"));
    assert!(fc.description.is_none());
    assert!(fc.owner.is_none());

    // Verify round-trip serialization uses correct wire names.
    let out = serde_json::to_value(&fc).expect("serialize");
    assert_eq!(out["inCalendar"], "cal-001");
    assert_eq!(out["after"], "2024-01-01T00:00:00");
    assert_eq!(out["before"], "2024-12-31T23:59:59");
}

/// draft-ietf-jmap-calendars-33 §5.11.1 renamed the `attendee` condition:
/// "*participant*: String Looks for the text in the name or email fields of
/// a participant in the "participants" property of the event". The old
/// -26 name is now an unknown key, which the filter refuses.
#[test]
fn calendar_event_filter_condition_participant_replaces_attendee() {
    let fc: CalendarEventFilterCondition = serde_json::from_str(&common::fixture(
        "calendar_event_filter_condition_participant_replaces_attendee.json",
    ))
    .expect("participant condition");
    assert_eq!(fc.participant.as_deref(), Some("tom@foobar.example.com"));
    assert_eq!(
        serde_json::to_value(&fc).expect("serialize"),
        serde_json::json!({ "participant": "tom@foobar.example.com" })
    );
    assert!(
        serde_json::from_str::<CalendarEventFilterCondition>(&common::fixture(
            "calendar_event_filter_condition_participant_replaces_attendee_2.json"
        ))
        .is_err(),
        "the draft-26 `attendee` condition must no longer parse"
    );
}

// ─── CalendarEventNotification ────────────────────────────────────────────────

/// Deserialize a full CalendarEventNotification from hand-written JSON.
/// Oracle: draft-ietf-jmap-calendars-33 §7 field descriptions.
#[test]
fn notification_deserialize() {
    let json = &common::fixture("notification_deserialize.json");

    let n: CalendarEventNotification =
        serde_json::from_str(json).expect("CalendarEventNotification deserialize");

    assert_eq!(n.id.as_ref(), "notif-001");
    assert_eq!(n.created, "2024-06-15T10:05:00Z");
    assert_eq!(n.changed_by.name, "Alice Smith");
    assert_eq!(n.changed_by.email.as_deref(), Some("alice@example.com"));
    assert_eq!(
        n.changed_by.principal_id.as_ref().map(|id| id.as_ref()),
        Some("principal-alice")
    );
    assert_eq!(
        n.changed_by.calendar_address.as_deref(),
        Some("mailto:alice@example.com")
    );
    assert!(n.comment.is_none());
    assert_eq!(
        n.notification_type,
        jmap_calendars_types::NotificationType::Updated
    );
    assert_eq!(n.calendar_event_id.as_ref(), "event-001");
    assert_eq!(n.is_draft, Some(false));
    assert_eq!(n.event["title"], "Original Title");
    let patch = n.event_patch.as_ref().expect("eventPatch");
    assert_eq!(
        patch.as_map().get("title"),
        Some(&serde_json::Value::String("New Title".to_owned()))
    );
    // Wire format byte-identical via PatchObject's #[serde(transparent)].
    let out: serde_json::Value = serde_json::to_value(&n).expect("serialize notification");
    assert_eq!(out["eventPatch"]["title"], "New Title");
}

/// A `created` notification has no eventPatch.
#[test]
fn notification_created_no_patch() {
    let json = &common::fixture("notification_created_no_patch.json");

    let n: CalendarEventNotification = serde_json::from_str(json).expect("created notification");
    assert_eq!(
        n.notification_type,
        jmap_calendars_types::NotificationType::Created
    );
    assert!(n.event_patch.is_none());
    assert_eq!(n.is_draft, Some(true));
}

// ─── NotificationType ─────────────────────────────────────────────────────────

/// All three known notification types serialize to correct wire strings.
#[test]
fn notification_type_known_values() {
    use jmap_calendars_types::NotificationType;

    let created = serde_json::to_string(&NotificationType::Created).expect("created");
    let updated = serde_json::to_string(&NotificationType::Updated).expect("updated");
    let destroyed = serde_json::to_string(&NotificationType::Destroyed).expect("destroyed");

    assert_eq!(created, r#""created""#);
    assert_eq!(updated, r#""updated""#);
    assert_eq!(destroyed, r#""destroyed""#);
}

/// An unknown notification type maps to `Other(String)` and round-trips.
#[test]
fn notification_type_other_roundtrip() {
    use jmap_calendars_types::NotificationType;

    let other: NotificationType = serde_json::from_str(r#""rescheduled""#).expect("other type");
    match &other {
        NotificationType::Other(s) => assert_eq!(s, "rescheduled"),
        _ => panic!("expected Other variant"),
    }
    let back = serde_json::to_string(&other).expect("re-serialize");
    assert_eq!(back, r#""rescheduled""#);
}

/// The `type` filter condition carries the same value set as the
/// notification's `type` property.
///
/// Oracle: draft-ietf-jmap-calendars-33 §7.4.1 (line 2709):
/// "*type*: String / The "type" property must be the same to match the
/// condition." Expected values are hand-written.
#[test]
fn notification_filter_type_is_notification_type() {
    use jmap_calendars_types::{NotificationFilterCondition, NotificationType};

    let known: NotificationFilterCondition = serde_json::from_str(&common::fixture(
        "notification_filter_type_is_notification_type.json",
    ))
    .expect("known type");
    assert_eq!(known.notification_type, Some(NotificationType::Updated));

    let unknown: NotificationFilterCondition = serde_json::from_str(&common::fixture(
        "notification_filter_type_is_notification_type_2.json",
    ))
    .expect("unknown type");
    assert_eq!(
        serde_json::to_value(&unknown).expect("serialize"),
        serde_json::json!({"type": "rescheduled"})
    );
}

// ─── ParticipantIdentity ──────────────────────────────────────────────────────

/// ParticipantIdentity round-trip with isDefault true.
/// Oracle: draft §3 field descriptions.
#[test]
fn participant_identity_roundtrip() {
    let json = &common::fixture("participant_identity_roundtrip.json");

    let pi: ParticipantIdentity = serde_json::from_str(json).expect("ParticipantIdentity");

    let id_val = pi.id.as_ref().expect("id present");
    assert_eq!(id_val.as_ref(), "pi-001");
    assert_eq!(pi.name, "Joe Bloggs");
    assert_eq!(pi.calendar_address, "mailto:joe@example.com");
    assert!(pi.is_default);

    // Round-trip.
    let serialized = serde_json::to_string(&pi).expect("serialize");
    let recovered: ParticipantIdentity = serde_json::from_str(&serialized).expect("re-deserialize");
    assert_eq!(pi, recovered);
}

/// ParticipantIdentity wire field names match spec.
/// Oracle: draft §3 field list.
#[test]
fn participant_identity_wire_names() {
    let json = &common::fixture("participant_identity_wire_names.json");
    let pi: ParticipantIdentity = serde_json::from_str(json).expect("ParticipantIdentity");
    let out = serde_json::to_value(&pi).expect("serialize");
    assert_eq!(out["id"], "pi-002");
    assert_eq!(out["name"], "Jane Doe");
    assert_eq!(out["calendarAddress"], "mailto:jane@example.com");
    assert_eq!(out["isDefault"], false);
}

/// `ParticipantIdentity.id` is `Option<Id>` with `skip_serializing_if` so
/// a typed /set create payload (where the caller has no server-assigned
/// id yet) does NOT emit `id` on the wire.
///
/// Oracle: RFC 8620 §5.3 — "The id property MUST NOT be set in the
/// create object." This test asserts the wire shape directly: a
/// ParticipantIdentity deserialized from JSON without `id` must serialize
/// back without `id`. Independent of the code under test — JSON is
/// hand-written.
#[test]
fn participant_identity_id_absent_when_none() {
    // JSON without an `id` field (matches /set create payload shape).
    let json = &common::fixture("participant_identity_id_absent_when_none.json");
    let pi: ParticipantIdentity =
        serde_json::from_str(json).expect("ParticipantIdentity must deserialize without id");
    assert!(pi.id.is_none(), "id must be None when absent from input");

    let out = serde_json::to_value(&pi).expect("serialize");
    let obj = out.as_object().expect("object");
    assert!(
        !obj.contains_key("id"),
        "id must be absent from wire when None (RFC 8620 §5.3 create payload contract): {out}"
    );
}

// ─── Capability ───────────────────────────────────────────────────────────────

/// CalendarsCapability serializes to an empty object.
#[test]
fn calendars_capability_empty_object() {
    let cap = CalendarsCapability::default();
    let json = serde_json::to_string(&cap).expect("serialize");
    assert_eq!(json, "{}");
}

/// CalendarsAccountCapability round-trip with all required fields.
/// Oracle: draft §1.5.1 field descriptions.
#[test]
fn calendars_account_capability_roundtrip() {
    let json = &common::fixture("calendars_account_capability_roundtrip.json");

    let cap: CalendarsAccountCapability =
        serde_json::from_str(json).expect("CalendarsAccountCapability");

    assert_eq!(cap.max_calendars_per_event, Some(5));
    assert_eq!(cap.min_date_time, "1970-01-01T00:00:00Z");
    assert_eq!(cap.max_date_time, "2099-12-31T23:59:59Z");
    assert_eq!(cap.max_expanded_query_duration.as_ref(), "P1Y");
    assert!(cap.max_participants_per_event.is_none());
    assert!(cap.may_create_calendar);

    // Round-trip.
    let s = serde_json::to_string(&cap).expect("serialize");
    let r: CalendarsAccountCapability = serde_json::from_str(&s).expect("re-deserialize");
    assert_eq!(cap, r);
}

/// `maxAvailabilityDuration` is a Duration on the wire and round-trips
/// unchanged. Oracle: draft-ietf-jmap-calendars-33 §1.5.2
/// "maxAvailabilityDuration: Duration"; hand-written fixture.
#[test]
fn principals_availability_account_capability_roundtrip() {
    let json = &common::fixture("principals_availability_account_capability_roundtrip.json");
    let cap: PrincipalsAvailabilityAccountCapability =
        serde_json::from_str(json).expect("must deserialize");
    assert_eq!(cap.max_availability_duration.as_ref(), "P56D");
    assert_eq!(serde_json::to_string(&cap).expect("serialize"), *json);
}

/// JMAP_CALENDARS_URI constant matches spec §1.5.1.
#[test]
fn calendars_uri_constant() {
    assert_eq!(JMAP_CALENDARS_URI, "urn:ietf:params:jmap:calendars");
}

// ─── AlertTrigger ─────────────────────────────────────────────────────────────

/// OffsetTrigger serializes and deserializes correctly.
/// Oracle: RFC 8984 §4.5.2.
#[test]
fn alert_offset_trigger_roundtrip() {
    let json = &common::fixture("alert_offset_trigger_roundtrip.json");

    let trigger: AlertTrigger = serde_json::from_str(json).expect("OffsetTrigger");
    match &trigger {
        AlertTrigger::OffsetTrigger(t) => {
            assert_eq!(t.at_type, "OffsetTrigger");
            assert_eq!(t.offset.as_ref(), "-PT15M");
            assert_eq!(t.relative_to.as_deref(), Some("start"));
        }
        _ => panic!("expected OffsetTrigger variant"),
    }

    let back = serde_json::to_string(&trigger).expect("serialize");
    let recovered: AlertTrigger = serde_json::from_str(&back).expect("re-deserialize");
    assert_eq!(trigger, recovered);
}

/// AbsoluteTrigger serializes and deserializes correctly.
/// Oracle: RFC 8984 §4.5.2.
#[test]
fn alert_absolute_trigger_roundtrip() {
    let json = &common::fixture("alert_absolute_trigger_roundtrip.json");

    let trigger: AlertTrigger = serde_json::from_str(json).expect("AbsoluteTrigger");
    match &trigger {
        AlertTrigger::AbsoluteTrigger(t) => {
            assert_eq!(t.at_type, "AbsoluteTrigger");
            assert_eq!(t.when, "2024-06-15T08:45:00Z");
        }
        _ => panic!("expected AbsoluteTrigger variant"),
    }

    let back = serde_json::to_string(&trigger).expect("serialize");
    let recovered: AlertTrigger = serde_json::from_str(&back).expect("re-deserialize");
    assert_eq!(trigger, recovered);
}

/// An unknown trigger type is preserved via the Unknown variant.
/// Oracle: RFC 8984 §4.5.2 "Implementations MUST preserve unknown trigger types."
#[test]
fn alert_unknown_trigger_roundtrip() {
    let json = &common::fixture("alert_unknown_trigger_roundtrip.json");

    let trigger: AlertTrigger = serde_json::from_str(json).expect("unknown trigger");
    match &trigger {
        AlertTrigger::Unknown(v) => {
            assert_eq!(v["@type"], "CustomTrigger");
            assert_eq!(v["customField"], "customValue");
        }
        _ => panic!("expected Unknown variant"),
    }

    let back = serde_json::to_string(&trigger).expect("re-serialize");
    let recovered: AlertTrigger = serde_json::from_str(&back).expect("re-deserialize");
    match &recovered {
        AlertTrigger::Unknown(v) => assert_eq!(v["@type"], "CustomTrigger"),
        _ => panic!("round-trip should remain Unknown"),
    }
}

/// Full Alert with OffsetTrigger deserializes correctly.
#[test]
fn alert_with_offset_trigger() {
    let json = &common::fixture("alert_with_offset_trigger.json");

    let alert: Alert = serde_json::from_str(json).expect("Alert");
    assert_eq!(alert.at_type, "Alert");
    assert_eq!(alert.action.as_deref(), Some("display"));
    assert!(alert.acknowledged.is_none());
    match &alert.trigger {
        AlertTrigger::OffsetTrigger(t) => assert_eq!(t.offset.as_ref(), "-PT15M"),
        _ => panic!("expected OffsetTrigger"),
    }
}

// ─── Person ───────────────────────────────────────────────────────────────────

/// Person wire field names match draft §7.
#[test]
fn person_wire_names() {
    let json = &common::fixture("person_wire_names.json");
    let p: Person = serde_json::from_str(json).expect("Person");
    let out = serde_json::to_value(&p).expect("serialize");
    assert_eq!(out["name"], "Charlie Brown");
    assert_eq!(out["email"], "charlie@example.com");
    assert_eq!(out["principalId"], "princ-007");
    assert_eq!(out["calendarAddress"], "mailto:charlie@example.com");
}

/// Person with null fields serializes correctly (nullable, not absent).
#[test]
fn person_null_fields() {
    let json = &common::fixture("person_null_fields.json");
    let p: Person = serde_json::from_str(json).expect("Person");
    assert_eq!(p.name, "Eve");
    assert!(p.email.is_none());
    assert!(p.principal_id.is_none());
    assert!(p.calendar_address.is_none());
}

// ─── BusyPeriod (draft-ietf-jmap-calendars-33 §2.2) ─────────────────────────

/// Deserialize a BusyPeriod with all fields set.
///
/// Oracle: field types from draft-ietf-jmap-calendars-33 §2.2 field descriptions.
/// busyStatus values: "confirmed", "tentative", "unavailable".
#[test]
fn busy_period_full_deserialize() {
    let json = &common::fixture("busy_period_full_deserialize.json");

    let bp: BusyPeriod = serde_json::from_str(json).expect("BusyPeriod deserialize");
    assert_eq!(bp.utc_start, "2024-06-15T09:00:00Z");
    assert_eq!(bp.utc_end, "2024-06-15T10:00:00Z");
    assert_eq!(bp.busy_status, BusyStatus::Confirmed);
    assert!(bp.event.is_some(), "event must be deserialized");
    assert_eq!(bp.event.as_ref().unwrap()["title"], "Team meeting");
    assert!(bp.account_id.is_some(), "accountId must be present");
    assert_eq!(bp.account_id.as_ref().unwrap().as_ref(), "acc-42");
}

/// Deserialize a BusyPeriod where event and accountId are absent (no detail access).
///
/// Oracle: §2.2 — when showDetails=false or user lacks mayReadItems, event and
/// accountId are null (absent) in the response.
#[test]
fn busy_period_no_detail_access() {
    let json = &common::fixture("busy_period_no_detail_access.json");

    let bp: BusyPeriod = serde_json::from_str(json).expect("BusyPeriod minimal deserialize");
    assert_eq!(bp.utc_start, "2024-06-15T14:00:00Z");
    assert_eq!(bp.utc_end, "2024-06-15T15:30:00Z");
    assert_eq!(bp.busy_status, BusyStatus::Unavailable);
    assert!(bp.event.is_none());
    assert!(bp.account_id.is_none());

    // Optional fields absent from wire when None.
    let v = serde_json::to_value(&bp).expect("serialize");
    let obj = v.as_object().expect("object");
    assert!(!obj.contains_key("event"), "event must be absent when None");
    assert!(
        !obj.contains_key("accountId"),
        "accountId must be absent when None"
    );
}

/// BusyPeriod round-trip: serialize then re-deserialize, verify equality.
#[test]
fn busy_period_roundtrip() {
    let json = &common::fixture("busy_period_roundtrip.json");

    let original: BusyPeriod = serde_json::from_str(json).expect("first deserialize");
    let serialized = serde_json::to_string(&original).expect("serialize");
    let back: BusyPeriod = serde_json::from_str(&serialized).expect("re-deserialize");

    assert_eq!(original.utc_start, back.utc_start);
    assert_eq!(original.utc_end, back.utc_end);
    assert_eq!(original.busy_status, back.busy_status);
    assert_eq!(original.account_id, back.account_id);
    assert_eq!(original.event, back.event);
}

/// Wire key names for BusyPeriod match spec camelCase names.
#[test]
fn busy_period_wire_names() {
    let json = &common::fixture("busy_period_wire_names.json");
    let bp: BusyPeriod = serde_json::from_str(json).expect("deserialize");
    let v = serde_json::to_value(&bp).expect("serialize");
    let obj = v.as_object().expect("object");

    assert!(obj.contains_key("utcStart"), "wire key must be utcStart");
    assert!(obj.contains_key("utcEnd"), "wire key must be utcEnd");
    assert!(
        obj.contains_key("busyStatus"),
        "wire key must be busyStatus"
    );
    assert!(obj.contains_key("accountId"), "wire key must be accountId");
}

/// An absent `busyStatus` takes the draft default.
///
/// Oracle: draft-ietf-jmap-calendars-33 §2.2, `busyStatus`:
/// "String (default: "unavailable")".
#[test]
fn busy_period_absent_busy_status_defaults_to_unavailable() {
    let json = &common::fixture("busy_period_absent_busy_status_defaults_to_unavailable.json");
    let bp: BusyPeriod = serde_json::from_str(json).expect("deserialize");
    assert_eq!(bp.busy_status, BusyStatus::Unavailable);
}

/// `busyStatus` is a closed set: a value outside it is rejected.
///
/// Oracle: draft-ietf-jmap-calendars-33 §2.2, `busyStatus`: "This MUST be
/// one of" "confirmed", "tentative", "unavailable". `"busy"` is not.
#[test]
fn busy_period_rejects_unknown_busy_status() {
    let json = &common::fixture("busy_period_rejects_unknown_busy_status.json");
    assert!(serde_json::from_str::<BusyPeriod>(json).is_err());
}

/// Each `busyStatus` variant serializes to the draft's wire string.
///
/// Oracle: draft-ietf-jmap-calendars-33 §2.2 value list.
#[test]
fn busy_status_wire_strings() {
    for (v, wire) in [
        (BusyStatus::Confirmed, "confirmed"),
        (BusyStatus::Tentative, "tentative"),
        (BusyStatus::Unavailable, "unavailable"),
    ] {
        assert_eq!(serde_json::to_value(v).unwrap(), serde_json::json!(wire));
    }
}

// ─── PrincipalCalendarsCapability (calendars-33 §2.1) ────────────────────────

/// Deserialize PrincipalCalendarsCapability with accountId populated.
///
/// Oracle: field names from draft-ietf-jmap-calendars-33 §2.1 field descriptions.
#[test]
fn principal_calendars_capability_with_account_id() {
    let json = &common::fixture("principal_calendars_capability_with_account_id.json");

    let cap: PrincipalCalendarsCapability =
        serde_json::from_str(json).expect("PrincipalCalendarsCapability deserialize");
    assert_eq!(
        cap.account_id.as_ref().map(|id| id.as_ref()),
        Some("acc-alice")
    );
    assert!(cap.may_get_availability);
    assert!(cap.may_share_with);
    assert_eq!(
        cap.calendar_address.as_deref(),
        Some("mailto:alice@example.com")
    );
}

/// draft-ietf-jmap-calendars-33 §2.1: "*calendarAddress*: String|null If
/// this Principal may be added as a participant to an event, this is the
/// calendarAddress to use to receive iTIP scheduling messages; otherwise,
/// this is null." Required-nullable: `null` parses and re-serializes as
/// `null`, not as an absent key.
#[test]
fn principal_calendars_capability_calendar_address_null() {
    let wire = serde_json::json!({
        "accountId": null,
        "mayGetAvailability": true,
        "mayShareWith": false,
        "calendarAddress": null
    });
    let cap: PrincipalCalendarsCapability =
        serde_json::from_value(wire.clone()).expect("null calendarAddress must parse");
    assert!(cap.calendar_address.is_none());
    assert_eq!(serde_json::to_value(&cap).expect("serialize"), wire);
}

/// Deserialize PrincipalCalendarsCapability with accountId null.
///
/// Oracle: §2.1 — accountId is `Id|null`; null when the principal has no
/// accessible calendar account.
#[test]
fn principal_calendars_capability_account_id_null() {
    let json = &common::fixture("principal_calendars_capability_account_id_null.json");

    let cap: PrincipalCalendarsCapability =
        serde_json::from_str(json).expect("deserialize with null accountId");
    assert!(cap.account_id.is_none(), "accountId must be None for null");
    assert!(!cap.may_get_availability);
    assert!(!cap.may_share_with);
}

/// accountId serializes as null (not absent) when None.
///
/// Oracle: §2.1 types accountId as `Id|null` — required-nullable, must always
/// appear on the wire.
#[test]
fn principal_calendars_capability_account_id_null_serializes() {
    let json = &common::fixture("principal_calendars_capability_account_id_null_serializes.json");
    let cap: PrincipalCalendarsCapability = serde_json::from_str(json).expect("deserialize");
    let v = serde_json::to_value(&cap).expect("serialize");
    let obj = v.as_object().expect("object");

    assert!(
        obj.contains_key("accountId"),
        "accountId must be present in wire JSON (required-nullable)"
    );
    assert!(
        obj["accountId"].is_null(),
        "accountId must serialize as null"
    );
}

/// PrincipalCalendarsCapability round-trip.
#[test]
fn principal_calendars_capability_roundtrip() {
    let json = &common::fixture("principal_calendars_capability_roundtrip.json");

    let original: PrincipalCalendarsCapability =
        serde_json::from_str(json).expect("first deserialize");
    let serialized = serde_json::to_string(&original).expect("serialize");
    let back: PrincipalCalendarsCapability =
        serde_json::from_str(&serialized).expect("re-deserialize");

    assert_eq!(original.account_id, back.account_id);
    assert_eq!(original.may_get_availability, back.may_get_availability);
    assert_eq!(original.may_share_with, back.may_share_with);
    assert_eq!(original.calendar_address, back.calendar_address);
}

// ─── Participant — scheduleSequence / scheduleUpdated (RFC 8984 §5.2) ────────

/// Verify Participant carries scheduleSequence and scheduleUpdated.
///
/// Oracle: RFC 8984 §5.2.1 / §5.2.2 — both fields have Context: Participant.
/// JSON constructed from the spec field descriptions: scheduleSequence is a
/// UnsignedInt, scheduleUpdated is a UTCDateTime string.
#[test]
fn participant_schedule_fields_roundtrip() {
    let json = &common::fixture("participant_schedule_fields_roundtrip.json");

    let p: Participant = serde_json::from_str(json).expect("Participant deserialize");
    assert_eq!(p.schedule_sequence, Some(3));
    // schedule_updated is Option<UTCDate>; UTCDate does not impl Deref<Target=str>
    // so we cannot use Option::as_deref. Take an AsRef<str> view via map instead.
    assert_eq!(
        p.schedule_updated.as_ref().map(AsRef::as_ref),
        Some("2024-06-15T10:30:00Z")
    );

    // Round-trip: serialize then re-deserialize.
    let serialized = serde_json::to_string(&p).expect("serialize");
    let back: Participant = serde_json::from_str(&serialized).expect("re-deserialize");
    assert_eq!(back.schedule_sequence, Some(3));
    assert_eq!(
        back.schedule_updated.as_ref().map(AsRef::as_ref),
        Some("2024-06-15T10:30:00Z")
    );

    // Wire names: camelCase.
    let v: serde_json::Value = serde_json::from_str(&serialized).expect("parse");
    assert_eq!(v["scheduleSequence"], serde_json::json!(3_u64));
    assert_eq!(
        v["scheduleUpdated"],
        serde_json::json!("2024-06-15T10:30:00Z")
    );
}

/// Participant with no schedule fields omits them from wire (optional).
///
/// Oracle: RFC 8984 §5.2 — these fields are optional per-participant iTIP
/// tracking fields; absent when not involved in scheduling.
#[test]
fn participant_schedule_fields_absent_when_none() {
    let json = &common::fixture("participant_schedule_fields_absent_when_none.json");

    let p: Participant = serde_json::from_str(json).expect("Participant deserialize");
    assert_eq!(p.schedule_sequence, None);
    assert_eq!(p.schedule_updated, None);
    assert!(
        p.schedule_status.is_none(),
        "scheduleStatus must be None when absent"
    );

    let serialized = serde_json::to_string(&p).expect("serialize");
    let v: serde_json::Value = serde_json::from_str(&serialized).expect("parse");
    let obj = v.as_object().expect("object");
    assert!(
        !obj.contains_key("scheduleSequence"),
        "scheduleSequence must be absent when None"
    );
    assert!(
        !obj.contains_key("scheduleUpdated"),
        "scheduleUpdated must be absent when None"
    );
    assert!(
        !obj.contains_key("scheduleStatus"),
        "scheduleStatus must be absent when None"
    );
}

// ─── Id usage in tests ────────────────────────────────────────────────────────

/// Verify Id::from works correctly (used implicitly via serde deserialize above).
#[test]
fn id_from_str_works() {
    let id = Id::from("test-id-123");
    assert_eq!(id.as_ref(), "test-id-123");
}

// ---------------------------------------------------------------------------
// Link
// ---------------------------------------------------------------------------

#[test]
fn link_with_href_roundtrip() {
    // Oracle: RFC 8984 §1.4.11 field definitions.
    let json = &common::fixture("link_with_href_roundtrip.json");
    let link: Link =
        serde_json::from_str(json).expect("link_with_href_roundtrip: must deserialize");
    assert_eq!(link.at_type, "Link");
    assert_eq!(link.href.as_deref(), Some("https://example.com/file.pdf"));
    assert_eq!(link.content_type.as_deref(), Some("application/pdf"));
    assert_eq!(link.size, Some(4096));
    assert_eq!(link.rel.as_deref(), Some("enclosure"));
    assert_eq!(link.display.as_deref(), Some("report.pdf"));
    assert!(
        link.blob_id.is_none(),
        "blob_id must be absent when not in JSON"
    );

    // Verify blobId absent from serialized output.
    let out = serde_json::to_string(&link).expect("link_with_href_roundtrip: must serialize");
    assert!(
        !out.contains("blobId"),
        "blobId must not appear when None: {out}"
    );
}

#[test]
fn link_with_blob_id_roundtrip() {
    // Oracle: draft-ietf-jmap-calendars-33 §5.3 — blobId may be set instead of href.
    let json = &common::fixture("link_with_blob_id_roundtrip.json");
    let link: Link =
        serde_json::from_str(json).expect("link_with_blob_id_roundtrip: must deserialize");
    assert_eq!(link.blob_id, Some(Id::from("blob-abc123")));
    assert!(link.href.is_none(), "href must be absent when not in JSON");

    // Verify blobId is present in serialized output but href is not.
    let out = serde_json::to_value(&link).expect("link_with_blob_id_roundtrip: must serialize");
    assert_eq!(
        out["blobId"], "blob-abc123",
        "blobId must serialize to wire name"
    );
    assert!(
        out.get("href").is_none() || out["href"].is_null(),
        "href must be absent when None"
    );
}

#[test]
fn link_blob_id_absent_when_none() {
    // Oracle: skip_serializing_if = Option::is_none — optional field absent when not set.
    // Construct via deserialization (Link is #[non_exhaustive]).
    let json = &common::fixture("link_blob_id_absent_when_none.json");
    let link: Link =
        serde_json::from_str(json).expect("link_blob_id_absent_when_none: must deserialize");
    assert!(
        link.blob_id.is_none(),
        "blob_id must be None when absent from JSON"
    );
    let out = serde_json::to_string(&link).expect("link_blob_id_absent_when_none: must serialize");
    assert!(
        !out.contains("blobId"),
        "blobId must not appear when None: {out}"
    );
}

#[test]
fn link_wire_names() {
    // Oracle: #[serde(rename_all = "camelCase")] on Link struct.
    // All camelCase wire keys must be present; snake_case must not appear.
    let json = &common::fixture("link_wire_names.json");
    let link: Link = serde_json::from_str(json).expect("link_wire_names: must deserialize");
    let out = serde_json::to_value(&link).expect("link_wire_names: must serialize");
    // camelCase keys must be present
    assert!(
        out.get("blobId").is_some(),
        "blobId must be camelCase wire key"
    );
    assert!(
        out.get("contentType").is_some(),
        "contentType must be camelCase wire key"
    );
    assert!(out.get("rel").is_some(), "rel must be present");
    assert!(out.get("display").is_some(), "display must be present");
    // snake_case must NOT appear
    assert!(
        out.get("blob_id").is_none(),
        "snake_case blob_id must not appear on wire"
    );
    assert!(
        out.get("content_type").is_none(),
        "snake_case content_type must not appear on wire"
    );
}

// ---------------------------------------------------------------------------
// CalendarAlert
// ---------------------------------------------------------------------------

#[test]
fn calendar_alert_with_recurrence_id_roundtrip() {
    // Oracle: draft-ietf-jmap-calendars-33 §6.4 CalendarAlert push-notification object.
    // A recurring-event alert: recurrenceId is present and non-null.
    let json = &common::fixture("calendar_alert_with_recurrence_id_roundtrip.json");
    let alert: CalendarAlert = serde_json::from_str(json)
        .expect("calendar_alert_with_recurrence_id_roundtrip: must deserialize");
    assert_eq!(
        alert.at_type, "CalendarAlert",
        "@type field must be 'CalendarAlert'"
    );
    assert_eq!(alert.account_id.as_ref(), "acc-1");
    assert_eq!(alert.calendar_event_id.as_ref(), "ev-42");
    assert_eq!(alert.uid, "abc-uid-123");
    assert_eq!(
        alert.recurrence_id.as_deref(),
        Some("2024-06-15T10:00:00"),
        "recurrenceId must be present for recurring events"
    );
    assert_eq!(alert.alert_id, "alert-1");

    // Round-trip: serialize and re-deserialize.
    let serialized = serde_json::to_string(&alert)
        .expect("calendar_alert_with_recurrence_id_roundtrip: must serialize");
    let recovered: CalendarAlert = serde_json::from_str(&serialized)
        .expect("calendar_alert_with_recurrence_id_roundtrip: round-trip must deserialize");
    assert_eq!(alert, recovered);
}

#[test]
fn calendar_alert_recurrence_id_null_for_non_recurring() {
    // Oracle: draft-ietf-jmap-calendars-33 §6.4 — recurrenceId is null for non-recurring events.
    // It MUST serialize as null (not be omitted) so receivers can distinguish
    // recurring from non-recurring events.
    let json = &common::fixture("calendar_alert_recurrence_id_null_for_non_recurring.json");
    let alert: CalendarAlert = serde_json::from_str(json)
        .expect("calendar_alert_recurrence_id_null_for_non_recurring: must deserialize");
    assert!(
        alert.recurrence_id.is_none(),
        "recurrenceId must be None when null"
    );

    // Verify it serializes back as null (not omitted).
    let out = serde_json::to_value(&alert)
        .expect("calendar_alert_recurrence_id_null_for_non_recurring: must serialize");
    assert!(
        out.get("recurrenceId").is_some(),
        "recurrenceId key must be present in serialized output (not omitted)"
    );
    assert!(
        out["recurrenceId"].is_null(),
        "recurrenceId must serialize as null for non-recurring events"
    );
}

#[test]
fn calendar_alert_wire_names() {
    // Oracle: #[serde(rename_all = "camelCase")] + #[serde(rename = "@type")] on CalendarAlert.
    // All camelCase wire keys must be present; snake_case must not appear.
    let json = &common::fixture("calendar_alert_wire_names.json");
    let alert: CalendarAlert =
        serde_json::from_str(json).expect("calendar_alert_wire_names: must deserialize");
    let out = serde_json::to_value(&alert).expect("calendar_alert_wire_names: must serialize");
    // Required camelCase wire keys
    assert!(out.get("@type").is_some(), "@type must be present");
    assert!(
        out.get("accountId").is_some(),
        "accountId must be camelCase"
    );
    assert!(
        out.get("calendarEventId").is_some(),
        "calendarEventId must be camelCase"
    );
    assert!(out.get("alertId").is_some(), "alertId must be camelCase");
    // snake_case must NOT appear on wire
    assert!(
        out.get("account_id").is_none(),
        "account_id must not appear on wire"
    );
    assert!(
        out.get("calendar_event_id").is_none(),
        "calendar_event_id must not appear on wire"
    );
    assert!(
        out.get("alert_id").is_none(),
        "alert_id must not appear on wire"
    );
    assert!(
        out.get("at_type").is_none(),
        "at_type must not appear on wire (must be @type)"
    );
}

// ---------------------------------------------------------------------------
// VirtualLocation — mandatory uri field (RFC 8984 §4.2.6)
// ---------------------------------------------------------------------------

#[test]
fn virtual_location_uri_required() {
    // Oracle: RFC 8984 §4.2.6 — uri is a mandatory String field.
    // A well-formed VirtualLocation must include uri; deserialization must succeed
    // and preserve the uri value.
    let json = &common::fixture("virtual_location_uri_required.json");
    let vl: VirtualLocation =
        serde_json::from_str(json).expect("virtual_location_uri_required: must deserialize");
    assert_eq!(
        vl.uri, "https://meet.example.com/room-42",
        "uri must round-trip correctly"
    );
    assert_eq!(vl.name.as_deref(), Some("Team Call"));
}

#[test]
fn virtual_location_uri_missing_fails_deserialization() {
    // Oracle: RFC 8984 §4.2.6 — uri is mandatory; a VirtualLocation with no uri
    // must fail deserialization (the crate uses String, not Option<String>).
    let json = &common::fixture("virtual_location_uri_missing_fails_deserialization.json");
    let result: Result<VirtualLocation, _> = serde_json::from_str(json);
    assert!(
        result.is_err(),
        "VirtualLocation without uri must fail deserialization (uri is mandatory per RFC 8984 §4.2.6)"
    );
}

#[test]
fn virtual_location_wire_names() {
    // Oracle: #[serde(rename_all = "camelCase")] on VirtualLocation.
    let json = &common::fixture("virtual_location_wire_names.json");
    let vl: VirtualLocation =
        serde_json::from_str(json).expect("virtual_location_wire_names: must deserialize");
    let out = serde_json::to_value(&vl).expect("virtual_location_wire_names: must serialize");
    assert!(out.get("uri").is_some(), "uri must be present on wire");
    assert!(out.get("@type").is_some(), "@type must be present on wire");
    // snake_case must not appear
    assert!(
        out.get("at_type").is_none(),
        "at_type must not appear on wire"
    );
}

// ---------------------------------------------------------------------------
// Link.cid and Link.title fields (RFC 8984 §1.4.11)
// ---------------------------------------------------------------------------

#[test]
fn link_cid_roundtrip() {
    // Oracle: RFC 8984 §1.4.11 — cid is an optional field for inline image
    // references in text/html event descriptions via cid: URLs.
    let json = &common::fixture("link_cid_roundtrip.json");
    let link: Link = serde_json::from_str(json).expect("link_cid_roundtrip: must deserialize");
    assert_eq!(
        link.cid.as_deref(),
        Some("logo@example.com"),
        "cid must round-trip correctly"
    );
    // Verify wire name is "cid" (camelCase would be identical here).
    let out = serde_json::to_value(&link).expect("link_cid_roundtrip: must serialize");
    assert_eq!(
        out["cid"], "logo@example.com",
        "cid wire name must be 'cid'"
    );
}

#[test]
fn link_cid_absent_when_none() {
    // Oracle: skip_serializing_if = Option::is_none — cid must be absent when not set.
    let json = &common::fixture("link_blob_id_absent_when_none.json");
    let link: Link =
        serde_json::from_str(json).expect("link_cid_absent_when_none: must deserialize");
    assert!(link.cid.is_none(), "cid must be None when absent from JSON");
    let out = serde_json::to_string(&link).expect("link_cid_absent_when_none: must serialize");
    assert!(
        !out.contains("\"cid\""),
        "cid must not appear in output when None: {out}"
    );
}

#[test]
fn link_title_roundtrip() {
    // Oracle: RFC 8984 §1.4.11 — title is an optional human-readable description
    // of the linked resource, distinct from display (file name).
    let json = &common::fixture("link_title_roundtrip.json");
    let link: Link = serde_json::from_str(json).expect("link_title_roundtrip: must deserialize");
    assert_eq!(
        link.title.as_deref(),
        Some("Annual Report 2024"),
        "title must round-trip correctly"
    );
    let out = serde_json::to_value(&link).expect("link_title_roundtrip: must serialize");
    assert_eq!(
        out["title"], "Annual Report 2024",
        "title wire name must be 'title'"
    );
}

#[test]
fn link_title_absent_when_none() {
    // Oracle: skip_serializing_if = Option::is_none — title must be absent when not set.
    let json = &common::fixture("link_title_absent_when_none.json");
    let link: Link =
        serde_json::from_str(json).expect("link_title_absent_when_none: must deserialize");
    assert!(
        link.title.is_none(),
        "title must be None when absent from JSON"
    );
    let out = serde_json::to_string(&link).expect("link_title_absent_when_none: must serialize");
    assert!(
        !out.contains("\"title\""),
        "title must not appear in output when None: {out}"
    );
}

// ---------------------------------------------------------------------------
// Participant.scheduleStatus (RFC 8984 §4.4.6)
// ---------------------------------------------------------------------------

#[test]
fn participant_schedule_status_roundtrip() {
    // Oracle: RFC 8984 §4.4.6 — scheduleStatus is String[] (optional),
    // contains iTIP status codes (e.g. "1.0", "2.0").
    let json = &common::fixture("participant_schedule_status_roundtrip.json");
    let p: Participant = serde_json::from_str(json)
        .expect("participant_schedule_status_roundtrip: must deserialize");
    let status = p
        .schedule_status
        .as_ref()
        .expect("scheduleStatus must be Some");
    assert_eq!(status.len(), 2, "must have 2 status codes");
    assert_eq!(status[0], "1.0");
    assert_eq!(status[1], "2.0");

    let out =
        serde_json::to_value(&p).expect("participant_schedule_status_roundtrip: must serialize");
    assert_eq!(
        out["scheduleStatus"][0], "1.0",
        "scheduleStatus[0] must be '1.0'"
    );
    assert_eq!(
        out["scheduleStatus"][1], "2.0",
        "scheduleStatus[1] must be '2.0'"
    );
}

// ---------------------------------------------------------------------------
// CalendarEvent.iCalendar (calendars-33 §5.7)
// ---------------------------------------------------------------------------

/// draft-ietf-jmap-calendars-33 §5.7 names the property "iCalendar" (see
/// [I-D.ietf-calext-jscalendar-icalendar]), whose value is an
/// ICalComponent object. Fixture: Figure 9 of
/// draft-ietf-calext-jscalendar-icalendar-28.
#[test]
fn calendar_event_icalendar_roundtrip() {
    let ical = serde_json::json!({
        "@type": "ICalComponent",
        "name": "participant",
        "properties": [
            ["uid", {}, "text", "47AD2E1C-49D4-45DF-BD83-8398ACC7D8E2"]
        ]
    });
    let wire = serde_json::json!({ "id": "ev1", "iCalendar": ical });
    let event: CalendarEvent = serde_json::from_value(wire.clone()).expect("must deserialize");
    assert_eq!(event.icalendar.as_ref(), Some(&ical));
    assert!(
        event.extra.is_empty(),
        "iCalendar must land in the typed field"
    );
    let out = serde_json::to_value(&event).expect("must serialize");
    assert_eq!(out["iCalendar"], ical);
}

/// The draft-26 `iCalComponent` key is not the draft-33 property: a peer
/// still sending it must not be read as `iCalendar`. It stays in the
/// extras catch-all and round-trips under its own spelling.
#[test]
fn calendar_event_draft26_icalcomponent_lands_in_extras() {
    let payload = &common::fixture("calendar_event_draft26_icalcomponent_lands_in_extras.json");
    let ev: CalendarEvent = serde_json::from_str(payload).expect("must still deserialize");
    assert!(ev.icalendar.is_none());
    assert_eq!(
        ev.extra.get("iCalComponent").and_then(|v| v.as_str()),
        Some("QkVHSU46VkVWRU5U")
    );
    let reser = serde_json::to_value(&ev).expect("re-serialize must succeed");
    assert_eq!(reser["iCalComponent"], "QkVHSU46VkVWRU5U");
    assert!(reser.get("iCalendar").is_none());
}

/// draft-ietf-jmap-calendars-33 §5.7: "The "iCalendar" property is also
/// only returned if explicitly requested", so an unset value is absent
/// from the wire.
#[test]
fn calendar_event_icalendar_absent_when_none() {
    let event: CalendarEvent = serde_json::from_str(&common::fixture(
        "calendar_event_icalendar_absent_when_none.json",
    ))
    .expect("must deserialize");
    assert!(event.icalendar.is_none());
    let out = serde_json::to_value(&event).expect("must serialize");
    assert!(out.get("iCalendar").is_none(), "{out}");
}

/// draft-ietf-calext-jscalendarbis-22 §3.1.2: "version: String ... The
/// JSCalendar version of this object." Figure 10 of
/// draft-ietf-jmap-calendars-33 returns `"version": "2.0"` in `created`.
#[test]
fn calendar_event_version_is_typed() {
    let wire = serde_json::json!({ "id": "E-5d5776f6", "@type": "Event", "version": "2.0" });
    let event: CalendarEvent = serde_json::from_value(wire).expect("must deserialize");
    assert_eq!(event.version.as_deref(), Some("2.0"));
    assert!(event.extra.is_empty());
    assert_eq!(
        serde_json::to_value(&event).expect("serialize")["version"],
        "2.0"
    );
}

// ── Extras-preservation policy tests (JMAP-lbdy.4) ──────────────────────────
//
// One round-trip preservation test per migrated type. Each asserts that
// an unknown vendor / site / private-extension field survives
// deserialize/serialize unchanged. Per workspace AGENTS.md
// "Extras-preservation policy for vendor/site fields".

/// `BusyPeriod.extra` captures vendor fields and preserves them.
#[test]
fn busy_period_preserves_vendor_extras() {
    let raw = serde_json::json!({
        "utcStart": "2024-06-01T09:00:00Z",
        "utcEnd": "2024-06-01T10:00:00Z",
        "acmeCorpFreeBusyTag": "client-meeting"
    });
    let b: BusyPeriod = serde_json::from_value(raw).unwrap();
    assert_eq!(
        b.extra.get("acmeCorpFreeBusyTag").and_then(|v| v.as_str()),
        Some("client-meeting")
    );
    let back = serde_json::to_value(&b).unwrap();
    assert_eq!(back["acmeCorpFreeBusyTag"], "client-meeting");
}

/// `CalendarRights.extra` captures vendor fields and preserves them.
#[test]
fn calendar_rights_preserves_vendor_extras() {
    let raw = serde_json::json!({
        "mayReadFreeBusy": true,
        "mayReadItems": true,
        "mayWriteAll": false,
        "mayWriteOwn": true,
        "mayUpdatePrivate": false,
        "mayRSVP": true,
        "mayShare": false,
        "mayDelete": false,
        "acmeCorpMayPublish": false
    });
    let r: CalendarRights = serde_json::from_value(raw).unwrap();
    assert_eq!(
        r.extra.get("acmeCorpMayPublish").and_then(|v| v.as_bool()),
        Some(false)
    );
    let back = serde_json::to_value(&r).unwrap();
    assert_eq!(back["acmeCorpMayPublish"], false);
}

/// `Calendar.extra` captures vendor fields and preserves them.
#[test]
fn calendar_preserves_vendor_extras() {
    let raw = serde_json::json!({
        "id": "c1",
        "name": "Work",
        "description": null,
        "color": null,
        "sortOrder": 0,
        "isSubscribed": true,
        "isVisible": true,
        "isDefault": false,
        "includeInAvailability": "all",
        "defaultAlertsWithTime": null,
        "defaultAlertsWithoutTime": null,
        "timeZone": null,
        "shareWith": null,
        "myRights": {
            "mayReadFreeBusy": true, "mayReadItems": true, "mayWriteAll": true,
            "mayWriteOwn": true, "mayUpdatePrivate": true, "mayRSVP": true,
            "mayShare": true, "mayDelete": true
        },
        "acmeCorpDepartment": "engineering"
    });
    let c: Calendar = serde_json::from_value(raw).unwrap();
    assert_eq!(
        c.extra.get("acmeCorpDepartment").and_then(|v| v.as_str()),
        Some("engineering")
    );
    let back = serde_json::to_value(&c).unwrap();
    assert_eq!(back["acmeCorpDepartment"], "engineering");
}

/// `CalendarEvent.extra` captures vendor fields and preserves them.
#[test]
fn calendar_event_preserves_vendor_extras() {
    let raw = serde_json::json!({
        "@type": "Event",
        "uid": "event-1",
        "title": "Meeting",
        "start": "2024-06-01T10:00:00",
        "duration": "PT1H",
        "acmeCorpMeetingNotes": "https://wiki/n/42"
    });
    let e: CalendarEvent = serde_json::from_value(raw).unwrap();
    assert_eq!(
        e.extra.get("acmeCorpMeetingNotes").and_then(|v| v.as_str()),
        Some("https://wiki/n/42")
    );
    let back = serde_json::to_value(&e).unwrap();
    assert_eq!(back["acmeCorpMeetingNotes"], "https://wiki/n/42");
}

/// `Person.extra` captures vendor fields and preserves them.
#[test]
fn person_preserves_vendor_extras() {
    let raw = serde_json::json!({
        "name": "Alice",
        "email": "alice@example.com",
        "principalId": null,
        "calendarAddress": null,
        "acmeCorpEmployeeId": "emp-42"
    });
    let p: Person = serde_json::from_value(raw).unwrap();
    assert_eq!(
        p.extra.get("acmeCorpEmployeeId").and_then(|v| v.as_str()),
        Some("emp-42")
    );
    let back = serde_json::to_value(&p).unwrap();
    assert_eq!(back["acmeCorpEmployeeId"], "emp-42");
}

/// `CalendarEventNotification.extra` captures vendor fields and preserves them.
#[test]
fn calendar_event_notification_preserves_vendor_extras() {
    let raw = serde_json::json!({
        "id": "n1",
        "created": "2024-06-01T00:00:00Z",
        "changedBy": {
            "name": "Alice",
            "email": null,
            "principalId": null,
            "calendarAddress": null
        },
        "type": "created",
        "calendarEventId": "e1",
        "event": {},
        "acmeCorpNotificationChannel": "in-app"
    });
    let n: CalendarEventNotification = serde_json::from_value(raw).unwrap();
    assert_eq!(
        n.extra
            .get("acmeCorpNotificationChannel")
            .and_then(|v| v.as_str()),
        Some("in-app")
    );
    let back = serde_json::to_value(&n).unwrap();
    assert_eq!(back["acmeCorpNotificationChannel"], "in-app");
}

/// `CalendarAlert.extra` captures vendor fields and preserves them.
#[test]
fn calendar_alert_preserves_vendor_extras() {
    let raw = serde_json::json!({
        "@type": "CalendarAlert",
        "accountId": "a1",
        "calendarEventId": "e1",
        "uid": "uid-1",
        "recurrenceId": null,
        "alertId": "alrt-1",
        "acmeCorpPushPriority": "high"
    });
    let a: CalendarAlert = serde_json::from_value(raw).unwrap();
    assert_eq!(
        a.extra.get("acmeCorpPushPriority").and_then(|v| v.as_str()),
        Some("high")
    );
    let back = serde_json::to_value(&a).unwrap();
    assert_eq!(back["acmeCorpPushPriority"], "high");
}

/// `ParticipantIdentity.extra` captures vendor fields and preserves them.
#[test]
fn participant_identity_preserves_vendor_extras() {
    let raw = serde_json::json!({
        "id": "pi1",
        "name": "Alice",
        "calendarAddress": "mailto:alice@example.com",
        "isDefault": true,
        "acmeCorpDeliveryHint": "external"
    });
    let pi: ParticipantIdentity = serde_json::from_value(raw).unwrap();
    assert_eq!(
        pi.extra
            .get("acmeCorpDeliveryHint")
            .and_then(|v| v.as_str()),
        Some("external")
    );
    let back = serde_json::to_value(&pi).unwrap();
    assert_eq!(back["acmeCorpDeliveryHint"], "external");
}

// ── @type-default regression tests (bd:JMAP-ky8g.10) ──────────────────────
//
// CalendarAlert declares `@type` as a bare `String` with a serde-default
// function returning the literal `"CalendarAlert"`. Deserialize MUST
// succeed when `@type` is absent (spec-violating producer input or
// partial fixture), populating the field with the literal. Serialize
// MUST always emit the field. Mirrors the same regression contract on
// the 12 JSCalendar sub-types in `jmap-jscalendar-types` (same bead)
// and Person/CheckItem/Checklist/Comment in `jmap-tasks-types`
// (bd:JMAP-ky8g.1).
//
// Independent oracle: hand-written JSON shaped against
// draft-ietf-jmap-calendars-33 §6.4 example text with `@type` omitted.

/// `CalendarAlert` deserialize succeeds when `@type` is absent and
/// defaults to `"CalendarAlert"`. Re-serialize emits the field with
/// the default value.
#[test]
fn calendar_alert_at_type_defaults_when_absent() {
    let raw = serde_json::json!({
        "accountId": "acc-1",
        "calendarEventId": "ev-42",
        "uid": "abc-uid-123",
        "recurrenceId": null,
        "alertId": "alert-1"
    });
    let alert: CalendarAlert = serde_json::from_value(raw).unwrap();
    assert_eq!(alert.at_type, "CalendarAlert");
    let back = serde_json::to_value(&alert).unwrap();
    assert_eq!(back["@type"], "CalendarAlert");
}

/// Explicit non-default `@type` values round-trip verbatim — the
/// serde-default does NOT overwrite an explicit wire value. Locks in
/// the contract that a vendor shipping a non-conformant string is
/// preserved end-to-end rather than silently normalised.
#[test]
fn calendar_alert_at_type_explicit_value_round_trips_verbatim() {
    let raw = serde_json::json!({
        "@type": "AcmeCorpAlert",
        "accountId": "acc-1",
        "calendarEventId": "ev-42",
        "uid": "abc-uid-123",
        "recurrenceId": null,
        "alertId": "alert-1"
    });
    let alert: CalendarAlert = serde_json::from_value(raw).unwrap();
    assert_eq!(alert.at_type, "AcmeCorpAlert");
    let back = serde_json::to_value(&alert).unwrap();
    assert_eq!(back["@type"], "AcmeCorpAlert");
}

/// Oracle: workspace map-ordering policy (bd:JMAP-pdux) — wire-format maps
/// serialize in sorted key order. Input keys are written out of order;
/// expected bytes are hand-written.
#[test]
fn calendar_event_maps_serialize_in_sorted_key_order() {
    let raw = &common::fixture("calendar_event_maps_serialize_in_sorted_key_order.json");
    let ev: CalendarEvent = serde_json::from_str(raw).expect("deserialize");
    let j = serde_json::to_string(&ev).expect("serialize");
    assert!(
        j.contains(r#""calendarIds":{"cal-1":true,"cal-2":true}"#),
        "calendarIds keys must be sorted: {j}"
    );
    assert!(
        j.contains(r#""localizations":{"es":{"title":"Almuerzo"},"fr":{"title":"Dejeuner"}}"#),
        "localizations keys must be sorted: {j}"
    );
}

/// draft-ietf-jmap-metadata-04 §4.1: the rights object of every data type with
/// `myRights` "gains the following property: *maySetMetadata*: Boolean", and
/// the right is only present when the metadata capability lists the type, so
/// it is optional on the wire. Oracle: hand-written JSON with the spec's wire name.
#[test]
fn calendar_rights_may_set_metadata_typed_and_optional() {
    let with: serde_json::Value = serde_json::json!({ "mayReadFreeBusy": true, "mayReadItems": true, "mayWriteAll": false, "mayWriteOwn": true, "mayUpdatePrivate": true, "mayRSVP": true, "mayShare": false, "mayDelete": false, "maySetMetadata": true });
    let r: CalendarRights = serde_json::from_value(with.clone()).unwrap();
    assert_eq!(r.may_set_metadata, Some(true));
    assert!(!r.extra.contains_key("maySetMetadata"));
    assert_eq!(serde_json::to_value(&r).unwrap(), with);

    let denied: serde_json::Value = serde_json::json!({ "mayReadFreeBusy": true, "mayReadItems": true, "mayWriteAll": false, "mayWriteOwn": true, "mayUpdatePrivate": true, "mayRSVP": true, "mayShare": false, "mayDelete": false, "maySetMetadata": false });
    let r: CalendarRights = serde_json::from_value(denied.clone()).unwrap();
    assert_eq!(r.may_set_metadata, Some(false));
    assert_eq!(serde_json::to_value(&r).unwrap(), denied);

    let without: serde_json::Value = serde_json::json!({ "mayReadFreeBusy": true, "mayReadItems": true, "mayWriteAll": false, "mayWriteOwn": true, "mayUpdatePrivate": true, "mayRSVP": true, "mayShare": false, "mayDelete": false });
    let r: CalendarRights = serde_json::from_value(without.clone()).unwrap();
    assert_eq!(r.may_set_metadata, None);
    assert_eq!(serde_json::to_value(&r).unwrap(), without);
}

// ─── CalendarEventComparator ─────────────────────────────────────────────────

/// draft-ietf-jmap-calendars-33 §5.11.2: "The following properties MUST be
/// supported for sorting: id, uid, start" and "SHOULD be supported for
/// sorting: created, updated". A name not listed (including the draft-26
/// `recurrenceId`) survives as `Other` and re-encodes to the same JSON
/// (bd JMAP-wf92.11).
#[test]
fn calendar_event_comparator_sort_properties() {
    use jmap_calendars_types::{CalendarEventComparator, CalendarEventComparatorProperty as P};
    for (wire, want) in [
        ("id", P::Id),
        ("uid", P::Uid),
        ("start", P::Start),
        ("created", P::Created),
        ("updated", P::Updated),
    ] {
        let c: CalendarEventComparator =
            serde_json::from_value(serde_json::json!({ "property": wire })).unwrap();
        assert_eq!(c.property, want);
        // RFC 8620 §5.5 isAscending "(default: true)".
        assert!(c.is_ascending);
    }
    for name in ["x-vendor-rank", "recurrenceId"] {
        let wire = serde_json::json!({ "property": name, "isAscending": false });
        let c: CalendarEventComparator = serde_json::from_value(wire.clone()).unwrap();
        assert_eq!(c.property, P::Other(name.to_owned()));
        assert_eq!(serde_json::to_value(&c).unwrap(), wire);
    }
}