io-msgraph 0.7.0

Microsoft Graph API client library for Rust
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
//! # vCard projection
//!
//! Projects a Microsoft Graph contact onto a vCard 4.0 document
//! ([`MsgraphContact::to_vcard`]), and a vCard back onto a contact
//! ([`MsgraphContact::from_vcard`]).
//!
//! Graph exposes no vCard representation of a contact, its endpoints only
//! speaking the JSON contact resource, so a consumer needing one (an
//! address book client, a sync engine) synthesizes the document of record
//! here. Only fields with a well-defined vCard slot are projected:
//!
//! - Graph-only fields (`fileAs`, `officeLocation`, `assistantName`,
//!   `manager`) are minted as read-only `X-MSGRAPH-*` properties and
//!   consumed on the way back, the server value staying authoritative;
//! - every other vCard line rides a single-value extended property, the
//!   stash ([`MSGRAPH_CONTACT_STASH_ID`]), and is spliced back verbatim on
//!   read. Graph omits extended properties unless expanded, so a read that
//!   should carry the stash passes [`MSGRAPH_CONTACT_STASH_EXPAND`].
//!
//! [`MsgraphContact::from_vcard`] is the full-state projection: every
//! managed field is Set when the vCard carries it and Null when it does
//! not, while Graph-only fields stay Unset and survive updates untouched.
//! [`MsgraphContact::create_from_vcard`] shapes a create body and
//! [`MsgraphContact::update_from_vcard`] an update body, both stripping the
//! gratuitous nulls the Outlook backend rejects with HTTP 500.

use core::{fmt, str::FromStr};

use alloc::{
    borrow::Cow,
    boxed::Box,
    format,
    string::{String, ToString},
    vec,
    vec::Vec,
};

use crate::v1::{
    field::MsgraphField,
    rest::users::{
        contacts::{MsgraphContact, MsgraphPhysicalAddress, MsgraphSingleValueExtendedProperty},
        messages::MsgraphEmailAddress,
    },
};
use serde_json::{from_value, to_value};
use vcard::{
    param::VcardParam,
    prop::{
        VcardProp, VcardPropKind, VcardPropName, adr::ADR, categories::CATEGORIES, email::EMAIL,
        r#fn::FN, impp::IMPP, n::N, nickname::NICKNAME, note::NOTE, org::ORG, related::RELATED,
        role::ROLE, tel::TEL, title::TITLE, url::URL,
    },
    tree::{cst::VcardCst, error::VcardParseError, line::VcardLine, prop::lens::VcardPropLens},
    value::{
        VcardValue,
        adr::VcardAdr,
        datetime::VcardDateAndOrTime,
        n::VcardN,
        org::VcardOrg,
        text::{VcardText, VcardTextList},
        uri::VcardUri,
    },
};

/// Extended-property id under which the vCard remainder is stashed on the
/// Graph contact, a fixed app GUID plus a name (the String MAPI form).
///
/// It rides inline in create and update bodies. The name predates this
/// crate (Cardamum wrote it first) and is kept so contacts stashed then
/// still read back.
pub const MSGRAPH_CONTACT_STASH_ID: &str =
    "String {c8e5e5cf-3f6c-4f0a-9d4e-52f1e7b2a9d3} Name cardamum-vcard";

/// The `$expand` clause reading the stash back with a contact, which Graph
/// omits otherwise.
pub const MSGRAPH_CONTACT_STASH_EXPAND: &str = "singleValueExtendedProperties($filter=id eq \
     'String {c8e5e5cf-3f6c-4f0a-9d4e-52f1e7b2a9d3} Name cardamum-vcard')";

/// Longest raw property line stashed server-side.
///
/// A longer line, a base64 PHOTO blob essentially, stays in the local
/// document of record rather than risking the whole write against an
/// undocumented size limit.
const MAX_STASH_LINE: usize = 8 * 1024;

/// Property names minted by [`to_vcard`] from the Graph-only contact
/// fields.
///
/// [`to_contact`] consumes them, the server value being authoritative: the
/// fields stay Unset, out of every body.
const MINTED_PROPS: &[&str] = &[
    "X-MSGRAPH-FILE-AS",
    "X-MSGRAPH-OFFICE-LOCATION",
    "X-MSGRAPH-ASSISTANT",
    "X-MSGRAPH-MANAGER",
];

impl MsgraphContact {
    /// Projects an io-msgraph contact onto a fresh vCard 4.0 document.
    ///
    /// The UID is the one the stash carries ([`stashed_uid`]), else one minted
    /// from the Graph id for a contact Graph created itself. The phone and
    /// address slots become typed TEL and ADR properties (business work, home
    /// home, mobile cell), and spouse and children become RELATED names, their
    /// types being standard in vCard 4.0.
    ///
    /// [`stashed_uid`]: Self::stashed_uid
    pub fn to_vcard(&self) -> String {
        let contact = self;
        let mut card = VcardCst::v4();

        let id = contact.id.trim();
        if contact.stashed_uid().is_none() && !id.is_empty() {
            card.push(VcardProp::text(VcardPropKind::Uid, vec![], id));
        }

        card.push(VcardProp::text(
            VcardPropKind::Fn,
            vec![],
            display_name(contact),
        ));

        // NOTE: the Graph title is the honorific (Dr., Mrs.), hence the N
        // prefix slot; the job title maps to TITLE below.
        let n = VcardN {
            family: component(&contact.surname),
            given: component(&contact.given_name),
            additional: component(&contact.middle_name),
            prefixes: component(&contact.title),
            suffixes: Vec::new(),
        };

        let empty = n.family.is_empty()
            && n.given.is_empty()
            && n.additional.is_empty()
            && n.prefixes.is_empty();
        if !empty {
            card.push(VcardProp {
                group: None,
                name: VcardPropName::Kind(VcardPropKind::N),
                params: vec![],
                value: VcardValue::N(n),
            });
        }

        if let Some(nick) = opt(&contact.nick_name) {
            card.push(VcardProp {
                group: None,
                name: VcardPropName::Kind(VcardPropKind::Nickname),
                params: vec![],
                value: VcardValue::TextList(VcardTextList(vec![Cow::Owned(nick.to_string())])),
            });
        }

        for email in list(&contact.email_addresses) {
            if let Some(address) = email.address.as_deref() {
                let address = address.trim();
                if !address.is_empty() {
                    card.push(VcardProp::text(VcardPropKind::Email, vec![], address));
                }
            }
        }

        for im in list(&contact.im_addresses) {
            let im = im.trim();
            if !im.is_empty() {
                card.push(VcardProp {
                    group: None,
                    name: VcardPropName::Kind(VcardPropKind::Impp),
                    params: vec![],
                    value: VcardValue::Uri(VcardUri(Cow::Owned(im.to_string()))),
                });
            }
        }

        for phone in list(&contact.business_phones) {
            let phone = phone.trim();
            if !phone.is_empty() {
                card.push(VcardProp::text(
                    VcardPropKind::Tel,
                    vec![type_param("work")],
                    phone,
                ));
            }
        }
        for phone in list(&contact.home_phones) {
            let phone = phone.trim();
            if !phone.is_empty() {
                card.push(VcardProp::text(
                    VcardPropKind::Tel,
                    vec![type_param("home")],
                    phone,
                ));
            }
        }
        if let Some(phone) = opt(&contact.mobile_phone) {
            card.push(VcardProp::text(
                VcardPropKind::Tel,
                vec![type_param("cell")],
                phone,
            ));
        }

        if let Some(prop) = adr_prop(contact.home_address.as_option(), Some("home")) {
            card.push(prop);
        }
        if let Some(prop) = adr_prop(contact.business_address.as_option(), Some("work")) {
            card.push(prop);
        }
        if let Some(prop) = adr_prop(contact.other_address.as_option(), None) {
            card.push(prop);
        }

        let company = opt(&contact.company_name);
        let department = opt(&contact.department);
        if company.is_some() || department.is_some() {
            let mut components: Vec<Cow<'static, str>> =
                vec![Cow::Owned(company.unwrap_or_default().to_string())];
            if let Some(department) = department {
                components.push(Cow::Owned(department.to_string()));
            }
            card.push(VcardProp {
                group: None,
                name: VcardPropName::Kind(VcardPropKind::Org),
                params: vec![],
                value: VcardValue::Org(VcardOrg(components)),
            });
        }

        if let Some(title) = opt(&contact.job_title) {
            card.push(VcardProp::text(VcardPropKind::Title, vec![], title));
        }
        if let Some(role) = opt(&contact.profession) {
            card.push(VcardProp::text(VcardPropKind::Role, vec![], role));
        }
        if let Some(page) = opt(&contact.business_home_page) {
            card.push(VcardProp {
                group: None,
                name: VcardPropName::Kind(VcardPropKind::Url),
                params: vec![],
                value: VcardValue::Uri(VcardUri(Cow::Owned(page.to_string()))),
            });
        }

        // NOTE: Graph serves the birthday as an ISO 8601 date-time
        // (1983-04-01T00:00:00Z); only its date part has a vCard slot.
        if let Some(birthday) = opt(&contact.birthday) {
            let date = birthday.split('T').next().unwrap_or(birthday);
            if let Some(date) = VcardDateAndOrTime::from(date).full_date() {
                card.push(VcardProp {
                    group: None,
                    name: VcardPropName::Kind(VcardPropKind::Bday),
                    params: vec![],
                    value: VcardValue::DateAndOrTime(VcardDateAndOrTime(Cow::Owned(date))),
                });
            }
        }

        if let Some(notes) = opt(&contact.personal_notes) {
            card.push(VcardProp::text(VcardPropKind::Note, vec![], notes));
        }

        let categories: Vec<Cow<'static, str>> = list(&contact.categories)
            .iter()
            .map(|category| category.trim())
            .filter(|category| !category.is_empty())
            .map(|category| Cow::Owned(category.to_string()))
            .collect();
        if !categories.is_empty() {
            card.push(VcardProp {
                group: None,
                name: VcardPropName::Kind(VcardPropKind::Categories),
                params: vec![],
                value: VcardValue::TextList(VcardTextList(categories)),
            });
        }

        if let Some(spouse) = opt(&contact.spouse_name) {
            card.push(related_prop("spouse", spouse));
        }
        for child in list(&contact.children) {
            let child = child.trim();
            if !child.is_empty() {
                card.push(related_prop("child", child));
            }
        }

        // NOTE: Graph-only fields ride the vCard as read-only X-MSGRAPH-*
        // vendor properties, and the stashed remainder restores verbatim.
        let minted = [
            ("X-MSGRAPH-FILE-AS", opt(&contact.file_as)),
            ("X-MSGRAPH-OFFICE-LOCATION", opt(&contact.office_location)),
            ("X-MSGRAPH-ASSISTANT", opt(&contact.assistant_name)),
            ("X-MSGRAPH-MANAGER", opt(&contact.manager)),
        ];
        for (name, value) in minted {
            if let Some(value) = value {
                card.push(VcardProp::text(name, vec![], value));
            }
        }

        let stash = stash_lines(contact);
        for line in &stash {
            // NOTE: a line that no longer tokenises restores nothing rather
            // than corrupting the card.
            let _ = card.push_raw(line);
        }

        String::from_utf8_lossy(&card.to_bytes()).into_owned()
    }

    /// Projects a vCard onto an io-msgraph contact, in full state: each managed
    /// field is Set from the vCard or Null when absent (collections clear
    /// through an empty Set), while unmanaged Graph fields stay Unset.
    ///
    /// Graph keeps fixed slots even behind its collection-typed properties, so
    /// the first matching vCard property fills a slot and the extras fall to
    /// the stash rather than into another slot. Graph has no UID slot, so the
    /// UID rides the stash too, which is what keeps a contact's identity
    /// across a sync with another source.
    pub fn from_vcard(vcard: &str) -> Result<Self, MsgraphContactVcardError> {
        let card = VcardCst::parse(vcard).map_err(MsgraphContactVcardError::Parse)?;
        let version = card.version();

        let mut display_name = None;
        let mut surname = None;
        let mut given_name = None;
        let mut middle_name = None;
        let mut title = None;
        let mut nick_name = None;
        let mut emails = Vec::new();
        let mut ims = Vec::new();
        let mut business_phones = Vec::new();
        let mut home_phones = Vec::new();
        let mut mobile_phone = None;
        let mut home_address = None;
        let mut business_address = None;
        let mut other_address = None;
        let mut company_name = None;
        let mut department = None;
        let mut job_title = None;
        let mut profession = None;
        let mut business_home_page = None;
        let mut birthday = None;
        let mut spouse_name = None;
        let mut children = Vec::new();
        let mut categories = Vec::new();
        let mut notes = Vec::new();
        let mut stash = Vec::new();
        let mut name_seen = false;

        // NOTE: Outlook stores fixed slots behind the Graph collections:
        // three email addresses, three IM addresses, two business and two
        // home phones (Graph rejects bodies overflowing a slot set). The
        // first properties win, and the extras land in the stash remainder
        // like every other line that does not project, so they survive on
        // the server and restore on read (cairn/spec/projection.md).
        for line in &card.props {
            let consumed = match VcardPropKind::from_str(line.name.get()) {
                // NOTE: the VERSION line is structural and the minted
                // X-MSGRAPH-* properties are read-only projections;
                // neither belongs to the remainder.
                Err(_) => {
                    let raw_name = line.name.get();
                    raw_name.eq_ignore_ascii_case("VERSION")
                        || MINTED_PROPS
                            .iter()
                            .any(|prop| raw_name.eq_ignore_ascii_case(prop))
                }
                Ok(VcardPropKind::Fn) => {
                    let name = FN::decode(line, version);
                    set_first(&mut display_name, &name.0)
                }
                Ok(VcardPropKind::N) => {
                    if !name_seen {
                        name_seen = true;
                        let n = N::decode(line, version);
                        set_first(&mut surname, n.family.join(" "));
                        set_first(&mut given_name, n.given.join(" "));
                        set_first(&mut middle_name, n.additional.join(" "));
                        set_first(&mut title, n.prefixes.join(" "));
                        true
                    } else {
                        false
                    }
                }
                Ok(VcardPropKind::Nickname) => {
                    let all = NICKNAME::decode(line, version);
                    match all.0.first() {
                        Some(nick) => set_first(&mut nick_name, nick),
                        None => false,
                    }
                }
                Ok(VcardPropKind::Email) => {
                    let email = EMAIL::decode(line, version);
                    let address = email.0.trim();
                    if emails.len() < 3 && !address.is_empty() {
                        emails.push(MsgraphEmailAddress {
                            name: None,
                            address: Some(address.to_string()),
                        });
                        true
                    } else {
                        false
                    }
                }
                Ok(VcardPropKind::Impp) => {
                    let impp = IMPP::decode(line, version);
                    let address = impp.0.trim();
                    if ims.len() < 3 && !address.is_empty() {
                        ims.push(address.to_string());
                        true
                    } else {
                        false
                    }
                }
                Ok(VcardPropKind::Tel) => {
                    let tel = TEL::decode(line, version);
                    let number = tel.0.trim();
                    if number.is_empty() {
                        false
                    } else {
                        let types = type_values(line);
                        if types.iter().any(|t| t == "cell") {
                            // NOTE: one mobile slot; further cell TELs are
                            // stashed rather than misfiled as business
                            // phones.
                            if mobile_phone.is_none() {
                                mobile_phone = Some(number.to_string());
                                true
                            } else {
                                false
                            }
                        } else if types.iter().any(|t| t == "home") {
                            if home_phones.len() < 2 {
                                home_phones.push(number.to_string());
                                true
                            } else {
                                false
                            }
                        } else if business_phones.len() < 2 {
                            business_phones.push(number.to_string());
                            true
                        } else {
                            false
                        }
                    }
                }
                Ok(VcardPropKind::Adr) => {
                    let adr = ADR::decode(line, version);

                    // NOTE: Graph's street is one multiline field; the po
                    // box and extended components fold into it so nothing
                    // is lost.
                    let street: Vec<&str> = adr
                        .po_box
                        .iter()
                        .chain(&adr.extended)
                        .chain(&adr.street)
                        .map(|component| component.as_ref().trim())
                        .filter(|component| !component.is_empty())
                        .collect();

                    let address = MsgraphPhysicalAddress {
                        street: (!street.is_empty()).then(|| street.join("\n")),
                        city: joined(&adr.locality),
                        state: joined(&adr.region),
                        country_or_region: joined(&adr.country),
                        postal_code: joined(&adr.postal_code),
                    };

                    let empty = address.street.is_none()
                        && address.city.is_none()
                        && address.state.is_none()
                        && address.country_or_region.is_none()
                        && address.postal_code.is_none();
                    if empty {
                        false
                    } else {
                        let types = type_values(line);
                        let slot = if types.iter().any(|t| t == "home") {
                            &mut home_address
                        } else if types.iter().any(|t| t == "work") {
                            &mut business_address
                        } else {
                            &mut other_address
                        };
                        if slot.is_none() {
                            *slot = Some(address);
                            true
                        } else {
                            false
                        }
                    }
                }
                Ok(VcardPropKind::Org) => {
                    if company_name.is_none() && department.is_none() {
                        let org = ORG::decode(line, version);
                        let mut components = org.0.iter().map(|component| component.as_ref());
                        let company = components.next().unwrap_or_default();
                        let rest = components.collect::<Vec<_>>().join(" ");
                        set_first(&mut company_name, company);
                        set_first(&mut department, rest);
                        true
                    } else {
                        false
                    }
                }
                Ok(VcardPropKind::Title) => {
                    let value = TITLE::decode(line, version);
                    set_first(&mut job_title, &value.0)
                }
                Ok(VcardPropKind::Role) => {
                    let role = ROLE::decode(line, version);
                    set_first(&mut profession, &role.0)
                }
                Ok(VcardPropKind::Url) => {
                    let url = URL::decode(line, version);
                    set_first(&mut business_home_page, &url.0)
                }
                Ok(VcardPropKind::Bday) => {
                    // NOTE: a partial (year-less) birthday has no Graph
                    // date it round-trips through; it lands in the stash.
                    if birthday.is_none()
                        && let Some(date) =
                            VcardDateAndOrTime::from(line.raw_value_str()).full_date()
                    {
                        birthday = Some(format!("{date}T00:00:00Z"));
                        true
                    } else {
                        false
                    }
                }
                Ok(VcardPropKind::Note) => {
                    let note = NOTE::decode(line, version);
                    let note = note.0.trim();
                    if !note.is_empty() {
                        notes.push(note.to_string());
                        true
                    } else {
                        false
                    }
                }
                Ok(VcardPropKind::Categories) => {
                    let all = CATEGORIES::decode(line, version);
                    let mut pushed = false;
                    for category in &all.0 {
                        let category = category.trim();
                        if !category.is_empty() {
                            categories.push(category.to_string());
                            pushed = true;
                        }
                    }
                    pushed
                }
                Ok(VcardPropKind::Related) => {
                    // NOTE: only free-form spouse and child names
                    // (VALUE=text) project; other types and URI RELATED
                    // lines land in the stash.
                    let text = line.params.iter().any(|param| {
                        param.name.get().eq_ignore_ascii_case("VALUE")
                            && param
                                .values
                                .iter()
                                .any(|value| value.get().eq_ignore_ascii_case("text"))
                    });
                    if text {
                        let related = RELATED::decode(line, version);
                        let types = type_values(line);
                        if types.iter().any(|t| t == "spouse") {
                            set_first(&mut spouse_name, &related.0)
                        } else if types.iter().any(|t| t == "child") {
                            let child = related.0.trim();
                            if !child.is_empty() {
                                children.push(child.to_string());
                                true
                            } else {
                                false
                            }
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                }
                Ok(_) => false,
            };

            if !consumed {
                let raw = line.to_string();
                let raw = raw.trim_end().to_string();
                if raw.len() <= MAX_STASH_LINE {
                    stash.push(raw);
                }
            }
        }

        Ok(MsgraphContact {
            display_name: MsgraphField::set_or_null(display_name),
            given_name: MsgraphField::set_or_null(given_name),
            middle_name: MsgraphField::set_or_null(middle_name),
            surname: MsgraphField::set_or_null(surname),
            nick_name: MsgraphField::set_or_null(nick_name),
            title: MsgraphField::set_or_null(title),
            email_addresses: MsgraphField::Set(emails),
            im_addresses: MsgraphField::Set(ims),
            business_phones: MsgraphField::Set(business_phones),
            home_phones: MsgraphField::Set(home_phones),
            mobile_phone: MsgraphField::set_or_null(mobile_phone),
            home_address: MsgraphField::set_or_null(home_address),
            business_address: MsgraphField::set_or_null(business_address),
            other_address: MsgraphField::set_or_null(other_address),
            job_title: MsgraphField::set_or_null(job_title),
            company_name: MsgraphField::set_or_null(company_name),
            department: MsgraphField::set_or_null(department),
            profession: MsgraphField::set_or_null(profession),
            business_home_page: MsgraphField::set_or_null(business_home_page),
            birthday: MsgraphField::set_or_null(birthday),
            spouse_name: MsgraphField::set_or_null(spouse_name),
            children: MsgraphField::Set(children),
            personal_notes: MsgraphField::set_or_null(
                (!notes.is_empty()).then(|| notes.join("\n")),
            ),
            categories: MsgraphField::Set(categories),
            // NOTE: the stash entry is always Set (empty value when the
            // card has no remainder) so the delta projection can tell a
            // cleared stash from an unchanged one.
            single_value_extended_properties: MsgraphField::Set(vec![
                MsgraphSingleValueExtendedProperty {
                    id: MSGRAPH_CONTACT_STASH_ID.to_string(),
                    value: stash.join("\n"),
                },
            ]),
            ..Default::default()
        })
    }

    /// Projects a vCard onto an update body: the fields differing from the base
    /// vCard (the state last synced with the server), the unchanged ones
    /// turning Unset and staying out of the PATCH.
    ///
    /// The Outlook backend rejects the gratuitous nulls of a full-state body
    /// with an internal server error (HTTP 500), so a Null survives only when
    /// the edit cleared a field the base carried (collections clear through an
    /// explicit empty Set instead).
    pub fn update_from_vcard(
        vcard: &str,
        base_vcard: &str,
    ) -> Result<Self, MsgraphContactVcardError> {
        let mut contact = Self::from_vcard(vcard)?;
        let base = Self::from_vcard(base_vcard)?;

        macro_rules! unset_unchanged {
        ($($field:ident),* $(,)?) => {$(
            if contact.$field == base.$field {
                contact.$field = MsgraphField::Unset;
            }
        )*};
    }

        unset_unchanged!(
            display_name,
            given_name,
            middle_name,
            surname,
            nick_name,
            title,
            email_addresses,
            im_addresses,
            business_phones,
            home_phones,
            mobile_phone,
            home_address,
            business_address,
            other_address,
            job_title,
            company_name,
            department,
            profession,
            business_home_page,
            birthday,
            spouse_name,
            children,
            personal_notes,
            categories,
            single_value_extended_properties,
        );

        Ok(contact)
    }

    /// Projects a vCard onto a create body: the full-state projection minus the
    /// explicit nulls and empty collections.
    ///
    /// They are no-ops on a fresh resource, and the Outlook backend rejects null
    /// complex properties on POST with an internal server error (HTTP 500).
    pub fn create_from_vcard(vcard: &str) -> Result<Self, MsgraphContactVcardError> {
        let mut contact = Self::from_vcard(vcard)?;

        // NOTE: an empty stash entry is a no-op on a fresh resource.
        if stash_lines(&contact).is_empty() {
            contact.single_value_extended_properties = MsgraphField::Unset;
        }

        let mut body = to_value(&contact).map_err(MsgraphContactVcardError::Json)?;
        if let Some(object) = body.as_object_mut() {
            object.retain(|_, value| {
                !value.is_null() && value.as_array().is_none_or(|array| !array.is_empty())
            });
        }

        from_value(body).map_err(MsgraphContactVcardError::Json)
    }
}

/// A vCard that cannot become a Graph contact body.
#[derive(Debug)]
pub enum MsgraphContactVcardError {
    /// The vCard does not parse.
    Parse(VcardParseError),
    /// The projected contact does not reshape through JSON.
    Json(serde_json::Error),
}

impl fmt::Display for MsgraphContactVcardError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Parse(err) => write!(f, "Invalid vCard: {err}"),
            Self::Json(err) => write!(f, "Cannot shape the Graph contact body: {err}"),
        }
    }
}

impl core::error::Error for MsgraphContactVcardError {}

/// The contact's display name, composed from the name parts when
/// blank, with the filing name as a last resort.
fn display_name(contact: &MsgraphContact) -> String {
    if let Some(name) = opt(&contact.display_name) {
        return name.to_string();
    }

    let composed: Vec<&str> = [&contact.given_name, &contact.middle_name, &contact.surname]
        .into_iter()
        .filter_map(opt)
        .collect();
    if !composed.is_empty() {
        return composed.join(" ");
    }

    opt(&contact.file_as).unwrap_or_default().to_string()
}

/// An ADR property from a Graph physical address, None when every component
/// is empty.
///
/// Graph's street is one multiline field, so each of its lines becomes a
/// vCard street component.
fn adr_prop(
    address: Option<&MsgraphPhysicalAddress>,
    r#type: Option<&'static str>,
) -> Option<VcardProp<'static>> {
    let address = address?;

    let street = address.street.as_deref().unwrap_or("");
    let value = VcardAdr {
        po_box: Vec::new(),
        extended: Vec::new(),
        street: street
            .split('\n')
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .map(|line| Cow::Owned(line.to_string()))
            .collect(),
        locality: option_component(&address.city),
        region: option_component(&address.state),
        postal_code: option_component(&address.postal_code),
        country: option_component(&address.country_or_region),
        ..Default::default()
    };

    let empty = value.street.is_empty()
        && value.locality.is_empty()
        && value.region.is_empty()
        && value.postal_code.is_empty()
        && value.country.is_empty();
    if empty {
        return None;
    }

    Some(VcardProp {
        group: None,
        name: VcardPropName::Kind(VcardPropKind::Adr),
        params: r#type.map(type_param).into_iter().collect(),
        value: VcardValue::Adr(Box::new(value)),
    })
}

/// A RELATED name property (spouse, child): free-form text, hence the
/// explicit VALUE=text (RELATED defaults to a URI).
fn related_prop(r#type: &'static str, name: &str) -> VcardProp<'static> {
    VcardProp {
        group: None,
        name: VcardPropName::Kind(VcardPropKind::Related),
        params: vec![type_param(r#type), VcardParam::Value(Cow::Borrowed("text"))],
        value: VcardValue::Text(VcardText(Cow::Owned(name.to_string()))),
    }
}

/// A single-value TYPE parameter.
fn type_param(value: &'static str) -> VcardParam<'static> {
    VcardParam::Type(vec![Cow::Borrowed(value)])
}

/// The trimmed field, None when unset, null or blank.
fn opt(field: &MsgraphField<String>) -> Option<&str> {
    let value = field.as_deref()?.trim();
    if value.is_empty() { None } else { Some(value) }
}

/// The collection items, empty when the field is unset or null.
fn list<T>(field: &MsgraphField<Vec<T>>) -> &[T] {
    field.as_option().map(Vec::as_slice).unwrap_or(&[])
}

/// A structured-value component holding the trimmed field, or empty.
fn component(field: &MsgraphField<String>) -> Vec<Cow<'static, str>> {
    match opt(field) {
        Some(value) => vec![Cow::Owned(value.to_string())],
        None => Vec::new(),
    }
}

/// Like [`component`], for the plain options of a physical address.
fn option_component(value: &Option<String>) -> Vec<Cow<'static, str>> {
    let value = value.as_deref().unwrap_or("").trim();
    if value.is_empty() {
        Vec::new()
    } else {
        vec![Cow::Owned(value.to_string())]
    }
}

/// Fills a single-instance Graph field, first non-empty value wins;
/// true when this value took the slot.
fn set_first(slot: &mut Option<String>, value: impl AsRef<str>) -> bool {
    let value = value.as_ref().trim();
    if slot.is_none() && !value.is_empty() {
        *slot = Some(value.to_string());
        true
    } else {
        false
    }
}

impl MsgraphContact {
    /// The vCard UID the stash carries, `None` for a contact no vCard was
    /// ever written to, Graph having no UID slot of its own.
    ///
    /// A sync engine checks it after a write: a server that dropped the
    /// stash would hand the contact back with an identity minted from its
    /// Graph id rather than the UID it was written under.
    pub fn stashed_uid(&self) -> Option<String> {
        stash_lines(self).iter().find_map(|line| {
            let mut bytes = line.clone();
            bytes.push_str("\r\n");
            let (line, _) = VcardLine::take(bytes.as_bytes()).ok()?;
            line.bare_name()
                .eq_ignore_ascii_case("UID")
                .then(|| line.raw_value_str().trim().to_string())
                .filter(|uid| !uid.is_empty())
        })
    }
}

/// The stashed vCard remainder lines behind the contact's cardamum
/// extended property (matched by name: Graph may normalize the GUID
/// spelling in responses).
fn stash_lines(contact: &MsgraphContact) -> Vec<String> {
    contact
        .single_value_extended_properties
        .as_option()
        .map(Vec::as_slice)
        .unwrap_or(&[])
        .iter()
        .filter(|prop| prop.id.to_ascii_lowercase().contains("cardamum-vcard"))
        .flat_map(|prop| prop.value.split('\n'))
        .filter(|line| !line.is_empty())
        .map(str::to_string)
        .collect()
}

/// The structured-value components joined into one Graph field, None
/// when nothing remains.
fn joined(components: &[Cow<'_, str>]) -> Option<String> {
    let joined = components
        .iter()
        .map(|component| component.as_ref().trim())
        .filter(|component| !component.is_empty())
        .collect::<Vec<_>>()
        .join(" ");
    if joined.is_empty() {
        None
    } else {
        Some(joined)
    }
}

/// Collects every TYPE parameter value, lowercased.
fn type_values(line: &VcardLine) -> Vec<String> {
    let mut types = Vec::new();
    for param in &line.params {
        if param.name.get().eq_ignore_ascii_case("TYPE") {
            types.extend(
                param
                    .values
                    .iter()
                    .map(|value| value.get().to_ascii_lowercase()),
            );
        }
    }
    types
}

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

    /// A contact filling every field the projection manages.
    fn full_contact() -> MsgraphContact {
        MsgraphContact {
            display_name: MsgraphField::Set("Jane Doe".into()),
            given_name: MsgraphField::Set("Jane".into()),
            middle_name: MsgraphField::Set("Q.".into()),
            surname: MsgraphField::Set("Doe".into()),
            title: MsgraphField::Set("Dr.".into()),
            nick_name: MsgraphField::Set("Janie".into()),
            email_addresses: MsgraphField::Set(vec![MsgraphEmailAddress {
                name: None,
                address: Some("jane@doe.org".into()),
            }]),
            im_addresses: MsgraphField::Set(vec!["xmpp:jane@doe.org".into()]),
            business_phones: MsgraphField::Set(vec!["+331111".into()]),
            home_phones: MsgraphField::Set(vec!["+332222".into()]),
            mobile_phone: MsgraphField::Set("+333333".into()),
            home_address: MsgraphField::Set(MsgraphPhysicalAddress {
                street: Some("12 Main St".into()),
                city: Some("Paris".into()),
                state: Some("IDF".into()),
                country_or_region: Some("France".into()),
                postal_code: Some("75000".into()),
            }),
            business_address: MsgraphField::Set(MsgraphPhysicalAddress {
                street: Some("1 Work Way".into()),
                city: Some("Lyon".into()),
                state: None,
                country_or_region: None,
                postal_code: None,
            }),
            other_address: MsgraphField::Set(MsgraphPhysicalAddress {
                street: Some("3 Other Rd".into()),
                city: None,
                state: None,
                country_or_region: None,
                postal_code: None,
            }),
            company_name: MsgraphField::Set("ACME".into()),
            department: MsgraphField::Set("R&D".into()),
            job_title: MsgraphField::Set("Boss".into()),
            profession: MsgraphField::Set("Engineer".into()),
            business_home_page: MsgraphField::Set("https://doe.org".into()),
            birthday: MsgraphField::Set("1983-04-01T00:00:00Z".into()),
            spouse_name: MsgraphField::Set("John Doe".into()),
            children: MsgraphField::Set(vec!["Jimmy".into()]),
            personal_notes: MsgraphField::Set("a note".into()),
            categories: MsgraphField::Set(vec!["friends".into(), "band".into()]),
            ..Default::default()
        }
    }

    #[test]
    fn to_vcard_projects_every_mapped_field() {
        let mut contact = full_contact();
        contact.id = "AAMkAGI2".into();

        let vcard = (contact).to_vcard();
        assert!(vcard.contains("VERSION:4.0\r\n"));
        assert!(vcard.contains("UID:AAMkAGI2\r\n"));
        assert!(vcard.contains("FN:Jane Doe\r\n"));
        assert!(vcard.contains("N:Doe;Jane;Q.;Dr.;\r\n"));
        assert!(vcard.contains("NICKNAME:Janie\r\n"));
        assert!(vcard.contains("EMAIL:jane@doe.org\r\n"));
        assert!(vcard.contains("IMPP:xmpp:jane@doe.org\r\n"));
        assert!(vcard.contains("TEL;TYPE=work:+331111\r\n"));
        assert!(vcard.contains("TEL;TYPE=home:+332222\r\n"));
        assert!(vcard.contains("TEL;TYPE=cell:+333333\r\n"));
        assert!(vcard.contains("ADR;TYPE=home:;;12 Main St;Paris;IDF;75000;France\r\n"));
        assert!(vcard.contains("ADR;TYPE=work:;;1 Work Way;Lyon;;;\r\n"));
        assert!(vcard.contains("ADR:;;3 Other Rd;;;;\r\n"));
        assert!(vcard.contains("ORG:ACME;R&D\r\n"));
        assert!(vcard.contains("TITLE:Boss\r\n"));
        assert!(vcard.contains("ROLE:Engineer\r\n"));
        assert!(vcard.contains("URL:https://doe.org\r\n"));
        assert!(vcard.contains("BDAY:1983-04-01\r\n"));
        assert!(vcard.contains("NOTE:a note\r\n"));
        assert!(vcard.contains("CATEGORIES:friends,band\r\n"));
        assert!(vcard.contains("RELATED;TYPE=spouse;VALUE=text:John Doe\r\n"));
        assert!(vcard.contains("RELATED;TYPE=child;VALUE=text:Jimmy\r\n"));
    }

    #[test]
    fn to_vcard_composes_fn_from_name_parts() {
        let contact = MsgraphContact {
            given_name: MsgraphField::Set("Jane".into()),
            surname: MsgraphField::Set("Doe".into()),
            ..Default::default()
        };
        assert!((contact).to_vcard().contains("FN:Jane Doe\r\n"));
    }

    #[test]
    fn from_vcard_reads_managed_props() {
        let vcard = "BEGIN:VCARD\r\nVERSION:4.0\r\nUID:abc\r\nFN:Jane Doe\r\n\
            N:Doe;Jane;Q.;Dr.;\r\nNICKNAME:Janie,JJ\r\nEMAIL:jane@doe.org\r\n\
            IMPP:xmpp:jane@doe.org\r\nTEL;TYPE=cell:+333333\r\n\
            TEL;TYPE=home,voice:+332222\r\nTEL:+331111\r\n\
            ADR;TYPE=home:;;12 Main St;Paris;IDF;75000;France\r\nORG:ACME;R&D\r\n\
            TITLE:Boss\r\nROLE:Engineer\r\nURL:https://doe.org\r\nBDAY:1983-04-01\r\n\
            NOTE:a note\r\nCATEGORIES:friends,band\r\n\
            RELATED;TYPE=spouse;VALUE=text:John Doe\r\n\
            RELATED;TYPE=child;VALUE=text:Jimmy\r\nEND:VCARD\r\n";

        let contact = MsgraphContact::from_vcard(vcard).unwrap();
        assert_eq!(contact.id, "");
        assert_eq!(contact.display_name.as_deref(), Some("Jane Doe"));
        assert_eq!(contact.surname.as_deref(), Some("Doe"));
        assert_eq!(contact.given_name.as_deref(), Some("Jane"));
        assert_eq!(contact.middle_name.as_deref(), Some("Q."));
        assert_eq!(contact.title.as_deref(), Some("Dr."));
        assert_eq!(contact.nick_name.as_deref(), Some("Janie"));
        let emails = contact.email_addresses.as_option().unwrap();
        assert_eq!(emails[0].address.as_deref(), Some("jane@doe.org"));
        assert_eq!(
            contact.im_addresses.as_option().unwrap(),
            &vec!["xmpp:jane@doe.org".to_string()]
        );
        assert_eq!(contact.mobile_phone.as_deref(), Some("+333333"));
        assert_eq!(
            contact.home_phones.as_option().unwrap(),
            &vec!["+332222".to_string()]
        );
        assert_eq!(
            contact.business_phones.as_option().unwrap(),
            &vec!["+331111".to_string()]
        );
        let home = contact.home_address.as_option().unwrap();
        assert_eq!(home.street.as_deref(), Some("12 Main St"));
        assert_eq!(home.city.as_deref(), Some("Paris"));
        assert_eq!(home.state.as_deref(), Some("IDF"));
        assert_eq!(home.postal_code.as_deref(), Some("75000"));
        assert_eq!(home.country_or_region.as_deref(), Some("France"));
        assert_eq!(contact.company_name.as_deref(), Some("ACME"));
        assert_eq!(contact.department.as_deref(), Some("R&D"));
        assert_eq!(contact.job_title.as_deref(), Some("Boss"));
        assert_eq!(contact.profession.as_deref(), Some("Engineer"));
        assert_eq!(
            contact.business_home_page.as_deref(),
            Some("https://doe.org")
        );
        assert_eq!(contact.birthday.as_deref(), Some("1983-04-01T00:00:00Z"));
        assert_eq!(contact.spouse_name.as_deref(), Some("John Doe"));
        assert_eq!(
            contact.children.as_option().unwrap(),
            &vec!["Jimmy".to_string()]
        );
        assert_eq!(contact.personal_notes.as_deref(), Some("a note"));
        assert_eq!(
            contact.categories.as_option().unwrap(),
            &vec!["friends".to_string(), "band".to_string()]
        );
    }

    #[test]
    fn from_vcard_clears_absent_managed_fields_and_keeps_unmanaged_unset() {
        let vcard = "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:X\r\nEND:VCARD\r\n";
        let contact = MsgraphContact::from_vcard(vcard).unwrap();

        assert_eq!(contact.spouse_name, MsgraphField::Null);
        assert_eq!(contact.mobile_phone, MsgraphField::Null);
        assert_eq!(contact.home_address, MsgraphField::Null);
        assert_eq!(contact.business_phones, MsgraphField::Set(vec![]));
        assert_eq!(contact.email_addresses, MsgraphField::Set(vec![]));

        assert_eq!(contact.file_as, MsgraphField::Unset);
        assert_eq!(contact.assistant_name, MsgraphField::Unset);
        assert_eq!(contact.manager, MsgraphField::Unset);
        assert_eq!(contact.office_location, MsgraphField::Unset);
    }

    #[test]
    fn update_from_vcard_keeps_only_changed_fields() {
        let base = "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:Jane Doe\r\n\
            TEL;TYPE=cell:+333333\r\nEMAIL:jane@doe.org\r\n\
            NOTE:a note\r\nEND:VCARD\r\n";
        let edited = "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:Jane Doe\r\n\
            TEL;TYPE=cell:+444444\r\nEMAIL:jane@doe.org\r\nEND:VCARD\r\n";

        let contact = MsgraphContact::update_from_vcard(edited, base).unwrap();

        assert_eq!(contact.mobile_phone.as_deref(), Some("+444444"));
        assert_eq!(contact.personal_notes, MsgraphField::Null);

        // NOTE: unchanged on both sides means out of the body, since a
        // gratuitous null is what the Outlook backend chokes on.
        assert_eq!(contact.display_name, MsgraphField::Unset);
        assert_eq!(contact.email_addresses, MsgraphField::Unset);
        assert_eq!(contact.birthday, MsgraphField::Unset);
        assert_eq!(contact.home_address, MsgraphField::Unset);
        assert_eq!(contact.categories, MsgraphField::Unset);
    }

    #[test]
    fn update_from_vcard_clears_collections_with_empty_sets() {
        let base = "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:X\r\n\
            TEL;TYPE=home:+332222\r\nCATEGORIES:friends\r\nEND:VCARD\r\n";
        let edited = "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:X\r\nEND:VCARD\r\n";

        let contact = MsgraphContact::update_from_vcard(edited, base).unwrap();
        assert_eq!(contact.home_phones, MsgraphField::Set(vec![]));
        assert_eq!(contact.categories, MsgraphField::Set(vec![]));
    }

    #[test]
    fn update_from_vcard_of_identical_cards_is_empty() {
        let vcard = (full_contact()).to_vcard();
        let contact = MsgraphContact::update_from_vcard(&vcard, &vcard).unwrap();
        assert_eq!(contact, MsgraphContact::default());
    }

    #[test]
    fn create_from_vcard_drops_nulls_and_empty_collections() {
        let vcard = "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:X\r\nTEL;TYPE=CELL:+331111\r\nEND:VCARD\r\n";
        let contact = MsgraphContact::create_from_vcard(vcard).unwrap();

        assert_eq!(contact.display_name.as_deref(), Some("X"));
        assert_eq!(contact.mobile_phone.as_deref(), Some("+331111"));
        assert_eq!(contact.spouse_name, MsgraphField::Unset);
        assert_eq!(contact.home_address, MsgraphField::Unset);
        assert_eq!(contact.business_phones, MsgraphField::Unset);
        assert_eq!(contact.email_addresses, MsgraphField::Unset);
    }

    #[test]
    fn from_vcard_respects_graph_slots() {
        let vcard = "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:X\r\n\
            TEL;TYPE=cell:+331111\r\nTEL;TYPE=cell:+332222\r\n\
            TEL;TYPE=work:+333331\r\nTEL;TYPE=work:+333332\r\nTEL:+333333\r\n\
            TEL;TYPE=home:+334441\r\nTEL;TYPE=home:+334442\r\nTEL;TYPE=home:+334443\r\n\
            ADR;TYPE=home:;;First St;;;;\r\nADR;TYPE=home:;;Second St;;;;\r\n\
            EMAIL:a@x.org\r\nEMAIL:b@x.org\r\nEMAIL:c@x.org\r\nEMAIL:d@x.org\r\n\
            IMPP:xmpp:a@x.org\r\nIMPP:xmpp:b@x.org\r\nIMPP:xmpp:c@x.org\r\nIMPP:xmpp:d@x.org\r\n\
            RELATED;TYPE=spouse:urn:uuid:03a0e51f\r\nEND:VCARD\r\n";

        let contact = MsgraphContact::from_vcard(vcard).unwrap();

        // NOTE: one mobile slot, so the second cell TEL is dropped
        // rather than misfiled as a business phone.
        assert_eq!(contact.mobile_phone.as_deref(), Some("+331111"));

        assert_eq!(
            contact.business_phones.as_option().unwrap(),
            &vec!["+333331".to_string(), "+333332".to_string()]
        );
        assert_eq!(
            contact.home_phones.as_option().unwrap(),
            &vec!["+334441".to_string(), "+334442".to_string()]
        );
        assert_eq!(contact.email_addresses.as_option().unwrap().len(), 3);
        assert_eq!(contact.im_addresses.as_option().unwrap().len(), 3);

        let home = contact.home_address.as_option().unwrap();
        assert_eq!(home.street.as_deref(), Some("First St"));
        assert_eq!(contact.spouse_name, MsgraphField::Null);
    }

    #[test]
    fn round_trip() {
        let contact = full_contact();

        // NOTE: the full-state projection always carries the (empty)
        // stash slot, so a cleared stash is distinguishable from an
        // unchanged one.
        let mut expected = contact.clone();
        expected.single_value_extended_properties =
            MsgraphField::Set(vec![MsgraphSingleValueExtendedProperty {
                id: MSGRAPH_CONTACT_STASH_ID.to_string(),
                value: String::new(),
            }]);

        assert_eq!(
            MsgraphContact::from_vcard(&contact.to_vcard()).unwrap(),
            expected
        );
    }

    #[test]
    fn stash_preserves_unprojected_props() {
        let vcard = "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:X\r\nX-FOO;TYPE=bar:baz\r\n\
            EMAIL:a@x.org\r\nEMAIL:b@x.org\r\nEMAIL:c@x.org\r\nEMAIL:d@x.org\r\nEND:VCARD\r\n";

        let contact = MsgraphContact::from_vcard(vcard).unwrap();
        let props = contact
            .single_value_extended_properties
            .as_option()
            .unwrap();
        assert_eq!(props[0].id, MSGRAPH_CONTACT_STASH_ID);
        assert_eq!(props[0].value, "X-FOO;TYPE=bar:baz\nEMAIL:d@x.org");

        let restored = (contact).to_vcard();
        assert!(restored.contains("X-FOO;TYPE=bar:baz\r\n"));
        assert!(restored.contains("EMAIL:d@x.org\r\n"));
        assert!(restored.ends_with("END:VCARD\r\n"));
    }

    #[test]
    fn minted_props_project_and_consume() {
        let mut contact = full_contact();
        contact.file_as = MsgraphField::Set("Doe, Jane".into());
        contact.office_location = MsgraphField::Set("B2".into());
        contact.assistant_name = MsgraphField::Set("Sam".into());
        contact.manager = MsgraphField::Set("Alex".into());

        let vcard = (contact).to_vcard();
        assert!(vcard.contains("X-MSGRAPH-FILE-AS:Doe\\, Jane\r\n"));
        assert!(vcard.contains("X-MSGRAPH-OFFICE-LOCATION:B2\r\n"));
        assert!(vcard.contains("X-MSGRAPH-ASSISTANT:Sam\r\n"));
        assert!(vcard.contains("X-MSGRAPH-MANAGER:Alex\r\n"));

        // NOTE: consumed on the way back, so the fields stay Unset and
        // the lines stay out of the stash.
        let back = MsgraphContact::from_vcard(&vcard).unwrap();
        assert_eq!(back.file_as, MsgraphField::Unset);
        assert_eq!(back.office_location, MsgraphField::Unset);
        assert_eq!(back.assistant_name, MsgraphField::Unset);
        assert_eq!(back.manager, MsgraphField::Unset);
        let props = back.single_value_extended_properties.as_option().unwrap();
        assert_eq!(props[0].value, "");
    }

    #[test]
    fn update_from_vcard_tracks_the_stash() {
        let base = "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:X\r\nX-FOO:bar\r\nEND:VCARD\r\n";
        let unchanged = MsgraphContact::update_from_vcard(base, base).unwrap();
        assert_eq!(
            unchanged.single_value_extended_properties,
            MsgraphField::Unset
        );

        let cleared = "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:X\r\nEND:VCARD\r\n";
        let delta = MsgraphContact::update_from_vcard(cleared, base).unwrap();
        let props = delta.single_value_extended_properties.as_option().unwrap();
        assert_eq!(props[0].value, "");
    }

    #[test]
    fn create_from_vcard_drops_the_empty_stash() {
        let vcard = "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:X\r\nEND:VCARD\r\n";
        let contact = MsgraphContact::create_from_vcard(vcard).unwrap();
        assert_eq!(
            contact.single_value_extended_properties,
            MsgraphField::Unset
        );

        let vcard = "BEGIN:VCARD\r\nVERSION:4.0\r\nFN:X\r\nX-FOO:bar\r\nEND:VCARD\r\n";
        let contact = MsgraphContact::create_from_vcard(vcard).unwrap();
        let props = contact
            .single_value_extended_properties
            .as_option()
            .unwrap();
        assert_eq!(props[0].value, "X-FOO:bar");
    }

    #[test]
    fn the_expand_clause_names_the_stash() {
        let quoted = format!("'{MSGRAPH_CONTACT_STASH_ID}'");
        assert!(MSGRAPH_CONTACT_STASH_EXPAND.contains(&quoted));
    }

    #[test]
    fn a_vcard_uid_rides_the_stash_and_wins_over_the_graph_id() {
        let vcard = "BEGIN:VCARD\r\nVERSION:4.0\r\nUID:urn:uuid:4fbe8971\r\n\
            FN:Jane Doe\r\nEND:VCARD\r\n";

        let mut contact = MsgraphContact::create_from_vcard(vcard).unwrap();
        // NOTE: what Graph hands back after the create: its own id, and the
        // stash it was given.
        contact.id = "AAMkAGI2".into();

        assert_eq!(contact.stashed_uid().as_deref(), Some("urn:uuid:4fbe8971"));
        let vcard = contact.to_vcard();
        assert!(vcard.contains("UID:urn:uuid:4fbe8971\r\n"));
        assert!(!vcard.contains("UID:AAMkAGI2"));
    }

    #[test]
    fn a_contact_graph_created_mints_its_uid_from_the_graph_id() {
        let contact = MsgraphContact {
            id: "AAMkAGI2".into(),
            display_name: MsgraphField::Set("Jane Doe".into()),
            ..Default::default()
        };

        assert_eq!(contact.stashed_uid(), None);
        assert!(contact.to_vcard().contains("UID:AAMkAGI2\r\n"));
    }
}