openvtc-core 0.4.0

OpenVTC Core Library
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
//! Which VTA context a community lives in.
//!
//! Every community a person joins can get its own sub-context under the
//! account's top context (`<top>/<slug>`). A sub-context has its own branch of
//! the key hierarchy and its own ACL scope, and the persona's faces for that
//! community are worn in it, so nothing a community is shown, and no key its
//! persona signs with, is shared with another community unless the person
//! chooses to share it.
//!
//! The choice is the person's, made when they join (or start a vetting
//! application): a new sub-context, a context they already use, or the top
//! context. One constraint shapes the options: a persona's keys and DID live in
//! exactly one context, the one it was minted in. A persona minted into a
//! sub-context can only be presented from that context; picking it means
//! sharing that context. A persona minted before per-community contexts has its
//! keys in the top context, so any context can hold its faces, but none of them
//! isolates its keys.
//!
//! OpenVTC holds admin of the top context, which covers every sub-context
//! beneath it. Isolation is therefore between communities, not from OpenVTC
//! itself.

use vta_sdk::client::{CreateContextRequest, VtaClient};
use vta_sdk::error::VtaError;
use vta_sdk::protocols::context_management::delete::DeleteContextPreviewResultBody;

use super::account::{Account, CommunityRecord, PersonaId, PersonaRecord};
use super::context_path::{
    SEPARATOR, build_sub_context_id, child_path, parse_sub_context_id, slugify,
    validate_context_path,
};
use crate::errors::OpenVTCError;
use crate::vetting::applicant::Application;

/// The context `persona`'s keys and DID live in. Personas minted before
/// per-community contexts record none, and theirs are in the top context.
#[must_use]
pub fn persona_context<'a>(persona: &'a PersonaRecord, top_context_id: &'a str) -> &'a str {
    if persona.origin_context_id.is_empty() {
        top_context_id
    } else {
        &persona.origin_context_id
    }
}

/// Whether `context_id` is a sub-context of `top_context_id` (strictly below it).
#[must_use]
pub fn is_sub_context(context_id: &str, top_context_id: &str) -> bool {
    context_id
        .strip_prefix(top_context_id)
        .is_some_and(|rest| rest.starts_with(SEPARATOR) && rest.len() > 1)
}

/// What kind of context an option is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContextKind {
    /// A new sub-context, for this community alone.
    New,
    /// A context the account already uses.
    Existing,
    /// The account's top context.
    Top,
}

/// One context a join or an application can use.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContextOption {
    /// The full context path.
    pub context_id: String,
    pub kind: ContextKind,
    /// The communities already in it, by VTC DID.
    pub communities: Vec<String>,
    /// The persona being presented has its keys here, so this is the only
    /// context it can be presented from.
    pub holds_persona_keys: bool,
}

impl ContextOption {
    /// The option in one line: its path and what choosing it means.
    #[must_use]
    pub fn summary(&self) -> String {
        let id = &self.context_id;
        match self.kind {
            ContextKind::New => format!("{id}  (a context of its own)"),
            ContextKind::Existing if self.holds_persona_keys => {
                format!("{id}  (this persona's context)")
            }
            ContextKind::Existing => match self.communities.len() {
                0 => format!("{id}  (in use)"),
                1 => format!("{id}  (shared with 1 community)"),
                n => format!("{id}  (shared with {n} communities)"),
            },
            ContextKind::Top => format!("{id}  (top context — nothing kept apart)"),
        }
    }
}

/// The contexts available for presenting `persona` — `None` for a persona not
/// yet minted — to a community, with `suggested_new` as the new sub-context.
///
/// A persona whose keys live in a sub-context has one option: that context.
/// Everyone else may choose a new sub-context (first, the default), any
/// sub-context the account already uses, or the top context.
#[must_use]
pub fn context_options(
    account: &Account,
    persona: Option<&PersonaRecord>,
    suggested_new: &str,
) -> Vec<ContextOption> {
    let top = account.top_context_id.as_str();
    let in_context = |context_id: &str| -> Vec<String> {
        let mut communities: Vec<String> = account
            .memberships()
            .filter(|m| m.sub_context_id == context_id)
            .map(|m| m.vtc_did.clone())
            .collect();
        communities.sort();
        communities.dedup();
        communities
    };

    if let Some(persona) = persona {
        let home = persona_context(persona, top);
        if is_sub_context(home, top) {
            return vec![ContextOption {
                context_id: home.to_string(),
                kind: ContextKind::Existing,
                communities: in_context(home),
                holds_persona_keys: true,
            }];
        }
    }

    let mut existing: Vec<String> = account
        .memberships()
        .map(|m| m.sub_context_id.clone())
        .chain(
            account
                .personas
                .values()
                .map(|p| p.origin_context_id.clone()),
        )
        .filter(|c| is_sub_context(c, top) && c != suggested_new)
        .collect();
    existing.sort();
    existing.dedup();

    let mut options = vec![ContextOption {
        context_id: suggested_new.to_string(),
        kind: ContextKind::New,
        communities: Vec::new(),
        holds_persona_keys: false,
    }];
    options.extend(existing.into_iter().map(|context_id| ContextOption {
        communities: in_context(&context_id),
        context_id,
        kind: ContextKind::Existing,
        holds_persona_keys: false,
    }));
    options.push(ContextOption {
        context_id: top.to_string(),
        kind: ContextKind::Top,
        communities: in_context(top),
        holds_persona_keys: persona.is_some(),
    });
    options
}

/// Whether `context_id` is already used by the account — by a membership or a
/// persona's keys.
#[must_use]
pub fn context_in_use(account: &Account, context_id: &str) -> bool {
    account
        .memberships()
        .any(|m| m.sub_context_id == context_id)
        || account
            .personas
            .values()
            .any(|p| p.origin_context_id == context_id)
}

/// The new sub-context `<top>/<slug>` for a slug the person typed.
///
/// # Errors
///
/// A slug that is not a valid path segment, a path too deep, or one already in
/// use — a new context is new, and choosing an existing one is a different
/// option.
pub fn new_context_id(
    top_context_id: &str,
    slug: &str,
    taken: impl Fn(&str) -> bool,
) -> Result<String, OpenVTCError> {
    let id = child_path(top_context_id, slug.trim())?;
    if taken(&id) {
        return Err(OpenVTCError::Config(format!(
            "{id} is already in use — choose it from the list to share it, or pick another name"
        )));
    }
    Ok(id)
}

/// How far a membership is kept apart from the account's other communities.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Isolation {
    /// Its own sub-context, holding its persona's keys.
    Isolated,
    /// A sub-context that holds its persona's keys, shared with `n` other
    /// memberships.
    Shared(usize),
    /// Its own sub-context for faces, but the persona's keys live elsewhere —
    /// a persona minted before per-community contexts, or one shown to several.
    KeysElsewhere,
    /// The account's top context.
    Top,
}

impl Isolation {
    /// One line for the communities panel.
    #[must_use]
    pub fn describe(self) -> String {
        match self {
            Isolation::Isolated => "own context — kept apart from your other communities".into(),
            Isolation::Shared(1) => "shared with 1 other community".into(),
            Isolation::Shared(n) => format!("shared with {n} other communities"),
            Isolation::KeysElsewhere => {
                "own context for faces — this persona's keys live in another context".into()
            }
            Isolation::Top => "top context — not kept apart".into(),
        }
    }
}

/// How `membership` is kept apart, given the account it belongs to.
#[must_use]
pub fn isolation(account: &Account, membership: &CommunityRecord) -> Isolation {
    let top = account.top_context_id.as_str();
    let context = membership.sub_context_id.as_str();
    if context.is_empty() || !is_sub_context(context, top) {
        return Isolation::Top;
    }
    let keys_here = account
        .personas
        .get(&membership.persona_ref)
        .is_some_and(|p| persona_context(p, top) == context);
    if !keys_here {
        return Isolation::KeysElsewhere;
    }
    let others = account
        .memberships()
        .filter(|m| m.sub_context_id == context)
        .count()
        .saturating_sub(1);
    match others {
        0 => Isolation::Isolated,
        n => Isolation::Shared(n),
    }
}

/// Make sure `context_id` exists at the VTA, creating it — and any missing
/// ancestor — beneath the account's top context. Returns whether anything was
/// created. The top context itself is never created here; it exists from setup.
///
/// Looked up before it is created, and a create that races another one
/// (`Conflict`) counts as existing, so a retried join reuses what an
/// interrupted one left behind.
///
/// # Errors
///
/// A path outside the account's top context, or a VTA that refuses.
pub async fn ensure_context(
    client: &VtaClient,
    top_context_id: &str,
    context_id: &str,
    name: &str,
) -> Result<bool, OpenVTCError> {
    if context_id == top_context_id {
        return Ok(false);
    }
    validate_context_path(context_id)?;
    if !is_sub_context(context_id, top_context_id) {
        return Err(OpenVTCError::Config(format!(
            "{context_id} is not inside this account's context {top_context_id}"
        )));
    }
    let mut created = false;
    let mut chain = Vec::new();
    let mut current = context_id;
    while current != top_context_id {
        chain.push(current);
        match parse_sub_context_id(current) {
            Some((parent, _)) => current = parent,
            None => break,
        }
    }
    for path in chain.into_iter().rev() {
        match client.get_context(path).await {
            Ok(_) => continue,
            Err(VtaError::NotFound(_)) => {}
            Err(e) => {
                return Err(OpenVTCError::Vta(format!(
                    "could not look up context {path}: {e}"
                )));
            }
        }
        let Some((parent, slug)) = parse_sub_context_id(path) else {
            continue;
        };
        let label = if path == context_id { name } else { slug };
        match client
            .create_context(
                CreateContextRequest::new(slug, label)
                    .description("A community context, created by OpenVTC")
                    .parent(parent),
            )
            .await
        {
            Ok(_) => created = true,
            Err(VtaError::Conflict(_)) => {}
            Err(e) => {
                return Err(OpenVTCError::Vta(format!(
                    "could not create context {path}: {e}"
                )));
            }
        }
    }
    Ok(created)
}

/// Whether `context_id` is already claimed: by a membership, a persona's keys,
/// or a vetting application's face. A new context must not be any of these.
#[must_use]
pub fn context_claimed(account: &Account, applications: &[Application], context_id: &str) -> bool {
    context_in_use(account, context_id)
        || applications
            .iter()
            .any(|a| a.context_id.as_deref() == Some(context_id))
}

/// The new sub-context to suggest for something called `name` — a community,
/// or a persona's label — slugified, made unique, and `fallback` when the name
/// has nothing a path segment can hold.
///
/// # Errors
///
/// Only a top context that cannot hold a child (invalid, or at the depth
/// limit).
pub fn suggested_context_id(
    top_context_id: &str,
    name: &str,
    fallback: &str,
    taken: impl Fn(&str) -> bool,
) -> Result<String, OpenVTCError> {
    let name = if slugify(name).is_empty() {
        fallback
    } else {
        name
    };
    // With a name that slugifies to something, the community-DID fallback of
    // `build_sub_context_id` is never consulted.
    build_sub_context_id(top_context_id, Some(name), "", taken)
}

/// Something that keeps a context in use, and so stops it being deleted.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ContextUse {
    /// A membership lives in it.
    Membership {
        vtc_did: String,
        persona: PersonaId,
        /// The community's display name, or its DID.
        name: String,
    },
    /// A persona's keys and DID were minted in it; deleting the context
    /// deletes them.
    PersonaKeys {
        persona: PersonaId,
        /// The persona's label, or its DID.
        name: String,
    },
    /// A vetting application wears its face there.
    VettingApplication {
        community: String,
        persona: PersonaId,
    },
}

impl ContextUse {
    /// What uses the context, in words.
    #[must_use]
    pub fn describe(&self) -> String {
        match self {
            ContextUse::Membership { name, .. } => format!("your membership of {name}"),
            ContextUse::PersonaKeys { name, .. } => format!("the keys and DID of persona {name}"),
            ContextUse::VettingApplication { community, .. } => {
                format!("your vetting application to {community}")
            }
        }
    }
}

/// Everything in the account that uses `context_id`.
#[must_use]
pub fn context_uses(
    account: &Account,
    applications: &[Application],
    context_id: &str,
) -> Vec<ContextUse> {
    let memberships = account
        .memberships()
        .filter(|m| m.sub_context_id == context_id)
        .map(|m| ContextUse::Membership {
            vtc_did: m.vtc_did.clone(),
            persona: m.persona_ref,
            name: m.display_name.clone().unwrap_or_else(|| m.vtc_did.clone()),
        });
    let mut personas: Vec<&PersonaRecord> = account
        .personas
        .values()
        .filter(|p| p.origin_context_id == context_id)
        .collect();
    personas.sort_by(|a, b| a.did.cmp(&b.did));
    let personas = personas.into_iter().map(|p| ContextUse::PersonaKeys {
        persona: p.persona_id,
        name: p.label.clone().unwrap_or_else(|| p.did.clone()),
    });
    let applications = applications
        .iter()
        .filter(|a| a.context_id.as_deref() == Some(context_id))
        .map(|a| ContextUse::VettingApplication {
            community: a.community.clone(),
            persona: a.persona,
        });
    memberships.chain(personas).chain(applications).collect()
}

/// A persona deleted together with its community's context: its keys and DID
/// live there, and the finished membership being cleaned up was its only use.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PersonaTakenAlong {
    pub persona: PersonaId,
    /// The persona's `did:webvh`.
    pub did: String,
    /// The persona's label, or its DID.
    pub name: String,
}

/// What deleting a finished membership's context takes with it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContextDeletion {
    /// The context, deleted with its subtree.
    pub context_id: String,
    /// The persona deleted along with the context — and, with the persona, the
    /// membership record, which is left with nothing to act on. `None` when no
    /// persona's keys are in the context; the membership record is then kept,
    /// without a context.
    pub persona: Option<PersonaTakenAlong>,
}

impl ContextDeletion {
    /// What the deletion removes beyond the VTA's own preview of the context,
    /// one line each, for the membership of `community`.
    #[must_use]
    pub fn consequences(&self, community: &str) -> Vec<String> {
        match &self.persona {
            Some(persona) => vec![
                "Also deleted with it:".to_string(),
                format!("  Persona {}", persona.name),
                format!("    {}", persona.did),
                "    This persona can no longer be used anywhere. Its did:webvh is removed from its"
                    .to_string(),
                "    host through your VTA; if the host cannot be reached, it stays published there."
                    .to_string(),
                format!("  Your finished membership of {community}"),
                "    Its record is removed: nothing is left for it to act on.".to_string(),
            ],
            None => vec![format!(
                "Your finished membership of {community} is kept, without a context."
            )],
        }
    }
}

/// Something other than the finished membership that uses its persona, and so
/// keeps the persona — and the context holding its keys — from being deleted.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PersonaUse {
    /// Another membership, of any status.
    Membership {
        /// The community's display name, or its DID.
        name: String,
    },
    /// A vetting application, wherever its face is worn.
    VettingApplication { community: String },
    /// It is the persona OpenVTC is acting as.
    Active,
}

impl PersonaUse {
    /// The use, in words.
    #[must_use]
    pub fn describe(&self) -> String {
        match self {
            PersonaUse::Membership { name } => format!("your membership of {name}"),
            PersonaUse::VettingApplication { community } => {
                format!("your vetting application to {community}")
            }
            PersonaUse::Active => "OpenVTC, as your active persona".to_string(),
        }
    }
}

/// Why a membership's context cannot be deleted.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DeletionRefusal {
    /// The membership lives in the account's top context (or names none of its
    /// own), and the top context is never deleted from here.
    TopContext,
    /// The membership is still live (Active or Pending); it has to be over
    /// first.
    StillLive,
    /// Something else still uses the context.
    InUse(Vec<ContextUse>),
    /// The context holds the keys of the membership's persona, and the persona
    /// is used by something besides this membership.
    PersonaInUse {
        /// The persona's label, or its DID.
        name: String,
        uses: Vec<PersonaUse>,
    },
}

impl DeletionRefusal {
    /// The refusal, in a sentence that names what to do about it.
    #[must_use]
    pub fn describe(&self) -> String {
        match self {
            DeletionRefusal::TopContext => {
                "This community lives in your top context, which holds every community — it is \
                 never deleted from here."
                    .to_string()
            }
            DeletionRefusal::StillLive => {
                "Leave the community (or cancel the join) before deleting its context.".to_string()
            }
            DeletionRefusal::InUse(uses) => {
                let what: Vec<String> = uses.iter().map(ContextUse::describe).collect();
                format!(
                    "The context is still used by {} — it can be deleted once nothing uses it.",
                    what.join("; ")
                )
            }
            DeletionRefusal::PersonaInUse { name, uses } => {
                let what: Vec<String> = uses.iter().map(PersonaUse::describe).collect();
                format!(
                    "The context holds the keys and DID of persona {name}, which is also used by \
                     {} — it can be deleted with that persona only while this finished \
                     membership is the persona's only use.",
                    what.join("; ")
                )
            }
        }
    }
}

/// What deleting `membership`'s context would take with it, if it may be
/// deleted.
///
/// Only a membership that is over (left, withdrawn, rejected, removed,
/// expired), only a sub-context of the account's own, and only when nothing
/// else — another membership, another persona's keys, a vetting application —
/// uses it. The membership itself does not count as a use.
///
/// The context may hold the keys of the membership's own persona: joining
/// mints a persona into the community's context. Then the persona goes too,
/// with the membership record, provided this finished membership is the
/// persona's only use — no other membership of any status, no vetting
/// application, and not `active_persona`. Otherwise the refusal names what
/// still uses the persona.
///
/// # Errors
///
/// The [`DeletionRefusal`] that applies.
pub fn deletable_context(
    account: &Account,
    applications: &[Application],
    active_persona: Option<PersonaId>,
    membership: &CommunityRecord,
) -> Result<ContextDeletion, DeletionRefusal> {
    let context_id = membership.sub_context_id.as_str();
    if !is_sub_context(context_id, &account.top_context_id) {
        return Err(DeletionRefusal::TopContext);
    }
    if !membership.status.is_inactive() {
        return Err(DeletionRefusal::StillLive);
    }
    let own = membership.persona_ref;
    let is_this = |vtc: &str, persona: PersonaId| vtc == membership.vtc_did && persona == own;
    let uses: Vec<ContextUse> = context_uses(account, applications, context_id)
        .into_iter()
        .filter(|u| {
            !matches!(u, ContextUse::Membership { vtc_did, persona, .. }
                if is_this(vtc_did, *persona))
        })
        .collect();
    let own_keys =
        |u: &ContextUse| matches!(u, ContextUse::PersonaKeys { persona, .. } if *persona == own);
    if uses.iter().any(|u| !own_keys(u)) {
        return Err(DeletionRefusal::InUse(uses));
    }
    let context_id = context_id.to_string();
    let record = match account.personas.get(&own) {
        Some(record) if uses.iter().any(own_keys) => record,
        _ => {
            return Ok(ContextDeletion {
                context_id,
                persona: None,
            });
        }
    };
    let name = record.label.clone().unwrap_or_else(|| record.did.clone());
    let mut persona_uses: Vec<PersonaUse> = account
        .memberships()
        .filter(|m| m.persona_ref == own && !is_this(&m.vtc_did, m.persona_ref))
        .map(|m| PersonaUse::Membership {
            name: m.display_name.clone().unwrap_or_else(|| m.vtc_did.clone()),
        })
        .collect();
    persona_uses.extend(applications.iter().filter(|a| a.persona == own).map(|a| {
        PersonaUse::VettingApplication {
            community: a.community.clone(),
        }
    }));
    if active_persona == Some(own) {
        persona_uses.push(PersonaUse::Active);
    }
    if !persona_uses.is_empty() {
        return Err(DeletionRefusal::PersonaInUse {
            name,
            uses: persona_uses,
        });
    }
    Ok(ContextDeletion {
        context_id,
        persona: Some(PersonaTakenAlong {
            persona: own,
            did: record.did.clone(),
            name,
        }),
    })
}

/// The contexts strictly beneath `context_id` among `all`, in path order.
/// Segment-aware: `openvtc/kernel-evil` is not beneath `openvtc/kernel`.
#[must_use]
pub fn descendants_of(context_id: &str, all: impl IntoIterator<Item = String>) -> Vec<String> {
    let mut below: Vec<String> = all
        .into_iter()
        .filter(|c| c != context_id && vta_sdk::context_path::is_ancestor_or_self(context_id, c))
        .collect();
    below.sort();
    below.dedup();
    below
}

/// What deleting a context would remove, as the VTA reports it: the context's
/// own resources, then each sub-context's, which the delete cascades to.
#[derive(Clone, Debug, Default)]
pub struct ContextDeletionPreview {
    /// The context being deleted.
    pub context_id: String,
    /// The VTA's preview for the context and for every sub-context beneath it,
    /// the context itself first.
    pub contexts: Vec<DeleteContextPreviewResultBody>,
}

impl ContextDeletionPreview {
    /// The sub-contexts the delete cascades to.
    pub fn sub_contexts(&self) -> impl Iterator<Item = &str> {
        self.contexts
            .iter()
            .map(|c| c.id.as_str())
            .filter(|id| *id != self.context_id)
    }

    /// Whether the subtree holds nothing but the contexts themselves.
    #[must_use]
    pub fn holds_nothing(&self) -> bool {
        self.contexts.iter().all(|c| {
            c.keys.is_empty()
                && c.webvh_dids.is_empty()
                && c.acl_entries_removed.is_empty()
                && c.acl_entries_updated.is_empty()
                && c.did_templates.is_empty()
        })
    }

    /// Everything that would be removed, one item per line, grouped by context.
    #[must_use]
    pub fn lines(&self) -> Vec<String> {
        let mut lines = Vec::new();
        for c in &self.contexts {
            lines.push(if c.id == self.context_id {
                format!("Context {}", c.id)
            } else {
                format!("Sub-context {}", c.id)
            });
            let before = lines.len();
            lines.extend(c.keys.iter().map(|k| format!("  key           {k}")));
            lines.extend(c.webvh_dids.iter().map(|d| format!("  DID           {d}")));
            lines.extend(
                c.acl_entries_removed
                    .iter()
                    .map(|s| format!("  access        {s}  (entry removed)")),
            );
            lines.extend(
                c.acl_entries_updated
                    .iter()
                    .map(|s| format!("  access        {s}  (loses this context only)")),
            );
            lines.extend(
                c.did_templates
                    .iter()
                    .map(|t| format!("  DID template  {t}")),
            );
            if lines.len() == before {
                lines.push("  nothing else".to_string());
            }
        }
        lines
    }
}

/// What has to be typed to confirm a context deletion.
pub const DELETE_CONFIRMATION: &str = "DELETE";

/// Whether `typed` confirms a deletion: exactly [`DELETE_CONFIRMATION`], so a
/// stray key or a lower-case habit never deletes anything.
#[must_use]
pub fn confirms_deletion(typed: &str) -> bool {
    typed == DELETE_CONFIRMATION
}

/// Map a VTA failure to an error that says which kind it was: the VTA could not
/// be reached, would not accept this session, or refused the request itself.
/// One message for all three sends the operator to check the network when the
/// fault is a permission, or the reverse.
pub(crate) fn vta_failure(action: &str, e: VtaError) -> OpenVTCError {
    match e {
        VtaError::Network(_) | VtaError::DidcommTransport(_) | VtaError::TspTransport(_) => {
            OpenVTCError::Vta(format!("could not reach your VTA to {action}: {e}"))
        }
        VtaError::Server { .. } => {
            OpenVTCError::Vta(format!("your VTA failed while trying to {action}: {e}"))
        }
        VtaError::Auth(_) => OpenVTCError::Auth(format!(
            "your VTA did not accept this session to {action}: {e}"
        )),
        VtaError::Forbidden(_) => OpenVTCError::Auth(format!(
            "your VTA does not allow this session to {action}: {e}"
        )),
        other => OpenVTCError::Vta(format!(
            "your VTA rejected the request to {action}: {other}"
        )),
    }
}

/// Refuse the top context, and anything outside it.
fn require_sub_context(top_context_id: &str, context_id: &str) -> Result<(), OpenVTCError> {
    if is_sub_context(context_id, top_context_id) {
        Ok(())
    } else {
        Err(OpenVTCError::Config(format!(
            "{context_id} is not a sub-context of {top_context_id}; only a community's own \
             context is deleted from here"
        )))
    }
}

/// Ask the VTA what deleting `context_id` would remove: its own preview, and
/// the preview of every sub-context beneath it (the VTA's preview covers only
/// the context named, while the delete cascades).
///
/// Either the whole subtree is previewed or the call fails — a preview missing
/// a sub-context would look complete and not be.
///
/// # Errors
///
/// The top context; the VTA unreachable or refusing any of the reads.
pub async fn preview_context_deletion(
    client: &VtaClient,
    top_context_id: &str,
    context_id: &str,
) -> Result<ContextDeletionPreview, OpenVTCError> {
    require_sub_context(top_context_id, context_id)?;
    let listing = client
        .list_contexts()
        .await
        .map_err(|e| vta_failure("list contexts", e))?;
    let below = descendants_of(context_id, listing.contexts.into_iter().map(|c| c.id));
    let mut contexts = Vec::with_capacity(below.len() + 1);
    for id in std::iter::once(context_id.to_string()).chain(below) {
        contexts.push(
            client
                .preview_delete_context(&id)
                .await
                .map_err(|e| vta_failure(&format!("preview deleting {id}"), e))?,
        );
    }
    Ok(ContextDeletionPreview {
        context_id: context_id.to_string(),
        contexts,
    })
}

/// Delete `context_id` and everything beneath it at the VTA (`force`, the
/// cascade the preview described).
///
/// # Errors
///
/// The top context; the VTA unreachable or refusing.
pub async fn delete_context(
    client: &VtaClient,
    top_context_id: &str,
    context_id: &str,
) -> Result<(), OpenVTCError> {
    require_sub_context(top_context_id, context_id)?;
    client
        .delete_context(context_id, true)
        .await
        .map_err(|e| vta_failure(&format!("delete {context_id}"), e))
}

/// What [`delete_community_context`] did.
#[derive(Debug)]
pub struct DeletionReport {
    /// The persona's `did:webvh` was removed at the VTA. True even when the
    /// context delete that follows fails: the persona is unusable either way,
    /// and the caller must forget it.
    pub persona_removed: bool,
    /// Whether the whole deletion succeeded.
    pub result: Result<(), OpenVTCError>,
}

/// Carry out `deletion`: remove the persona's `did:webvh` first, when one goes
/// with the context, then delete the context and its subtree.
///
/// The DID goes through the VTA's `webvh/dids/delete` — the removal deleting a
/// persona already uses: it revokes the credentials the VTA issued to the DID
/// and deletes its log at the hosting server. It goes first because the
/// context's cascade only drops the VTA's own record of the DID, after which
/// nothing could remove it from its host. If the VTA refuses the DID, nothing
/// is deleted.
pub async fn delete_community_context(
    client: &VtaClient,
    top_context_id: &str,
    deletion: &ContextDeletion,
) -> DeletionReport {
    if let Err(e) = require_sub_context(top_context_id, &deletion.context_id) {
        return DeletionReport {
            persona_removed: false,
            result: Err(e),
        };
    }
    let mut persona_removed = false;
    if let Some(persona) = &deletion.persona {
        match client.delete_did_webvh(&persona.did).await {
            // Already gone is what was asked for.
            Ok(()) | Err(VtaError::NotFound(_)) => persona_removed = true,
            Err(e) => {
                return DeletionReport {
                    persona_removed: false,
                    result: Err(vta_failure(
                        &format!(
                            "remove persona {}'s DID {} (nothing was deleted)",
                            persona.name, persona.did
                        ),
                        e,
                    )),
                };
            }
        }
    }
    DeletionReport {
        persona_removed,
        result: delete_context(client, top_context_id, &deletion.context_id).await,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::account::CommunityStatus;
    use chrono::Utc;
    use uuid::Uuid;

    const TOP: &str = "openvtc";

    fn persona(origin: &str) -> PersonaRecord {
        let persona_id = PersonaId::new();
        PersonaRecord {
            extra: serde_json::Map::new(),
            persona_id,
            did: format!("did:webvh:scid:example.com:{persona_id}"),
            did_document: None,
            key_refs: vec![],
            mediator_did: None,
            origin_context_id: origin.to_string(),
            created_at: Utc::now(),
            label: None,
        }
    }

    fn account() -> Account {
        Account {
            top_context_id: TOP.into(),
            ..Account::default()
        }
    }

    fn join(account: &mut Account, persona: &PersonaRecord, community: &str, context: &str) {
        account.personas.insert(persona.persona_id, persona.clone());
        account.add_membership(CommunityRecord::new_pending(
            community.into(),
            None,
            context.into(),
            persona.persona_id,
            Uuid::new_v4(),
            Utc::now(),
        ));
    }

    #[test]
    fn a_sub_context_is_strictly_below_the_top() {
        assert!(is_sub_context("openvtc/kernel", TOP));
        assert!(is_sub_context("openvtc/work/kernel", TOP));
        assert!(!is_sub_context("openvtc", TOP));
        assert!(!is_sub_context("openvtc-evil/kernel", TOP));
        assert!(!is_sub_context("openvtc/", TOP));
    }

    /// A new persona may go anywhere: a new sub-context first, then the ones in
    /// use, then the top context.
    #[test]
    fn a_new_persona_is_offered_new_existing_and_top() {
        let mut account = account();
        let work = persona("openvtc/work");
        join(&mut account, &work, "did:webvh:a", "openvtc/work");
        let options = context_options(&account, None, "openvtc/kernel");
        let kinds: Vec<_> = options.iter().map(|o| o.kind).collect();
        assert_eq!(
            kinds,
            [ContextKind::New, ContextKind::Existing, ContextKind::Top]
        );
        assert_eq!(options[1].context_id, "openvtc/work");
        assert_eq!(options[1].communities, ["did:webvh:a"]);
        assert!(options.iter().all(|o| !o.holds_persona_keys));
    }

    /// A persona's keys live in one context, so a persona minted into a
    /// sub-context can only be presented from it.
    #[test]
    fn a_persona_with_keys_in_a_sub_context_has_one_option() {
        let mut account = account();
        let work = persona("openvtc/work");
        join(&mut account, &work, "did:webvh:a", "openvtc/work");
        let options = context_options(&account, Some(&work), "openvtc/kernel");
        assert_eq!(options.len(), 1);
        assert_eq!(options[0].context_id, "openvtc/work");
        assert!(options[0].holds_persona_keys);
    }

    /// A persona from before per-community contexts keeps its keys in the top
    /// context; its faces can still go in a context of its own.
    #[test]
    fn a_legacy_persona_can_still_choose_where_its_faces_go() {
        let mut account = account();
        let legacy = persona("");
        join(&mut account, &legacy, "did:webvh:a", "openvtc/a");
        let options = context_options(&account, Some(&legacy), "openvtc/b");
        assert_eq!(options[0].kind, ContextKind::New);
        assert!(options.last().unwrap().holds_persona_keys);
        assert_eq!(options.last().unwrap().kind, ContextKind::Top);
    }

    #[test]
    fn isolation_reads_where_the_keys_are_and_who_shares() {
        let mut account = account();
        let alone = persona("openvtc/kernel");
        join(&mut account, &alone, "did:webvh:k", "openvtc/kernel");
        let shared = persona("openvtc/work");
        join(&mut account, &shared, "did:webvh:w1", "openvtc/work");
        join(&mut account, &shared, "did:webvh:w2", "openvtc/work");
        let legacy = persona("");
        join(&mut account, &legacy, "did:webvh:l", "openvtc/legacy");
        join(&mut account, &legacy, "did:webvh:t", TOP);

        let of = |vtc: &str| {
            let m = account.memberships().find(|m| m.vtc_did == vtc).unwrap();
            isolation(&account, m)
        };
        assert_eq!(of("did:webvh:k"), Isolation::Isolated);
        assert_eq!(of("did:webvh:w1"), Isolation::Shared(1));
        assert_eq!(of("did:webvh:l"), Isolation::KeysElsewhere);
        assert_eq!(of("did:webvh:t"), Isolation::Top);
    }

    #[test]
    fn a_new_context_must_be_new_and_well_formed() {
        let taken = |id: &str| id == "openvtc/work";
        assert_eq!(
            new_context_id(TOP, "kernel", taken).unwrap(),
            "openvtc/kernel"
        );
        assert!(new_context_id(TOP, "work", taken).is_err());
        assert!(new_context_id(TOP, "a/b", taken).is_err());
        assert!(new_context_id(TOP, "", taken).is_err());
    }

    fn end(account: &mut Account, community: &str) {
        let persona = account
            .memberships()
            .find(|m| m.vtc_did == community)
            .map(|m| m.persona_ref)
            .unwrap();
        account.membership_mut(community, persona).unwrap().status = CommunityStatus::Left;
    }

    fn membership<'a>(account: &'a Account, community: &str) -> &'a CommunityRecord {
        account
            .memberships()
            .find(|m| m.vtc_did == community)
            .unwrap()
    }

    fn application(persona: PersonaId, community: &str, context: &str) -> Application {
        let mut book = crate::vetting::VettingBook::default();
        let app = book
            .start_application(community, persona, "did:webvh:join", Utc::now())
            .unwrap();
        app.context_id = Some(context.to_string());
        book.applications.remove(0)
    }

    /// A context whose only user is the membership that is over, holding a
    /// legacy persona's faces, may be deleted.
    #[test]
    fn a_finished_membership_alone_in_its_context_may_delete_it() {
        let mut account = account();
        let legacy = persona("");
        join(&mut account, &legacy, "did:webvh:k", "openvtc/kernel");
        end(&mut account, "did:webvh:k");
        assert_eq!(
            deletable_context(&account, &[], None, membership(&account, "did:webvh:k")),
            Ok(ContextDeletion {
                context_id: "openvtc/kernel".into(),
                persona: None,
            })
        );
    }

    #[test]
    fn a_live_membership_or_the_top_context_is_never_deleted() {
        let mut account = account();
        let legacy = persona("");
        join(&mut account, &legacy, "did:webvh:k", "openvtc/kernel");
        join(&mut account, &legacy, "did:webvh:t", TOP);
        assert_eq!(
            deletable_context(&account, &[], None, membership(&account, "did:webvh:k")),
            Err(DeletionRefusal::StillLive)
        );
        end(&mut account, "did:webvh:t");
        assert_eq!(
            deletable_context(&account, &[], None, membership(&account, "did:webvh:t")),
            Err(DeletionRefusal::TopContext)
        );
    }

    /// Everything else that uses the context is named: another membership, the
    /// persona whose keys were minted there, a vetting application.
    #[test]
    fn every_other_use_of_the_context_is_named_in_the_refusal() {
        let mut account = account();
        let minted = persona("openvtc/kernel");
        let legacy = persona("");
        join(&mut account, &minted, "did:webvh:k", "openvtc/kernel");
        join(&mut account, &legacy, "did:webvh:k2", "openvtc/kernel");
        end(&mut account, "did:webvh:k");
        let applications = [application(
            legacy.persona_id,
            "did:webvh:v",
            "openvtc/kernel",
        )];

        let Err(DeletionRefusal::InUse(uses)) = deletable_context(
            &account,
            &applications,
            None,
            membership(&account, "did:webvh:k"),
        ) else {
            panic!("the context is in use");
        };
        assert!(
            !uses.iter().any(
                |u| matches!(u, ContextUse::Membership { vtc_did, .. } if vtc_did == "did:webvh:k")
            ),
            "the membership being cleaned up is not a use of its own context"
        );
        assert!(uses.iter().any(
            |u| matches!(u, ContextUse::Membership { vtc_did, .. } if vtc_did == "did:webvh:k2")
        ));
        assert!(uses.iter().any(
            |u| matches!(u, ContextUse::PersonaKeys { persona, .. } if *persona == minted.persona_id)
        ));
        assert!(
            uses.iter()
                .any(|u| matches!(u, ContextUse::VettingApplication { .. }))
        );
        let text = DeletionRefusal::InUse(uses).describe();
        assert!(
            text.contains("did:webvh:k2") && text.contains("did:webvh:v"),
            "{text}"
        );
    }

    /// Joining mints the persona into the community's context. Once that
    /// membership is over and is the persona's only use, the persona goes with
    /// the context — and the preview says so, naming its DID.
    #[test]
    fn a_persona_whose_only_use_is_the_finished_membership_goes_with_its_context() {
        let mut account = account();
        let minted = persona("openvtc/kernel");
        join(&mut account, &minted, "did:webvh:k", "openvtc/kernel");
        end(&mut account, "did:webvh:k");

        let deletion = deletable_context(&account, &[], None, membership(&account, "did:webvh:k"))
            .expect("the persona has no other use");
        assert_eq!(deletion.context_id, "openvtc/kernel");
        assert_eq!(
            deletion.persona,
            Some(PersonaTakenAlong {
                persona: minted.persona_id,
                did: minted.did.clone(),
                name: minted.did.clone(),
            })
        );
        let text = deletion.consequences("Kernel").join("\n");
        for item in [
            "Persona",
            minted.did.as_str(),
            "can no longer be used anywhere",
            "stays published there",
            "finished membership of Kernel",
            "record is removed",
        ] {
            assert!(text.contains(item), "missing {item:?} in\n{text}");
        }
    }

    /// Anything else using the persona keeps it, and the context holding its
    /// keys: another membership of any status, a vetting application wherever
    /// its face is worn, or being the active persona. The refusal says which.
    #[test]
    fn a_persona_used_by_anything_else_keeps_its_context() {
        let minted = persona("openvtc/kernel");
        let finished = |extra: &dyn Fn(&mut Account)| {
            let mut account = account();
            join(&mut account, &minted, "did:webvh:k", "openvtc/kernel");
            extra(&mut account);
            end(&mut account, "did:webvh:k");
            account
        };

        let another = finished(&|account| {
            join(account, &minted, "did:webvh:w", "openvtc/work");
            end(account, "did:webvh:w");
        });
        let refusal = deletable_context(&another, &[], None, membership(&another, "did:webvh:k"))
            .unwrap_err();
        assert_eq!(
            refusal,
            DeletionRefusal::PersonaInUse {
                name: minted.did.clone(),
                uses: vec![PersonaUse::Membership {
                    name: "did:webvh:w".into()
                }],
            }
        );
        assert!(refusal.describe().contains("did:webvh:w"));

        let alone = finished(&|_| {});
        let applications = [application(
            minted.persona_id,
            "did:webvh:v",
            "openvtc/elsewhere",
        )];
        assert!(matches!(
            deletable_context(&alone, &applications, None, membership(&alone, "did:webvh:k")),
            Err(DeletionRefusal::PersonaInUse { uses, .. })
                if uses == [PersonaUse::VettingApplication { community: "did:webvh:v".into() }]
        ));

        let refusal = deletable_context(
            &alone,
            &[],
            Some(minted.persona_id),
            membership(&alone, "did:webvh:k"),
        )
        .unwrap_err();
        assert!(matches!(
            &refusal,
            DeletionRefusal::PersonaInUse { uses, .. } if uses == &[PersonaUse::Active]
        ));
        assert!(refusal.describe().contains("active persona"));
    }

    /// Only the membership's own persona is ever taken along; another
    /// persona's keys in the context refuse the deletion.
    #[test]
    fn another_personas_keys_are_never_taken_along() {
        let mut account = account();
        let legacy = persona("");
        join(&mut account, &legacy, "did:webvh:k", "openvtc/kernel");
        end(&mut account, "did:webvh:k");
        let other = persona("openvtc/kernel");
        account.personas.insert(other.persona_id, other.clone());

        let Err(DeletionRefusal::InUse(uses)) =
            deletable_context(&account, &[], None, membership(&account, "did:webvh:k"))
        else {
            panic!("another persona's keys are a use");
        };
        assert!(matches!(
            uses.as_slice(),
            [ContextUse::PersonaKeys { persona, .. }] if *persona == other.persona_id
        ));
    }

    #[test]
    fn a_context_without_a_persona_keeps_the_membership() {
        let deletion = ContextDeletion {
            context_id: "openvtc/kernel".into(),
            persona: None,
        };
        assert_eq!(
            deletion.consequences("Kernel"),
            ["Your finished membership of Kernel is kept, without a context."]
        );
    }

    #[test]
    fn a_claimed_context_includes_vetting_applications() {
        let account = account();
        let applications = [application(PersonaId::new(), "did:webvh:v", "openvtc/v")];
        assert!(context_claimed(&account, &applications, "openvtc/v"));
        assert!(!context_claimed(&account, &applications, "openvtc/w"));
    }

    #[test]
    fn descendants_are_segment_aware_and_exclude_the_context() {
        let all = [
            "openvtc",
            "openvtc/kernel",
            "openvtc/kernel/ci",
            "openvtc/kernel/ci/nightly",
            "openvtc/kernel-evil",
            "other/kernel",
        ]
        .map(String::from);
        assert_eq!(
            descendants_of("openvtc/kernel", all),
            ["openvtc/kernel/ci", "openvtc/kernel/ci/nightly"]
        );
    }

    #[test]
    fn a_preview_lists_every_item_under_its_context() {
        let preview = ContextDeletionPreview {
            context_id: "openvtc/kernel".into(),
            contexts: vec![
                DeleteContextPreviewResultBody {
                    id: "openvtc/kernel".into(),
                    keys: vec!["key-1".into()],
                    webvh_dids: vec!["did:webvh:scid:host:p".into()],
                    acl_entries_removed: vec!["did:key:zDevice".into()],
                    acl_entries_updated: vec!["did:key:zWide".into()],
                    did_templates: vec![],
                    sub_contexts: vec![],
                },
                DeleteContextPreviewResultBody {
                    id: "openvtc/kernel/ci".into(),
                    ..Default::default()
                },
            ],
        };
        assert_eq!(
            preview.sub_contexts().collect::<Vec<_>>(),
            ["openvtc/kernel/ci"]
        );
        assert!(!preview.holds_nothing());
        let lines = preview.lines().join("\n");
        for item in [
            "Context openvtc/kernel",
            "key-1",
            "did:webvh:scid:host:p",
            "did:key:zDevice  (entry removed)",
            "did:key:zWide  (loses this context only)",
            "Sub-context openvtc/kernel/ci",
            "nothing else",
        ] {
            assert!(lines.contains(item), "missing {item:?} in\n{lines}");
        }
    }

    #[test]
    fn only_the_exact_word_confirms() {
        assert!(confirms_deletion("DELETE"));
        for typed in ["", "delete", "DELET", "DELETE ", " DELETE"] {
            assert!(!confirms_deletion(typed), "{typed:?}");
        }
    }

    #[test]
    fn a_persona_label_suggests_its_own_context() {
        let taken = |id: &str| id == "openvtc/work";
        assert_eq!(
            suggested_context_id(TOP, "Work", "persona", taken).unwrap(),
            "openvtc/work-2"
        );
        assert_eq!(
            suggested_context_id(TOP, "日本", "persona", taken).unwrap(),
            "openvtc/persona"
        );
    }

    /// The top context and anything outside the account are refused before
    /// the VTA is asked.
    #[test]
    fn only_a_sub_context_is_previewed_or_deleted() {
        assert!(require_sub_context(TOP, TOP).is_err());
        assert!(require_sub_context(TOP, "elsewhere/kernel").is_err());
        assert!(require_sub_context(TOP, "openvtc/kernel").is_ok());
    }

    /// Unreachable, not accepted, and refused read differently.
    #[test]
    fn a_vta_failure_says_which_kind_it_was() {
        let unreachable = vta_failure("x", VtaError::DidcommTransport("timeout".into()));
        assert!(matches!(unreachable, OpenVTCError::Vta(ref m) if m.contains("could not reach")));
        let auth = vta_failure("x", VtaError::Auth("expired".into()));
        assert!(matches!(auth, OpenVTCError::Auth(ref m) if m.contains("did not accept")));
        let forbidden = vta_failure("x", VtaError::Forbidden("no".into()));
        assert!(matches!(forbidden, OpenVTCError::Auth(ref m) if m.contains("does not allow")));
        let rejected = vta_failure("x", VtaError::Validation("bad".into()));
        assert!(matches!(rejected, OpenVTCError::Vta(ref m) if m.contains("rejected")));
    }

    #[test]
    fn an_option_reads_as_a_line() {
        let option = ContextOption {
            context_id: "openvtc/work".into(),
            kind: ContextKind::Existing,
            communities: vec!["a".into(), "b".into()],
            holds_persona_keys: false,
        };
        assert_eq!(
            option.summary(),
            "openvtc/work  (shared with 2 communities)"
        );
    }
}