daaki-imap 0.1.0

An IMAP4rev1/IMAP4rev2 async client library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
//! IMAP server response types (RFC 3501 Section 7 / RFC 9051 Section 7).
//!
//! Models the full grammar of IMAP responses: greeting, tagged, untagged, and continuation.
//! Extended response codes per RFC 5530.

use super::{FetchResponse, Flag, MailboxInfo, StatusItem};

/// A complete response line from the IMAP server
/// (RFC 3501 Section 2.2.2 / RFC 9051 Section 2.2.2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Response {
    /// Initial server greeting on connection (RFC 3501 Section 7.1).
    Greeting(GreetingResponse),
    /// Tagged response to a client command (RFC 3501 Section 2.2.2).
    Tagged(TaggedResponse),
    /// Untagged (unsolicited or data) response (RFC 3501 Section 2.2.2).
    Untagged(Box<UntaggedResponse>),
    /// Continuation request (`+ ...`) (RFC 3501 Section 7.5).
    Continuation(ContinuationRequest),
}

/// Initial greeting sent by the server upon connection
/// (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GreetingResponse {
    /// Greeting status (`OK`, `PREAUTH`, or `BYE`) (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
    pub status: GreetingStatus,
    /// Optional response code in square brackets (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
    pub code: Option<ResponseCode>,
    /// Human-readable text following the status (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
    pub text: String,
}

/// Status of the server greeting (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GreetingStatus {
    /// `* OK` — server ready, client should authenticate.
    Ok,
    /// `* PREAUTH` — already authenticated (e.g. via TLS client cert).
    PreAuth,
    /// `* BYE` — server refusing connections.
    Bye,
}

/// Tagged response (response to a specific client command)
/// (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaggedResponse {
    /// Command tag that this response corresponds to (RFC 3501 Section 2.2.1 / RFC 9051 Section 2.2.1).
    pub tag: String,
    /// Completion status (`OK`, `NO`, or `BAD`) (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
    pub status: StatusKind,
    /// Optional response code in square brackets (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
    pub code: Option<ResponseCode>,
    /// Human-readable text following the status (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
    pub text: String,
}

impl TaggedResponse {
    /// Check that the response indicates `OK` status. On success returns the
    /// response itself so callers can still access fields like `code`. On
    /// failure returns an appropriate [`Error`] for `NO` / `BAD`.
    ///
    /// RFC 3501 Section 7.1 / RFC 9051 Section 7.1: `OK` indicates success,
    /// `NO` an operational error, `BAD` a protocol-level error.
    pub(crate) fn require_ok(self) -> Result<Self, crate::error::Error> {
        match self.status {
            StatusKind::Ok => Ok(self),
            StatusKind::No => Err(crate::error::Error::no_with_code(self.text, self.code)),
            StatusKind::Bad => Err(crate::error::Error::bad_with_code(self.text, self.code)),
        }
    }
}

/// Status of a tagged response (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatusKind {
    Ok,
    No,
    Bad,
}

/// Status of an untagged status response (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UntaggedStatus {
    Ok,
    No,
    Bad,
    Bye,
}

/// Untagged server response (RFC 3501 Section 7 / RFC 9051 Section 7).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UntaggedResponse {
    /// `* OK/NO/BAD/BYE [code] text` (RFC 3501 Section 7.1).
    Status {
        status: UntaggedStatus,
        code: Option<ResponseCode>,
        text: String,
    },
    /// `* <n> EXISTS` (RFC 3501 Section 7.3.1).
    Exists(u32),
    /// `* <n> RECENT` (RFC 3501 Section 7.3.2).
    Recent(u32),
    /// `* <n> EXPUNGE` (RFC 3501 Section 7.4.1).
    Expunge(u32),
    /// `* <n> FETCH (...)` (RFC 3501 Section 7.4.2).
    Fetch(Box<FetchResponse>),
    /// `* LIST (\attrs) "/" "name"` (RFC 3501 Section 7.2.2).
    List(MailboxInfo),
    /// `* LSUB (\attrs) "/" "name"` (RFC 3501 Section 7.2.3).
    Lsub(MailboxInfo),
    /// `* FLAGS (...)` (RFC 3501 Section 7.2.6).
    Flags(Vec<Flag>),
    /// `* SEARCH 1 2 3 ... [(MODSEQ n)]` (RFC 3501 Section 7.2.5, RFC 7162 Section 3.1.5).
    ///
    /// The optional `mod_seq` is present when the client searched with a MODSEQ
    /// criterion and the result is non-empty (RFC 7162 Section 3.1.5).
    Search {
        /// Matching message sequence numbers or UIDs.
        uids: Vec<u32>,
        /// Highest mod-sequence of matching messages (RFC 7162 Section 3.1.5).
        mod_seq: Option<u64>,
    },
    /// `* ESEARCH (TAG "tag") [UID] result-data` (RFC 4731 Section 3.1).
    ///
    /// RFC 4731 Section 3.1 ABNF:
    /// `search-return-data = "MIN" SP nz-number / "MAX" SP nz-number /
    ///                        "ALL" SP sequence-set / "COUNT" SP number`
    Esearch(EsearchResponse),
    /// `* STATUS "mailbox" (...)` (RFC 3501 Section 7.2.4).
    MailboxStatus {
        mailbox: String,
        items: Vec<StatusItem>,
    },
    /// `* CAPABILITY ...` (RFC 3501 Section 7.2.1).
    Capability(Vec<Capability>),
    /// `* ENABLED ...` (RFC 5161 Section 3.2).
    Enabled(Vec<String>),
    /// `* VANISHED (EARLIER) 1:5` (RFC 7162 QRESYNC).
    Vanished { earlier: bool, uids: Vec<UidRange> },
    /// `* ID (...)` (RFC 2971 Section 3.2).
    Id(Vec<(String, Option<String>)>),
    /// `* NAMESPACE personal other shared` (RFC 2342).
    Namespace {
        personal: Vec<NamespaceDescriptor>,
        other: Vec<NamespaceDescriptor>,
        shared: Vec<NamespaceDescriptor>,
    },

    // --- QUOTA (RFC 2087) ---
    /// `* QUOTA <root> (STORAGE <usage> <limit>)` (RFC 2087 Section 5.1).
    Quota {
        root: String,
        resources: Vec<QuotaResource>,
    },
    /// `* QUOTAROOT <mailbox> <root1> <root2> ...` (RFC 2087 Section 5.2).
    QuotaRoot { mailbox: String, roots: Vec<String> },

    // --- ACL (RFC 4314) ---
    /// `* ACL <mailbox> <id1> <rights1> ...` (RFC 4314 Section 3.6).
    Acl {
        mailbox: String,
        entries: Vec<AclEntry>,
    },
    /// `* MYRIGHTS <mailbox> <rights>` (RFC 4314 Section 3.8).
    MyRights { mailbox: String, rights: String },
    /// `* LISTRIGHTS <mailbox> <id> <required> <optional1> ...` (RFC 4314 Section 3.7).
    ListRights {
        mailbox: String,
        identifier: String,
        required: String,
        optional: Vec<String>,
    },
    /// `* METADATA "mailbox" (entry1 value1 ...)` (RFC 5464 Section 4.4).
    Metadata {
        mailbox: String,
        entries: Vec<MetadataEntry>,
    },
    /// `* THREAD (...)` (RFC 5256 Section 4).
    Thread(Vec<ThreadNode>),
    /// SORT response — sorted message numbers and optional MODSEQ
    /// (RFC 5256 Section 4, RFC 7162 Section 3.1.6).
    ///
    /// RFC 7162 Section 3.1.6: when a MODSEQ search criterion is used and the
    /// SORT result is non-empty, the server appends `(MODSEQ <n>)`.
    Sort {
        /// Sorted message numbers or UIDs (RFC 5256 Section 4).
        nums: Vec<u32>,
        /// Highest mod-sequence value of matching messages (RFC 7162 Section 3.1.6).
        mod_seq: Option<u64>,
    },
    /// Unknown or unrecognized untagged response (RFC 9051 Section 2.2.2).
    ///
    /// Servers may send extension responses that this client does not yet
    /// implement. Per RFC 9051, clients MUST tolerate such responses.
    Unknown(String),
}

/// Continuation request from the server (RFC 3501 Section 7.5 / RFC 9051 Section 7.5).
///
/// RFC 3501 Section 7.5: `continue-req = "+" SP (resp-text / base64) CRLF`
/// where `resp-text = ["[" resp-text-code "]" SP] text`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContinuationRequest {
    /// Optional response code in square brackets (RFC 3501 Section 7.5 / RFC 9051 Section 7.5).
    ///
    /// Present when the server sends a continuation like `+ [ALERT] text\r\n`.
    /// Base64 SASL challenges never start with `[`, so this is `None` for those.
    pub code: Option<ResponseCode>,
    /// Text or base64 challenge from the server
    /// (RFC 3501 Section 7.5 / RFC 9051 Section 7.5.1).
    pub data: String,
}

/// Response code in square brackets (e.g. `[UIDVALIDITY 12345]`)
/// (RFC 3501 Section 7.1 / RFC 9051 Section 7.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResponseCode {
    /// `[ALERT]` — must be presented to the user (RFC 3501 Section 7.1).
    Alert,
    /// `[BADCHARSET (charsets)]` — search charset not supported (RFC 3501 Section 7.1).
    BadCharset(Vec<String>),
    /// `[CAPABILITY ...]` — capability list (RFC 3501 Section 7.1).
    Capability(Vec<Capability>),
    /// `[PARSE]` — message headers could not be parsed (RFC 3501 Section 7.1).
    Parse,
    /// `[PERMANENTFLAGS (flags)]` — flags the client can change permanently (RFC 3501 Section 7.1).
    PermanentFlags(Vec<Flag>),
    /// `[READ-ONLY]` — mailbox is read-only (RFC 3501 Section 7.1).
    ReadOnly,
    /// `[READ-WRITE]` — mailbox is read-write (RFC 3501 Section 7.1).
    ReadWrite,
    /// `[TRYCREATE]` — attempt to CREATE the target mailbox (RFC 3501 Section 7.1).
    TryCreate,
    /// `[UIDNEXT n]` — predicted next UID (RFC 3501 Section 7.1).
    UidNext(u32),
    /// `[UIDVALIDITY n]` — UID validity value (RFC 3501 Section 7.1).
    UidValidity(u32),
    /// `[UNSEEN n]` — first unseen message sequence number (RFC 3501 Section 7.1).
    Unseen(u32),
    /// `[APPENDUID uidvalidity uid-set]` (RFC 4315 UIDPLUS Section 3).
    ///
    /// For a single APPEND, `uids` contains one range. For MULTIAPPEND
    /// (RFC 3502), `uids` may contain multiple ranges.
    AppendUid {
        uid_validity: u32,
        uids: Vec<UidRange>,
    },
    /// `[COPYUID uidvalidity source-uids dest-uids]` (RFC 4315 UIDPLUS).
    CopyUid {
        uid_validity: u32,
        source_uids: Vec<UidRange>,
        dest_uids: Vec<UidRange>,
    },
    /// `[HIGHESTMODSEQ n]` (RFC 7162 CONDSTORE).
    HighestModSeq(u64),
    /// `[MODIFIED uid-set]` (RFC 7162 CONDSTORE).
    Modified(Vec<UidRange>),
    /// `[NOMODSEQ]` — mailbox does not support mod-sequences (RFC 7162 Section 3.1.2).
    NoModSeq,
    /// `[CLOSED]` — previously selected mailbox is now closed (RFC 7162 QRESYNC).
    Closed,
    /// `[MAILBOXID (objectid)]` — unique mailbox identifier (RFC 8474 Section 5.1).
    MailboxId(String),

    // --- RFC 5530 extended response codes ---
    /// `[UNAVAILABLE]` — server temporarily unavailable (RFC 5530 Section 3).
    Unavailable,
    /// `[AUTHENTICATIONFAILED]` — authentication credentials invalid (RFC 5530 Section 3).
    AuthenticationFailed,
    /// `[AUTHORIZATIONFAILED]` — authorization identity not permitted (RFC 5530 Section 3).
    AuthorizationFailed,
    /// `[EXPIRED]` — credentials have expired (RFC 5530 Section 3).
    Expired,
    /// `[PRIVACYREQUIRED]` — operation requires encryption (RFC 5530 Section 3).
    PrivacyRequired,
    /// `[CONTACTADMIN]` — contact server administrator (RFC 5530 Section 3).
    ContactAdmin,
    /// `[NOPERM]` — no permission to perform the operation (RFC 5530 Section 3).
    NoPerm,
    /// `[INUSE]` — resource is in use by another session (RFC 5530 Section 3).
    InUse,
    /// `[EXPUNGEISSUED]` — expunge occurred during operation (RFC 5530 Section 3).
    ExpungeIssued,
    /// `[CORRUPTION]` — server detected data corruption (RFC 5530 Section 3).
    Corruption,
    /// `[SERVERBUG]` — server encountered an internal bug (RFC 5530 Section 3).
    ServerBug,
    /// `[CLIENTBUG]` — client sent malformed or nonsensical data (RFC 5530 Section 3).
    ClientBug,
    /// `[CANNOT]` — operation is not supported on this mailbox/server (RFC 5530 Section 3).
    Cannot,
    /// `[LIMIT]` — operation exceeds a server-imposed limit (RFC 5530 Section 3).
    Limit,
    /// `[OVERQUOTA]` — user has exceeded their storage quota (RFC 5530 Section 3).
    OverQuota,
    /// `[ALREADYEXISTS]` — mailbox already exists (e.g. on CREATE) (RFC 5530 Section 3).
    AlreadyExists,
    /// `[NONEXISTENT]` — mailbox does not exist (e.g. on SELECT/DELETE) (RFC 5530 Section 3).
    NonExistent,

    /// `[UIDNOTSTICKY]` — assigned UIDs are not persistent (RFC 4315 Section 2 / RFC 9051 Section 7.1).
    UidNotSticky,
    /// `[NOTSAVED]` — search result variable `$` is empty (RFC 5182 Section 2.1).
    NotSaved,
    /// `[HASCHILDREN]` — mailbox has child mailboxes (RFC 9051 Section 7.1).
    HasChildren,
    /// `[UNKNOWN-CTE]` — BINARY fetch failed due to unknown CTE (RFC 3516 Section 4.3).
    UnknownCte,
    /// `[TOOBIG]` — message too large for APPEND (RFC 7889 Section 4).
    TooBig,
    /// `[COMPRESSIONACTIVE]` — compression layer already active (RFC 4978 Section 3).
    CompressionActive,
    /// `[USEATTR]` — special-use attribute not supported (RFC 6154 Section 6).
    UseAttr,

    // --- METADATA (RFC 5464) ---
    /// `[METADATA LONGENTRIES n]` — entry values were truncated at `n` bytes
    /// (RFC 5464 Section 4.2.1).
    MetadataLongEntries(u64),
    /// `[METADATA MAXSIZE n]` — server's maximum annotation size
    /// (RFC 5464 Section 4.3).
    MetadataMaxSize(u64),
    /// `[METADATA TOOMANY]` — too many annotations on this mailbox
    /// (RFC 5464 Section 4.3).
    MetadataTooMany,
    /// `[METADATA NOPRIVATE]` — server does not support private annotations
    /// (RFC 5464 Section 4.3).
    MetadataNoPrivate,

    /// Unrecognized response code — preserved for forward compatibility.
    Other { name: String, value: Option<String> },
}

/// Server capability (RFC 3501 Section 7.2.1 / RFC 9051 Section 7.2.1).
#[derive(Debug, Clone)]
pub enum Capability {
    /// `IMAP4rev1` (RFC 3501).
    Imap4Rev1,
    /// `IMAP4rev2` (RFC 9051).
    Imap4Rev2,
    // --- Extensions (alphabetical) ---
    /// `ACL` (RFC 4314).
    Acl,
    /// `APPENDLIMIT` (RFC 7889 Section 5).
    AppendLimit(Option<u64>),
    /// `BINARY` (RFC 3516).
    Binary,
    /// `CHILDREN` (RFC 3348).
    Children,
    /// `COMPRESS=DEFLATE` (RFC 4978).
    CompressDeflate,
    /// `CONDSTORE` (RFC 7162).
    Condstore,
    /// `CREATE-SPECIAL-USE` (RFC 6154).
    CreateSpecialUse,
    /// `ENABLE` (RFC 5161).
    Enable,
    /// `ESEARCH` (RFC 4731).
    Esearch,
    /// `ID` (RFC 2971).
    Id,
    /// `IDLE` (RFC 2177).
    Idle,
    /// `LIST-EXTENDED` (RFC 5258).
    ListExtended,
    /// `LIST-STATUS` (RFC 5819).
    ListStatus,
    /// `LITERAL+` (RFC 7888).
    LiteralPlus,
    /// `LOGINDISABLED` (RFC 3501 Section 6.2.3 / RFC 9051 Section 6.2.3).
    LoginDisabled,
    /// LITERAL- extension — non-synchronizing literals up to 4096 bytes (RFC 7888 Section 5).
    LiteralMinus,
    /// `METADATA` (RFC 5464).
    Metadata,
    /// `METADATA-SERVER` — server-only metadata annotations (RFC 5464 Section 1).
    MetadataServer,
    /// `MOVE` (RFC 6851).
    Move,
    /// `MULTIAPPEND` (RFC 3502).
    MultiAppend,
    /// `NAMESPACE` (RFC 2342).
    Namespace,
    /// `OBJECTID` (RFC 8474).
    ObjectId,
    /// `QRESYNC` (RFC 7162).
    QResync,
    /// `QUOTA` (RFC 2087).
    Quota,
    /// `RIGHTS=<chars>` — indicates supported ACL rights (RFC 4314 Section 6).
    ///
    /// The `String` holds the new-rights characters (e.g. `"texk"`).
    Rights(String),
    /// `PREVIEW` (RFC 8970 Section 4).
    Preview,
    /// `SASL-IR` (RFC 4959).
    SaslIr,
    /// `SAVEDATE` (RFC 8514).
    SaveDate,
    /// `SEARCHRES` (RFC 5182).
    SearchRes,
    /// SORT extension (RFC 5256 Section 1).
    Sort,
    /// `SORT=DISPLAY` extension (RFC 5957).
    SortDisplay(String),
    /// `STARTTLS` (RFC 3501 Section 6.2.1 / RFC 9051 Section 6.2.1).
    StartTls,
    /// `SPECIAL-USE` (RFC 6154).
    SpecialUse,
    /// `THREAD=<algorithm>` (RFC 5256 Section 1).
    ///
    /// The String holds the algorithm name (e.g. `"REFERENCES"`, `"ORDEREDSUBJECT"`).
    /// Servers may advertise multiple `THREAD=` capabilities, each as a separate entry.
    Thread(String),
    /// `STATUS=SIZE` (RFC 8438).
    StatusSize,
    /// `UIDPLUS` (RFC 4315).
    UidPlus,
    /// `UNAUTHENTICATE` (RFC 8437 Section 2).
    Unauthenticate,
    /// `UNSELECT` (RFC 3691).
    Unselect,
    /// `UTF8=ACCEPT` (RFC 6855).
    Utf8Accept,
    /// `UTF8=ONLY` (RFC 6855 Section 4).
    Utf8Only,
    /// `WITHIN` (RFC 5032 Section 3).
    ///
    /// Enables OLDER and YOUNGER search keys for time-relative searches.
    Within,
    /// `AUTH=<mechanism>` (e.g. `AUTH=PLAIN`, `AUTH=XOAUTH2`) (RFC 3501 Section 7.2.1).
    Auth(String),
    /// Unrecognized capability — preserved verbatim.
    Other(String),
}

impl Capability {
    /// Returns the wire representation of this capability
    /// (e.g. `IDLE`, `AUTH=PLAIN`, `THREAD=REFERENCES`)
    /// (RFC 3501 Section 7.2.1 / RFC 9051 Section 7.2.1).
    ///
    /// For `AppendLimit(Some(n))` returns `APPENDLIMIT=n`; for `AppendLimit(None)`
    /// returns `APPENDLIMIT`.
    pub fn as_imap_str(&self) -> String {
        match self {
            Self::Imap4Rev1 => "IMAP4rev1".to_owned(),
            Self::Imap4Rev2 => "IMAP4rev2".to_owned(),
            Self::Acl => "ACL".to_owned(),
            Self::AppendLimit(Some(n)) => format!("APPENDLIMIT={n}"),
            Self::AppendLimit(None) => "APPENDLIMIT".to_owned(),
            Self::Binary => "BINARY".to_owned(),
            Self::Children => "CHILDREN".to_owned(),
            Self::CompressDeflate => "COMPRESS=DEFLATE".to_owned(),
            Self::Condstore => "CONDSTORE".to_owned(),
            Self::CreateSpecialUse => "CREATE-SPECIAL-USE".to_owned(),
            Self::Enable => "ENABLE".to_owned(),
            Self::Esearch => "ESEARCH".to_owned(),
            Self::Id => "ID".to_owned(),
            Self::Idle => "IDLE".to_owned(),
            Self::ListExtended => "LIST-EXTENDED".to_owned(),
            Self::ListStatus => "LIST-STATUS".to_owned(),
            Self::LiteralPlus => "LITERAL+".to_owned(),
            Self::LoginDisabled => "LOGINDISABLED".to_owned(),
            Self::LiteralMinus => "LITERAL-".to_owned(),
            Self::Metadata => "METADATA".to_owned(),
            Self::MetadataServer => "METADATA-SERVER".to_owned(),
            Self::Move => "MOVE".to_owned(),
            Self::MultiAppend => "MULTIAPPEND".to_owned(),
            Self::Namespace => "NAMESPACE".to_owned(),
            Self::ObjectId => "OBJECTID".to_owned(),
            Self::Preview => "PREVIEW".to_owned(),
            Self::QResync => "QRESYNC".to_owned(),
            Self::Quota => "QUOTA".to_owned(),
            Self::Rights(s) => format!("RIGHTS={s}"),
            Self::SaslIr => "SASL-IR".to_owned(),
            Self::SaveDate => "SAVEDATE".to_owned(),
            Self::SearchRes => "SEARCHRES".to_owned(),
            Self::Sort => "SORT".to_owned(),
            Self::SortDisplay(s) => format!("SORT={s}"),
            Self::StartTls => "STARTTLS".to_owned(),
            Self::SpecialUse => "SPECIAL-USE".to_owned(),
            Self::Thread(s) => format!("THREAD={s}"),
            Self::StatusSize => "STATUS=SIZE".to_owned(),
            Self::Unauthenticate => "UNAUTHENTICATE".to_owned(),
            Self::UidPlus => "UIDPLUS".to_owned(),
            Self::Unselect => "UNSELECT".to_owned(),
            Self::Within => "WITHIN".to_owned(),
            Self::Utf8Accept => "UTF8=ACCEPT".to_owned(),
            Self::Utf8Only => "UTF8=ONLY".to_owned(),
            Self::Auth(s) => format!("AUTH={s}"),
            Self::Other(s) => s.clone(),
        }
    }
}

/// RFC 3501 Section 7.2.1: "There is no requirement that capability names be
/// registered" — capability names are atoms and IMAP atoms are case-insensitive.
///
/// Known capability variants with no string payload compare by discriminant.
/// String-carrying variants (`Auth`, `Thread`, `SortDisplay`, `Rights`, `Other`)
/// compare using ASCII case-insensitive comparison so that e.g.
/// `Auth("PLAIN")` and `Auth("plain")` are treated as the same capability.
///
/// Cross-representation is also handled: `Other("IDLE")` equals `Idle`,
/// because they denote the same protocol capability.
impl PartialEq for Capability {
    fn eq(&self, other: &Self) -> bool {
        // RFC 3501 Section 7.2.1: capability comparisons are case-insensitive.
        match (self, other) {
            (Self::Imap4Rev1, Self::Imap4Rev1)
            | (Self::Imap4Rev2, Self::Imap4Rev2)
            | (Self::Acl, Self::Acl)
            | (Self::Binary, Self::Binary)
            | (Self::Children, Self::Children)
            | (Self::CompressDeflate, Self::CompressDeflate)
            | (Self::Condstore, Self::Condstore)
            | (Self::CreateSpecialUse, Self::CreateSpecialUse)
            | (Self::Enable, Self::Enable)
            | (Self::Esearch, Self::Esearch)
            | (Self::Id, Self::Id)
            | (Self::Idle, Self::Idle)
            | (Self::ListExtended, Self::ListExtended)
            | (Self::ListStatus, Self::ListStatus)
            | (Self::LiteralPlus, Self::LiteralPlus)
            | (Self::LoginDisabled, Self::LoginDisabled)
            | (Self::LiteralMinus, Self::LiteralMinus)
            | (Self::Metadata, Self::Metadata)
            | (Self::MetadataServer, Self::MetadataServer)
            | (Self::Move, Self::Move)
            | (Self::MultiAppend, Self::MultiAppend)
            | (Self::Namespace, Self::Namespace)
            | (Self::ObjectId, Self::ObjectId)
            | (Self::Preview, Self::Preview)
            | (Self::QResync, Self::QResync)
            | (Self::Quota, Self::Quota)
            | (Self::SaslIr, Self::SaslIr)
            | (Self::SaveDate, Self::SaveDate)
            | (Self::SearchRes, Self::SearchRes)
            | (Self::Sort, Self::Sort)
            | (Self::StartTls, Self::StartTls)
            | (Self::SpecialUse, Self::SpecialUse)
            | (Self::StatusSize, Self::StatusSize)
            | (Self::Unauthenticate, Self::Unauthenticate)
            | (Self::UidPlus, Self::UidPlus)
            | (Self::Unselect, Self::Unselect)
            | (Self::Within, Self::Within)
            | (Self::Utf8Accept, Self::Utf8Accept)
            | (Self::Utf8Only, Self::Utf8Only) => true,
            (Self::AppendLimit(a), Self::AppendLimit(b)) => a == b,
            (Self::Auth(a), Self::Auth(b))
            | (Self::Thread(a), Self::Thread(b))
            | (Self::SortDisplay(a), Self::SortDisplay(b))
            | (Self::Rights(a), Self::Rights(b))
            | (Self::Other(a), Self::Other(b)) => a.eq_ignore_ascii_case(b),
            // Cross-representation: compare Other's wire form against known variant.
            (Self::Other(s), known) | (known, Self::Other(s)) => {
                s.eq_ignore_ascii_case(&known.as_imap_str())
            }
            _ => false,
        }
    }
}

/// RFC 3501 Section 7.2.1: capability equality is reflexive, symmetric, transitive.
impl Eq for Capability {}

/// RFC 3501 Section 7.2.1: capability names are case-insensitive.
///
/// The `Hash` implementation must be consistent with `PartialEq`: capabilities that
/// compare equal must hash to the same value. Because `Other("IDLE")` must
/// equal `Idle`, we hash the lowercased wire form (`as_imap_str()`) for all
/// variants, which is identical for cross-representation equivalents.
impl std::hash::Hash for Capability {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // RFC 3501 Section 7.2.1: case-insensitive hashing via wire form.
        // Other("IDLE") and Idle both yield "IDLE", so lowercasing
        // produces the same hash.
        for byte in self.as_imap_str().as_bytes() {
            byte.to_ascii_lowercase().hash(state);
        }
    }
}

/// A single namespace entry from a NAMESPACE response (RFC 2342).
///
/// RFC 2342 Section 6 ABNF:
/// ```text
/// Namespace = nil / "(" 1*( "(" string SP  (<"> QUOTED_CHAR <"> / nil)
///                    *(Namespace_Response_Extension) ")" ) ")"
/// Namespace_Response_Extension = SP string SP "(" string *(SP string) ")"
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamespaceDescriptor {
    /// Namespace prefix (e.g. `""`, `"INBOX."`, `"#shared."`) (RFC 2342 Section 5).
    pub prefix: String,
    /// Hierarchy delimiter for this namespace, or `None` if flat (RFC 2342 Section 5).
    pub delimiter: Option<char>,
    /// Extension key-value-list pairs (RFC 2342 Section 6).
    ///
    /// Each entry is `(key, values)` where key is a string and values is a
    /// non-empty list of strings, corresponding to one
    /// `Namespace_Response_Extension = SP string SP "(" string *(SP string) ")"`.
    pub extensions: Vec<(String, Vec<String>)>,
}

/// ESEARCH response data (RFC 4731 Section 3.1).
///
/// RFC 4731 Section 3.1 ABNF:
/// `search-return-data = "MIN" SP nz-number / "MAX" SP nz-number /
///                        "ALL" SP sequence-set / "COUNT" SP number`
///
/// Normative rules:
/// - MIN: "Return the lowest message number/UID that satisfies the SEARCH criteria.
///   If the SEARCH results in no matches, the server MUST NOT include the MIN result
///   option in the ESEARCH response."
/// - MAX: "Return the highest message number/UID that satisfies the SEARCH criteria.
///   If the SEARCH results in no matches, the server MUST NOT include the MAX result
///   option in the ESEARCH response."
/// - ALL: Returns matching messages as a sequence-set rather than space-separated.
///   "If the SEARCH results in no matches, the server MUST NOT include the ALL result
///   option in the ESEARCH response."
/// - COUNT: "Return number of the messages that satisfy the SEARCH criteria. This result
///   option MUST always be included in the ESEARCH response."
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EsearchResponse {
    /// Correlating tag from `(TAG "tagstring")`, if present
    /// (RFC 4466 Section 2.6.2 `search-correlator`).
    pub tag: Option<String>,
    /// `true` when the response includes the `UID` indicator,
    /// meaning all returned numbers are UIDs rather than sequence numbers
    /// (RFC 4731 Section 3.1).
    pub uid: bool,
    /// MIN — lowest matching message number/UID (RFC 4731 Section 3.1).
    pub min: Option<u32>,
    /// MAX — highest matching message number/UID (RFC 4731 Section 3.1).
    pub max: Option<u32>,
    /// COUNT — number of matching messages (RFC 4731 Section 3.1).
    pub count: Option<u32>,
    /// ALL — matching message numbers/UIDs as a uid-set (RFC 4731 Section 3.1).
    pub all: Vec<UidRange>,
    /// MODSEQ — highest mod-sequence of matching messages (RFC 7162 Section 3.1.10).
    pub mod_seq: Option<u64>,
}

/// A UID range (e.g. `1:100`, or a single UID `42`)
/// (RFC 3501 Section 9 / RFC 4315 Section 2.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UidRange {
    /// First UID in this range (RFC 3501 Section 9 / RFC 4315 Section 2.1).
    pub start: u32,
    /// `None` means a single UID (not a range) (RFC 3501 Section 9 / RFC 4315 Section 2.1).
    pub end: Option<u32>,
}

impl UidRange {
    /// Create a single-UID range.
    ///
    /// # Panics (debug builds only)
    /// Panics if `uid` is 0 — UIDs are `nz-number` per RFC 3501 Section 9.
    pub const fn single(uid: u32) -> Self {
        debug_assert!(
            uid != 0,
            "UID must be non-zero (RFC 3501 Section 9: uniqueid = nz-number)"
        );
        Self {
            start: uid,
            end: None,
        }
    }

    /// Create an inclusive UID range.
    ///
    /// # Panics (debug builds only)
    /// Panics if `start` or `end` is 0 — UIDs are `nz-number` per RFC 3501 Section 9.
    pub const fn range(start: u32, end: u32) -> Self {
        debug_assert!(
            start != 0,
            "UID start must be non-zero (RFC 3501 Section 9: uniqueid = nz-number)"
        );
        debug_assert!(
            end != 0,
            "UID end must be non-zero (RFC 3501 Section 9: uniqueid = nz-number)"
        );
        Self {
            start,
            end: Some(end),
        }
    }

    /// Try to create a single-UID range, returning `None` if `uid` is 0
    /// (RFC 3501 Section 9: uniqueid = nz-number).
    pub const fn try_single(uid: u32) -> Option<Self> {
        if uid == 0 {
            None
        } else {
            Some(Self {
                start: uid,
                end: None,
            })
        }
    }

    /// Try to create an inclusive UID range, returning `None` if `start` or `end` is 0
    /// (RFC 3501 Section 9: uniqueid = nz-number).
    pub const fn try_range(start: u32, end: u32) -> Option<Self> {
        if start == 0 || end == 0 {
            None
        } else {
            Some(Self {
                start,
                end: Some(end),
            })
        }
    }
}

/// Result of an EXPUNGE command (RFC 3501 Section 7.4.1 / RFC 7162 Section 3.2.10).
///
/// When QRESYNC is enabled (RFC 7162 Section 3.2.3), the server sends
/// `VANISHED` responses instead of `EXPUNGE`. This enum allows callers
/// to handle both cases.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExpungeResult {
    /// Classic EXPUNGE — sequence numbers of removed messages (RFC 3501 Section 7.4.1).
    ///
    /// Returned when QRESYNC is NOT enabled.
    Expunged(Vec<u32>),
    /// VANISHED — UID ranges of removed messages (RFC 7162 Section 3.2.10).
    ///
    /// Returned when QRESYNC IS enabled. The server sends VANISHED
    /// instead of EXPUNGE after `ENABLE QRESYNC`.
    Vanished(Vec<UidRange>),
}

/// Result of a MOVE command (RFC 6851 Section 3).
///
/// RFC 6851 Section 3 specifies that the server sends EXPUNGE (or VANISHED
/// when QRESYNC is enabled per RFC 7162 Section 3.2.10) responses *before*
/// the tagged OK, followed by a COPYUID response code in the tagged OK
/// (RFC 6851 Section 4.3). This struct captures both pieces of information.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MoveResult {
    /// The response code from the tagged OK, typically `COPYUID`
    /// (RFC 6851 Section 4.3).
    pub code: Option<ResponseCode>,
    /// The EXPUNGE or VANISHED responses that preceded the tagged OK
    /// (RFC 6851 Section 3 / RFC 7162 Section 3.2.10).
    pub expunged: ExpungeResult,
}

/// Parameters for QRESYNC-enabled SELECT/EXAMINE (RFC 7162 Section 3.2.5.2).
///
/// Allows the client to provide its last known state so the server can send
/// only the changes since the last synchronization point.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QresyncParams {
    /// The UIDVALIDITY value from the last session (RFC 7162 Section 3.2.5.2).
    pub uid_validity: u32,
    /// The highest MODSEQ value the client has cached (RFC 7162 Section 3.2.5.2).
    pub mod_seq: u64,
    /// Optional set of known UIDs for more efficient resync (RFC 7162 Section 3.2.5.2).
    pub known_uids: Option<String>,
    /// Optional sequence-to-UID mapping for detecting message renumbering
    /// (RFC 7162 Section 3.2.5.2).
    ///
    /// `seq-match-data = "(" known-sequence-set SP known-uid-set ")"`
    pub seq_match_data: Option<(String, String)>,
}

/// A single quota resource from a QUOTA response (RFC 2087 Section 5.1).
///
/// Each resource triplet consists of a name (e.g. `STORAGE`, `MESSAGE`),
/// the current usage, and the limit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QuotaResource {
    /// Resource name (e.g. `"STORAGE"`, `"MESSAGE"`) (RFC 2087 Section 5.1).
    pub name: String,
    /// Current usage of this resource (RFC 2087 Section 5.1).
    pub usage: u64,
    /// Server-imposed limit for this resource (RFC 2087 Section 5.1).
    pub limit: u64,
}

/// A single ACL entry from an ACL response (RFC 4314 Section 3.6).
///
/// Each entry pairs an identifier (user or group name) with a rights string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AclEntry {
    /// The identifier (user or group) this entry applies to (RFC 4314 Section 3.6).
    pub identifier: String,
    /// The rights string for this identifier (RFC 4314 Section 3.6).
    pub rights: String,
}

/// A single metadata entry from a METADATA response (RFC 5464 Section 4.4).
///
/// Each entry has a name (e.g. `/private/comment`) and an optional value.
/// A `None` value indicates the entry does not exist or has been deleted.
///
/// RFC 5464 Section 5 formal syntax: `value = nstring / literal8`.
/// The `literal8` form (`~{n}\r\n<data>`) allows arbitrary binary octets,
/// so the value is stored as raw bytes rather than a UTF-8 string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetadataEntry {
    /// Entry name (e.g. `/private/comment`, `/shared/vendor/foo`) (RFC 5464 Section 3.2).
    pub name: String,
    /// Entry value as raw bytes, or `None` if the entry does not exist (RFC 5464 Section 4.4).
    ///
    /// RFC 5464 Section 5: `value = nstring / literal8` — values may contain
    /// arbitrary binary data via the `literal8` syntax, so `Vec<u8>` is used
    /// instead of `String` to preserve binary fidelity.
    pub value: Option<Vec<u8>>,
}

/// A node in a THREAD response tree (RFC 5256 Section 4).
///
/// Each node represents a message in a thread. A dummy parent (`id == None`)
/// is used when the threading algorithm infers a parent that does not
/// correspond to an existing message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadNode {
    /// UID (or sequence number) of this message, or `None` if this is a
    /// dummy parent (RFC 5256 Section 4).
    pub id: Option<u32>,
    /// Child thread nodes (RFC 5256 Section 4).
    pub children: Vec<Self>,
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::types::{FetchResponse, Flag, MailboxInfo, StatusItem};

    // --- GreetingStatus tests ---

    #[test]
    fn greeting_status_variants() {
        assert_eq!(GreetingStatus::Ok, GreetingStatus::Ok);
        assert_ne!(GreetingStatus::Ok, GreetingStatus::PreAuth);
        assert_ne!(GreetingStatus::PreAuth, GreetingStatus::Bye);
    }

    #[test]
    fn greeting_status_copy() {
        let s = GreetingStatus::PreAuth;
        let s2 = s; // Copy
        assert_eq!(s, s2);
    }

    // --- StatusKind tests ---

    #[test]
    fn status_kind_variants() {
        assert_eq!(StatusKind::Ok, StatusKind::Ok);
        assert_ne!(StatusKind::Ok, StatusKind::No);
        assert_ne!(StatusKind::No, StatusKind::Bad);
    }

    #[test]
    fn status_kind_copy() {
        let s = StatusKind::Bad;
        let s2 = s;
        assert_eq!(s, s2);
    }

    // --- UntaggedStatus tests ---

    #[test]
    fn untagged_status_variants() {
        assert_ne!(UntaggedStatus::Ok, UntaggedStatus::No);
        assert_ne!(UntaggedStatus::Bad, UntaggedStatus::Bye);
    }

    // --- GreetingResponse tests ---

    #[test]
    fn greeting_response_ok() {
        let greeting = GreetingResponse {
            status: GreetingStatus::Ok,
            code: None,
            text: "Dovecot ready.".into(),
        };
        assert_eq!(greeting.status, GreetingStatus::Ok);
        assert!(greeting.code.is_none());
        assert_eq!(greeting.text, "Dovecot ready.");
    }

    #[test]
    fn greeting_response_preauth_with_code() {
        let greeting = GreetingResponse {
            status: GreetingStatus::PreAuth,
            code: Some(ResponseCode::Alert),
            text: "Authenticated via TLS cert".into(),
        };
        assert_eq!(greeting.status, GreetingStatus::PreAuth);
        assert_eq!(greeting.code, Some(ResponseCode::Alert));
    }

    #[test]
    fn greeting_response_bye() {
        let greeting = GreetingResponse {
            status: GreetingStatus::Bye,
            code: None,
            text: "Server shutting down".into(),
        };
        assert_eq!(greeting.status, GreetingStatus::Bye);
    }

    // --- TaggedResponse tests ---

    #[test]
    fn tagged_response_ok() {
        let resp = TaggedResponse {
            tag: "A001".into(),
            status: StatusKind::Ok,
            code: None,
            text: "LOGIN completed".into(),
        };
        assert_eq!(resp.tag, "A001");
        assert_eq!(resp.status, StatusKind::Ok);
        assert!(resp.code.is_none());
    }

    #[test]
    fn tagged_response_no_with_code() {
        let resp = TaggedResponse {
            tag: "A002".into(),
            status: StatusKind::No,
            code: Some(ResponseCode::AuthenticationFailed),
            text: "Invalid credentials".into(),
        };
        assert_eq!(resp.status, StatusKind::No);
        assert_eq!(resp.code, Some(ResponseCode::AuthenticationFailed));
    }

    #[test]
    fn tagged_response_bad() {
        let resp = TaggedResponse {
            tag: "A003".into(),
            status: StatusKind::Bad,
            code: Some(ResponseCode::ClientBug),
            text: "Syntax error".into(),
        };
        assert_eq!(resp.status, StatusKind::Bad);
        assert_eq!(resp.code, Some(ResponseCode::ClientBug));
    }

    // --- ContinuationRequest tests ---

    #[test]
    fn continuation_request() {
        let cont = ContinuationRequest {
            code: None,
            data: "Ready for literal data".into(),
        };
        assert_eq!(cont.data, "Ready for literal data");
        assert_eq!(cont.code, None);
    }

    #[test]
    fn continuation_request_empty() {
        let cont = ContinuationRequest {
            code: None,
            data: String::new(),
        };
        assert!(cont.data.is_empty());
        assert_eq!(cont.code, None);
    }

    // --- ResponseCode tests ---

    #[test]
    fn response_code_simple_variants() {
        assert_eq!(ResponseCode::Alert, ResponseCode::Alert);
        assert_eq!(ResponseCode::Parse, ResponseCode::Parse);
        assert_eq!(ResponseCode::ReadOnly, ResponseCode::ReadOnly);
        assert_eq!(ResponseCode::ReadWrite, ResponseCode::ReadWrite);
        assert_eq!(ResponseCode::TryCreate, ResponseCode::TryCreate);
        assert_eq!(ResponseCode::NoModSeq, ResponseCode::NoModSeq);
        assert_eq!(ResponseCode::Closed, ResponseCode::Closed);
        assert_eq!(
            ResponseCode::MailboxId("abc".into()),
            ResponseCode::MailboxId("abc".into())
        );
    }

    #[test]
    fn response_code_uid_next() {
        let code = ResponseCode::UidNext(42);
        assert_eq!(code, ResponseCode::UidNext(42));
        assert_ne!(code, ResponseCode::UidNext(99));
    }

    #[test]
    fn response_code_uid_validity() {
        let code = ResponseCode::UidValidity(1_234_567_890);
        assert_eq!(code, ResponseCode::UidValidity(1_234_567_890));
    }

    #[test]
    fn response_code_unseen() {
        let code = ResponseCode::Unseen(5);
        assert_eq!(code, ResponseCode::Unseen(5));
    }

    #[test]
    fn response_code_append_uid() {
        let code = ResponseCode::AppendUid {
            uid_validity: 100,
            uids: vec![UidRange::single(200)],
        };
        match &code {
            ResponseCode::AppendUid { uid_validity, uids } => {
                assert_eq!(*uid_validity, 100);
                assert_eq!(uids, &[UidRange::single(200)]);
            }
            _ => panic!("expected AppendUid"),
        }
    }

    #[test]
    fn response_code_copy_uid() {
        let code = ResponseCode::CopyUid {
            uid_validity: 100,
            source_uids: vec![UidRange::single(1), UidRange::range(3, 5)],
            dest_uids: vec![UidRange::single(10)],
        };
        match &code {
            ResponseCode::CopyUid {
                uid_validity,
                source_uids,
                dest_uids,
            } => {
                assert_eq!(*uid_validity, 100);
                assert_eq!(source_uids.len(), 2);
                assert_eq!(dest_uids.len(), 1);
            }
            _ => panic!("expected CopyUid"),
        }
    }

    #[test]
    fn response_code_highest_mod_seq() {
        let code = ResponseCode::HighestModSeq(9999);
        assert_eq!(code, ResponseCode::HighestModSeq(9999));
    }

    #[test]
    fn response_code_bad_charset() {
        let code = ResponseCode::BadCharset(vec!["utf-8".into(), "us-ascii".into()]);
        match &code {
            ResponseCode::BadCharset(charsets) => {
                assert_eq!(charsets.len(), 2);
                assert_eq!(charsets[0], "utf-8");
            }
            _ => panic!("expected BadCharset"),
        }
    }

    #[test]
    fn response_code_permanent_flags() {
        let code = ResponseCode::PermanentFlags(vec![Flag::Seen, Flag::Flagged]);
        match &code {
            ResponseCode::PermanentFlags(flags) => {
                assert_eq!(flags.len(), 2);
                assert_eq!(flags[0], Flag::Seen);
            }
            _ => panic!("expected PermanentFlags"),
        }
    }

    #[test]
    fn response_code_capability() {
        let code = ResponseCode::Capability(vec![Capability::Imap4Rev1, Capability::Idle]);
        match &code {
            ResponseCode::Capability(caps) => {
                assert_eq!(caps.len(), 2);
                assert_eq!(caps[0], Capability::Imap4Rev1);
            }
            _ => panic!("expected Capability"),
        }
    }

    #[test]
    fn response_code_modified() {
        let code = ResponseCode::Modified(vec![UidRange::range(1, 10)]);
        match &code {
            ResponseCode::Modified(ranges) => {
                assert_eq!(ranges.len(), 1);
                assert_eq!(ranges[0], UidRange::range(1, 10));
            }
            _ => panic!("expected Modified"),
        }
    }

    #[test]
    fn response_code_rfc5530_variants() {
        // Ensure the RFC 5530 extended codes are distinct.
        let codes = [
            ResponseCode::Unavailable,
            ResponseCode::AuthenticationFailed,
            ResponseCode::AuthorizationFailed,
            ResponseCode::Expired,
            ResponseCode::PrivacyRequired,
            ResponseCode::ContactAdmin,
            ResponseCode::NoPerm,
            ResponseCode::InUse,
            ResponseCode::ExpungeIssued,
            ResponseCode::Corruption,
            ResponseCode::ServerBug,
            ResponseCode::ClientBug,
            ResponseCode::Cannot,
            ResponseCode::Limit,
            ResponseCode::OverQuota,
            ResponseCode::AlreadyExists,
            ResponseCode::NonExistent,
        ];
        // Each should equal itself.
        for code in &codes {
            assert_eq!(code, &code.clone());
        }
        // First and second should differ.
        assert_ne!(codes[0], codes[1]);
    }

    #[test]
    fn response_code_other() {
        let code = ResponseCode::Other {
            name: "CUSTOM".into(),
            value: Some("data".into()),
        };
        match &code {
            ResponseCode::Other { name, value } => {
                assert_eq!(name, "CUSTOM");
                assert_eq!(value.as_deref(), Some("data"));
            }
            _ => panic!("expected Other"),
        }
    }

    #[test]
    fn response_code_other_no_value() {
        let code = ResponseCode::Other {
            name: "XFOO".into(),
            value: None,
        };
        match &code {
            ResponseCode::Other { name, value } => {
                assert_eq!(name, "XFOO");
                assert!(value.is_none());
            }
            _ => panic!("expected Other"),
        }
    }

    // --- Response enum tests ---

    #[test]
    fn response_greeting_variant() {
        let resp = Response::Greeting(GreetingResponse {
            status: GreetingStatus::Ok,
            code: None,
            text: "Ready".into(),
        });
        assert!(matches!(resp, Response::Greeting(_)));
    }

    #[test]
    fn response_tagged_variant() {
        let resp = Response::Tagged(TaggedResponse {
            tag: "T1".into(),
            status: StatusKind::Ok,
            code: None,
            text: "Done".into(),
        });
        assert!(matches!(resp, Response::Tagged(_)));
    }

    #[test]
    fn response_continuation_variant() {
        let resp = Response::Continuation(ContinuationRequest {
            code: None,
            data: "+".into(),
        });
        assert!(matches!(resp, Response::Continuation(_)));
    }

    // --- UntaggedResponse tests ---

    #[test]
    fn untagged_exists() {
        let resp = UntaggedResponse::Exists(42);
        assert_eq!(resp, UntaggedResponse::Exists(42));
        assert_ne!(resp, UntaggedResponse::Exists(0));
    }

    #[test]
    fn untagged_recent() {
        let resp = UntaggedResponse::Recent(5);
        assert_eq!(resp, UntaggedResponse::Recent(5));
    }

    #[test]
    fn untagged_expunge() {
        let resp = UntaggedResponse::Expunge(7);
        assert_eq!(resp, UntaggedResponse::Expunge(7));
    }

    #[test]
    fn untagged_flags() {
        let resp = UntaggedResponse::Flags(vec![
            Flag::Seen,
            Flag::Answered,
            Flag::Custom("$Junk".into()),
        ]);
        match &resp {
            UntaggedResponse::Flags(flags) => {
                assert_eq!(flags.len(), 3);
                assert_eq!(flags[2], Flag::Custom("$Junk".into()));
            }
            _ => panic!("expected Flags"),
        }
    }

    #[test]
    fn untagged_search() {
        let resp = UntaggedResponse::Search {
            uids: vec![1, 5, 10, 42],
            mod_seq: None,
        };
        match &resp {
            UntaggedResponse::Search { uids, mod_seq } => {
                assert_eq!(uids, &[1, 5, 10, 42]);
                assert!(mod_seq.is_none());
            }
            _ => panic!("expected Search"),
        }
    }

    #[test]
    fn untagged_search_empty() {
        let resp = UntaggedResponse::Search {
            uids: vec![],
            mod_seq: None,
        };
        match &resp {
            UntaggedResponse::Search { uids, .. } => assert!(uids.is_empty()),
            _ => panic!("expected Search"),
        }
    }

    #[test]
    fn untagged_status() {
        let resp = UntaggedResponse::Status {
            status: UntaggedStatus::Ok,
            code: Some(ResponseCode::UidValidity(12345)),
            text: "selected".into(),
        };
        match &resp {
            UntaggedResponse::Status { status, code, text } => {
                assert_eq!(*status, UntaggedStatus::Ok);
                assert_eq!(code, &Some(ResponseCode::UidValidity(12345)));
                assert_eq!(text, "selected");
            }
            _ => panic!("expected Status"),
        }
    }

    #[test]
    fn untagged_mailbox_status() {
        let resp = UntaggedResponse::MailboxStatus {
            mailbox: "INBOX".into(),
            items: vec![StatusItem::Messages(42), StatusItem::Unseen(3)],
        };
        match &resp {
            UntaggedResponse::MailboxStatus { mailbox, items } => {
                assert_eq!(mailbox, "INBOX");
                assert_eq!(items.len(), 2);
            }
            _ => panic!("expected MailboxStatus"),
        }
    }

    #[test]
    fn untagged_capability() {
        let resp = UntaggedResponse::Capability(vec![
            Capability::Imap4Rev1,
            Capability::Idle,
            Capability::Auth("PLAIN".into()),
        ]);
        match &resp {
            UntaggedResponse::Capability(caps) => {
                assert_eq!(caps.len(), 3);
                assert_eq!(caps[2], Capability::Auth("PLAIN".into()));
            }
            _ => panic!("expected Capability"),
        }
    }

    #[test]
    fn untagged_enabled() {
        let resp = UntaggedResponse::Enabled(vec!["CONDSTORE".into(), "QRESYNC".into()]);
        match &resp {
            UntaggedResponse::Enabled(exts) => {
                assert_eq!(exts, &["CONDSTORE", "QRESYNC"]);
            }
            _ => panic!("expected Enabled"),
        }
    }

    #[test]
    fn untagged_fetch() {
        let fetch = FetchResponse {
            seq: 1,
            uid: Some(100),
            ..Default::default()
        };
        let resp = UntaggedResponse::Fetch(Box::new(fetch));
        match &resp {
            UntaggedResponse::Fetch(f) => {
                assert_eq!(f.seq, 1);
                assert_eq!(f.uid, Some(100));
            }
            _ => panic!("expected Fetch"),
        }
    }

    #[test]
    fn untagged_list() {
        let info = MailboxInfo {
            name: "INBOX".into(),
            delimiter: Some('/'),
            attributes: vec![],
            ..Default::default()
        };
        let resp = UntaggedResponse::List(info);
        match &resp {
            UntaggedResponse::List(i) => {
                assert_eq!(i.name, "INBOX");
                assert_eq!(i.delimiter, Some('/'));
            }
            _ => panic!("expected List"),
        }
    }

    #[test]
    fn untagged_vanished() {
        let resp = UntaggedResponse::Vanished {
            earlier: true,
            uids: vec![UidRange::range(1, 5), UidRange::single(10)],
        };
        match &resp {
            UntaggedResponse::Vanished { earlier, uids } => {
                assert!(*earlier);
                assert_eq!(uids.len(), 2);
            }
            _ => panic!("expected Vanished"),
        }
    }

    #[test]
    fn untagged_id() {
        let resp = UntaggedResponse::Id(vec![
            ("name".into(), Some("Dovecot".into())),
            ("version".into(), None),
        ]);
        match &resp {
            UntaggedResponse::Id(pairs) => {
                assert_eq!(pairs.len(), 2);
                assert_eq!(pairs[0].1.as_deref(), Some("Dovecot"));
                assert!(pairs[1].1.is_none());
            }
            _ => panic!("expected Id"),
        }
    }

    #[test]
    fn untagged_namespace() {
        let resp = UntaggedResponse::Namespace {
            personal: vec![NamespaceDescriptor {
                prefix: String::new(),
                delimiter: Some('/'),
                extensions: vec![],
            }],
            other: vec![],
            shared: vec![NamespaceDescriptor {
                prefix: "#shared.".into(),
                delimiter: Some('.'),
                extensions: vec![],
            }],
        };
        match &resp {
            UntaggedResponse::Namespace {
                personal,
                other,
                shared,
            } => {
                assert_eq!(personal.len(), 1);
                assert!(other.is_empty());
                assert_eq!(shared.len(), 1);
                assert_eq!(shared[0].prefix, "#shared.");
            }
            _ => panic!("expected Namespace"),
        }
    }

    #[test]
    fn untagged_quota() {
        let resp = UntaggedResponse::Quota {
            root: String::new(),
            resources: vec![QuotaResource {
                name: "STORAGE".into(),
                usage: 1024,
                limit: 10240,
            }],
        };
        match &resp {
            UntaggedResponse::Quota { root, resources } => {
                assert!(root.is_empty());
                assert_eq!(resources.len(), 1);
                assert_eq!(resources[0].usage, 1024);
                assert_eq!(resources[0].limit, 10240);
            }
            _ => panic!("expected Quota"),
        }
    }

    #[test]
    fn untagged_quota_root() {
        let resp = UntaggedResponse::QuotaRoot {
            mailbox: "INBOX".into(),
            roots: vec![String::new(), "user.alice".into()],
        };
        match &resp {
            UntaggedResponse::QuotaRoot { mailbox, roots } => {
                assert_eq!(mailbox, "INBOX");
                assert_eq!(roots.len(), 2);
            }
            _ => panic!("expected QuotaRoot"),
        }
    }

    #[test]
    fn untagged_acl() {
        let resp = UntaggedResponse::Acl {
            mailbox: "INBOX".into(),
            entries: vec![AclEntry {
                identifier: "alice".into(),
                rights: "lrswipkxte".into(),
            }],
        };
        match &resp {
            UntaggedResponse::Acl { mailbox, entries } => {
                assert_eq!(mailbox, "INBOX");
                assert_eq!(entries[0].identifier, "alice");
            }
            _ => panic!("expected Acl"),
        }
    }

    #[test]
    fn untagged_my_rights() {
        let resp = UntaggedResponse::MyRights {
            mailbox: "INBOX".into(),
            rights: "lrs".into(),
        };
        match &resp {
            UntaggedResponse::MyRights { mailbox, rights } => {
                assert_eq!(mailbox, "INBOX");
                assert_eq!(rights, "lrs");
            }
            _ => panic!("expected MyRights"),
        }
    }

    #[test]
    fn untagged_list_rights() {
        let resp = UntaggedResponse::ListRights {
            mailbox: "INBOX".into(),
            identifier: "bob".into(),
            required: "l".into(),
            optional: vec!["r".into(), "s".into()],
        };
        match &resp {
            UntaggedResponse::ListRights {
                mailbox,
                identifier,
                required,
                optional,
            } => {
                assert_eq!(mailbox, "INBOX");
                assert_eq!(identifier, "bob");
                assert_eq!(required, "l");
                assert_eq!(optional.len(), 2);
            }
            _ => panic!("expected ListRights"),
        }
    }

    #[test]
    fn untagged_metadata() {
        let resp = UntaggedResponse::Metadata {
            mailbox: "INBOX".into(),
            entries: vec![
                MetadataEntry {
                    name: "/private/comment".into(),
                    value: Some(b"My notes".to_vec()),
                },
                MetadataEntry {
                    name: "/shared/vendor/foo".into(),
                    value: None,
                },
            ],
        };
        match &resp {
            UntaggedResponse::Metadata { mailbox, entries } => {
                assert_eq!(mailbox, "INBOX");
                assert_eq!(entries.len(), 2);
                assert_eq!(entries[0].value.as_deref(), Some(b"My notes".as_slice()));
                assert!(entries[1].value.is_none());
            }
            _ => panic!("expected Metadata"),
        }
    }

    #[test]
    fn untagged_thread() {
        let resp = UntaggedResponse::Thread(vec![ThreadNode {
            id: Some(1),
            children: vec![
                ThreadNode {
                    id: Some(2),
                    children: vec![],
                },
                ThreadNode {
                    id: Some(3),
                    children: vec![ThreadNode {
                        id: Some(4),
                        children: vec![],
                    }],
                },
            ],
        }]);
        match &resp {
            UntaggedResponse::Thread(nodes) => {
                assert_eq!(nodes.len(), 1);
                assert_eq!(nodes[0].id, Some(1));
                assert_eq!(nodes[0].children.len(), 2);
                assert_eq!(nodes[0].children[1].children[0].id, Some(4));
            }
            _ => panic!("expected Thread"),
        }
    }

    // --- Capability tests ---

    #[test]
    fn capability_variants() {
        assert_eq!(Capability::Imap4Rev1, Capability::Imap4Rev1);
        assert_ne!(Capability::Imap4Rev1, Capability::Imap4Rev2);
        assert_eq!(
            Capability::Auth("PLAIN".into()),
            Capability::Auth("PLAIN".into())
        );
        assert_ne!(
            Capability::Auth("PLAIN".into()),
            Capability::Auth("XOAUTH2".into())
        );
    }

    #[test]
    fn capability_other() {
        let cap = Capability::Other("XSPECIAL".into());
        assert_eq!(cap, Capability::Other("XSPECIAL".into()));
    }

    // ===== RFC 3501 Section 7.2.1 audit: capability names are case-insensitive =====

    #[test]
    fn capability_other_case_insensitive() {
        // RFC 3501 Section 7.2.1: capability names are case-insensitive.
        // Two `Other` variants differing only in case must compare equal.
        assert_eq!(
            Capability::Other("XYZZY".into()),
            Capability::Other("xyzzy".into()),
            "Capability::Other must compare case-insensitively per RFC 3501 Section 7.2.1"
        );
    }

    #[test]
    fn capability_auth_case_insensitive() {
        // RFC 3501 Section 7.2.1: capability names are case-insensitive.
        assert_eq!(
            Capability::Auth("PLAIN".into()),
            Capability::Auth("plain".into()),
            "Capability::Auth must compare case-insensitively per RFC 3501 Section 7.2.1"
        );
    }

    #[test]
    fn capability_thread_case_insensitive() {
        // RFC 3501 Section 7.2.1: capability names are case-insensitive.
        assert_eq!(
            Capability::Thread("REFERENCES".into()),
            Capability::Thread("references".into()),
            "Capability::Thread must compare case-insensitively per RFC 3501 Section 7.2.1"
        );
    }

    #[test]
    fn capability_other_case_insensitive_hash() {
        // RFC 3501 Section 7.2.1: case-insensitively equal capabilities must hash the same.
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(Capability::Other("XYZZY".into()));
        set.insert(Capability::Other("xyzzy".into()));
        assert_eq!(
            set.len(),
            1,
            "Case-insensitively equal Capability::Other must have the same Hash \
             per RFC 3501 Section 7.2.1"
        );
    }

    #[test]
    fn capability_thread() {
        let cap = Capability::Thread("REFERENCES".into());
        assert_eq!(cap, Capability::Thread("REFERENCES".into()));
        assert_ne!(cap, Capability::Thread("ORDEREDSUBJECT".into()));
    }

    #[test]
    fn capability_append_limit() {
        assert_eq!(
            Capability::AppendLimit(Some(1024)),
            Capability::AppendLimit(Some(1024))
        );
        assert_eq!(Capability::AppendLimit(None), Capability::AppendLimit(None));
        assert_ne!(
            Capability::AppendLimit(Some(1024)),
            Capability::AppendLimit(None)
        );
    }

    #[test]
    fn capability_hash() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(Capability::Imap4Rev1);
        set.insert(Capability::Idle);
        set.insert(Capability::Imap4Rev1); // duplicate
        assert_eq!(set.len(), 2);
    }

    // --- UidRange tests ---

    #[test]
    fn uid_range_single() {
        let r = UidRange::single(42);
        assert_eq!(r.start, 42);
        assert!(r.end.is_none());
    }

    #[test]
    fn uid_range_range() {
        let r = UidRange::range(1, 100);
        assert_eq!(r.start, 1);
        assert_eq!(r.end, Some(100));
    }

    #[test]
    fn uid_range_copy() {
        let r = UidRange::range(5, 10);
        let r2 = r; // Copy
        assert_eq!(r, r2);
    }

    // --- UidRange nz-number validation tests (RFC 3501 Section 9) ---

    #[test]
    fn uid_range_try_single_zero_returns_none() {
        // UIDs are nz-number per RFC 3501 Section 9: 0 is invalid.
        assert!(UidRange::try_single(0).is_none());
    }

    #[test]
    fn uid_range_try_single_nonzero_returns_some() {
        let r = UidRange::try_single(1).unwrap();
        assert_eq!(r.start, 1);
        assert!(r.end.is_none());
    }

    #[test]
    fn uid_range_try_range_zero_start_returns_none() {
        // start=0 violates nz-number (RFC 3501 Section 9).
        assert!(UidRange::try_range(0, 5).is_none());
    }

    #[test]
    fn uid_range_try_range_zero_end_returns_none() {
        // end=0 violates nz-number (RFC 3501 Section 9).
        assert!(UidRange::try_range(5, 0).is_none());
    }

    #[test]
    fn uid_range_try_range_nonzero_returns_some() {
        let r = UidRange::try_range(1, 5).unwrap();
        assert_eq!(r.start, 1);
        assert_eq!(r.end, Some(5));
    }

    // --- NamespaceDescriptor tests ---

    #[test]
    fn namespace_descriptor() {
        let ns = NamespaceDescriptor {
            prefix: "INBOX.".into(),
            delimiter: Some('.'),
            extensions: vec![],
        };
        assert_eq!(ns.prefix, "INBOX.");
        assert_eq!(ns.delimiter, Some('.'));
        assert!(ns.extensions.is_empty());
    }

    #[test]
    fn namespace_descriptor_no_delimiter() {
        let ns = NamespaceDescriptor {
            prefix: String::new(),
            delimiter: None,
            extensions: vec![],
        };
        assert!(ns.prefix.is_empty());
        assert!(ns.delimiter.is_none());
        assert!(ns.extensions.is_empty());
    }

    // --- QuotaResource tests ---

    #[test]
    fn quota_resource() {
        let qr = QuotaResource {
            name: "MESSAGE".into(),
            usage: 50,
            limit: 1000,
        };
        assert_eq!(qr.name, "MESSAGE");
        assert_eq!(qr.usage, 50);
        assert_eq!(qr.limit, 1000);
    }

    // --- AclEntry tests ---

    #[test]
    fn acl_entry() {
        let entry = AclEntry {
            identifier: "admin".into(),
            rights: "lrswipkxtea".into(),
        };
        assert_eq!(entry.identifier, "admin");
        assert_eq!(entry.rights, "lrswipkxtea");
    }

    // --- MetadataEntry tests ---

    #[test]
    fn metadata_entry_with_value() {
        let entry = MetadataEntry {
            name: "/private/comment".into(),
            value: Some(b"hello".to_vec()),
        };
        assert_eq!(entry.name, "/private/comment");
        assert_eq!(entry.value.as_deref(), Some(b"hello".as_slice()));
    }

    #[test]
    fn metadata_entry_nil_value() {
        let entry = MetadataEntry {
            name: "/shared/something".into(),
            value: None,
        };
        assert!(entry.value.is_none());
    }

    // --- ThreadNode tests ---

    #[test]
    fn thread_node_leaf() {
        let node = ThreadNode {
            id: Some(5),
            children: vec![],
        };
        assert_eq!(node.id, Some(5));
        assert!(node.children.is_empty());
    }

    #[test]
    fn thread_node_dummy_parent() {
        let node = ThreadNode {
            id: None,
            children: vec![ThreadNode {
                id: Some(1),
                children: vec![],
            }],
        };
        assert_eq!(node.id, None);
        assert_eq!(node.children.len(), 1);
    }

    // --- Response wrapping via boxed UntaggedResponse ---

    #[test]
    fn response_untagged_boxed() {
        let untagged = UntaggedResponse::Exists(10);
        let resp = Response::Untagged(Box::new(untagged));
        match resp {
            Response::Untagged(inner) => {
                assert_eq!(*inner, UntaggedResponse::Exists(10));
            }
            _ => panic!("expected Untagged"),
        }
    }

    // --- EsearchResponse ---

    #[test]
    fn esearch_response_default() {
        let esearch = EsearchResponse::default();
        assert_eq!(esearch.tag, None);
        assert!(!esearch.uid);
        assert_eq!(esearch.min, None);
        assert_eq!(esearch.max, None);
        assert_eq!(esearch.count, None);
        assert!(esearch.all.is_empty());
    }

    #[test]
    fn esearch_response_clone_eq() {
        let esearch = EsearchResponse {
            tag: Some("A001".into()),
            uid: true,
            min: Some(1),
            max: Some(100),
            count: Some(50),
            all: vec![UidRange::range(1, 50), UidRange::range(51, 100)],
            mod_seq: None,
        };
        let cloned = esearch.clone();
        assert_eq!(esearch, cloned);
    }

    #[test]
    fn esearch_response_ne() {
        let a = EsearchResponse {
            min: Some(1),
            ..EsearchResponse::default()
        };
        let b = EsearchResponse {
            min: Some(2),
            ..EsearchResponse::default()
        };
        assert_ne!(a, b);
    }

    // ===== Spec audit: failing tests for known deviations =====

    // ===== RFC 3501 Section 7.2.1 audit: cross-representation equality =====

    #[test]
    fn custom_idle_equals_idle_variant() {
        // RFC 3501 Section 7.2.1: capability names are case-insensitive atoms.
        // Custom("IDLE") represents the same capability as Capability::Idle.
        assert_eq!(
            Capability::Other("IDLE".into()),
            Capability::Idle,
            "Other(\"IDLE\") must equal Capability::Idle per RFC 3501 Section 7.2.1"
        );
    }

    #[test]
    fn custom_capability_cross_representation_hash() {
        // RFC 3501 Section 7.2.1: equal capabilities must hash identically.
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(Capability::Idle);
        set.insert(Capability::Other("IDLE".into()));
        assert_eq!(
            set.len(),
            1,
            "Other(\"IDLE\") and Capability::Idle must hash the same \
             per RFC 3501 Section 7.2.1"
        );
    }

    #[test]
    fn custom_starttls_equals_starttls_variant() {
        // RFC 3501 Section 7.2.1: capability names are case-insensitive atoms.
        assert_eq!(
            Capability::Other("STARTTLS".into()),
            Capability::StartTls,
            "Other(\"STARTTLS\") must equal Capability::StartTls \
             per RFC 3501 Section 7.2.1"
        );
    }

    #[test]
    fn custom_auth_plain_equals_auth_variant() {
        // RFC 3501 Section 7.2.1: AUTH=PLAIN as Other must equal Auth("PLAIN").
        assert_eq!(
            Capability::Other("AUTH=PLAIN".into()),
            Capability::Auth("PLAIN".into()),
            "Other(\"AUTH=PLAIN\") must equal Auth(\"PLAIN\") \
             per RFC 3501 Section 7.2.1"
        );
    }

    #[test]
    fn sort_display_as_imap_str_round_trip() {
        // RFC 5957 defines the capability as `SORT=DISPLAY`. The parser stores the
        // part after `SORT=` (i.e. `"DISPLAY"`) into `SortDisplay(String)`.
        // `as_imap_str()` must reconstruct the original wire form `SORT=DISPLAY`,
        // not `SORT=DISPLAYDISPLAY`.
        let cap = Capability::SortDisplay("DISPLAY".to_owned());
        assert_eq!(cap.as_imap_str(), "SORT=DISPLAY");
    }

    #[test]
    fn sort_display_cross_representation_equality() {
        // Cross-representation: Other("SORT=DISPLAY") must equal SortDisplay("DISPLAY").
        let structured = Capability::SortDisplay("DISPLAY".to_owned());
        let other = Capability::Other("SORT=DISPLAY".to_owned());
        assert_eq!(structured, other);
        assert_eq!(other, structured);
    }

    #[test]
    fn sort_display_hash_consistency() {
        // Equal capabilities must produce the same hash (Hash/Eq contract).
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let a = Capability::SortDisplay("DISPLAY".to_owned());
        let b = Capability::Other("SORT=DISPLAY".to_owned());

        let hash = |c: &Capability| {
            let mut h = DefaultHasher::new();
            c.hash(&mut h);
            h.finish()
        };
        assert_eq!(a, b);
        assert_eq!(hash(&a), hash(&b));
    }

    #[test]
    fn spec_audit_l12_literal_minus_capability() {
        // RFC 7888 Section 5 defines the LITERAL- capability, which indicates
        // the server supports non-synchronizing literals only for small payloads
        // (up to 4096 bytes). It should have a dedicated Capability::LiteralMinus
        // variant, not Capability::Other("LITERAL-").
        let input = b"* CAPABILITY IMAP4rev1 LITERAL-\r\n";
        let (_, resp) = crate::codec::decode::parse_response(input).unwrap();
        match resp {
            Response::Untagged(inner) => match *inner {
                UntaggedResponse::Capability(ref caps) => {
                    // LITERAL- should NOT be an Other variant.
                    let has_dedicated = caps.iter().any(|c| {
                        // If a dedicated LiteralMinus variant existed, it would
                        // NOT match Capability::Other(_).
                        !matches!(c, Capability::Other(_)) && !matches!(c, Capability::Imap4Rev1)
                    });
                    assert!(
                        has_dedicated,
                        "LITERAL- should have a dedicated Capability variant, \
                         not Capability::Other; got {caps:?}"
                    );
                }
                other => panic!("expected Capability, got {other:?}"),
            },
            other => panic!("expected Untagged, got {other:?}"),
        }
    }

    // --- TaggedResponse status dispatch tests ---
    // Pre-refactor: validate the three-arm Ok/No/Bad dispatch that will be
    // extracted into TaggedResponse::require_ok().

    #[test]
    fn tagged_ok_returns_no_error() {
        use crate::error::Error;
        let tagged = TaggedResponse {
            tag: "A001".into(),
            status: StatusKind::Ok,
            code: None,
            text: "completed".into(),
        };
        let result: Result<(), Error> = match tagged.status {
            StatusKind::Ok => Ok(()),
            StatusKind::No => Err(Error::no_with_code(tagged.text, tagged.code)),
            StatusKind::Bad => Err(Error::bad_with_code(tagged.text, tagged.code)),
        };
        assert!(result.is_ok());
    }

    #[test]
    fn tagged_no_returns_no_error_variant() {
        use crate::error::Error;
        let tagged = TaggedResponse {
            tag: "A002".into(),
            status: StatusKind::No,
            code: Some(ResponseCode::NonExistent),
            text: "mailbox not found".into(),
        };
        let result: Result<(), Error> = match tagged.status {
            StatusKind::Ok => Ok(()),
            StatusKind::No => Err(Error::no_with_code(tagged.text, tagged.code)),
            StatusKind::Bad => Err(Error::bad_with_code(tagged.text, tagged.code)),
        };
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::No { text, code } => {
                assert_eq!(text, "mailbox not found");
                assert_eq!(code, Some(ResponseCode::NonExistent));
            }
            other => panic!("expected Error::No, got {other:?}"),
        }
    }

    #[test]
    fn tagged_bad_returns_bad_error() {
        use crate::error::Error;
        let tagged = TaggedResponse {
            tag: "A003".into(),
            status: StatusKind::Bad,
            code: None,
            text: "syntax error".into(),
        };
        let result: Result<(), Error> = match tagged.status {
            StatusKind::Ok => Ok(()),
            StatusKind::No => Err(Error::no_with_code(tagged.text, tagged.code)),
            StatusKind::Bad => Err(Error::bad_with_code(tagged.text, tagged.code)),
        };
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::Bad { text, code } => {
                assert_eq!(text, "syntax error");
                assert!(code.is_none());
            }
            other => panic!("expected Error::Bad, got {other:?}"),
        }
    }

    #[test]
    fn tagged_ok_with_response_code_succeeds() {
        use crate::error::Error;
        let tagged = TaggedResponse {
            tag: "A004".into(),
            status: StatusKind::Ok,
            code: Some(ResponseCode::ReadWrite),
            text: "SELECT completed".into(),
        };
        let result: Result<(), Error> = match tagged.status {
            StatusKind::Ok => Ok(()),
            StatusKind::No => Err(Error::no_with_code(tagged.text, tagged.code)),
            StatusKind::Bad => Err(Error::bad_with_code(tagged.text, tagged.code)),
        };
        assert!(result.is_ok());
    }

    // --- Capability::as_imap_str() tests ---
    // RFC 3501 Section 7.2.1 / RFC 9051 Section 7.2.1: wire representation.

    #[test]
    fn capability_as_imap_str_all_variants() {
        // RFC 3501 Section 7.2.1: each capability has a defined wire form.
        assert_eq!(Capability::Imap4Rev1.as_imap_str(), "IMAP4rev1");
        assert_eq!(Capability::Imap4Rev2.as_imap_str(), "IMAP4rev2");
        assert_eq!(Capability::Acl.as_imap_str(), "ACL");
        assert_eq!(
            Capability::AppendLimit(Some(1024)).as_imap_str(),
            "APPENDLIMIT=1024"
        );
        assert_eq!(Capability::AppendLimit(None).as_imap_str(), "APPENDLIMIT");
        assert_eq!(Capability::Binary.as_imap_str(), "BINARY");
        assert_eq!(Capability::Children.as_imap_str(), "CHILDREN");
        assert_eq!(
            Capability::CompressDeflate.as_imap_str(),
            "COMPRESS=DEFLATE"
        );
        assert_eq!(Capability::Condstore.as_imap_str(), "CONDSTORE");
        assert_eq!(
            Capability::CreateSpecialUse.as_imap_str(),
            "CREATE-SPECIAL-USE"
        );
        assert_eq!(Capability::Enable.as_imap_str(), "ENABLE");
        assert_eq!(Capability::Esearch.as_imap_str(), "ESEARCH");
        assert_eq!(Capability::Id.as_imap_str(), "ID");
        assert_eq!(Capability::Idle.as_imap_str(), "IDLE");
        assert_eq!(Capability::ListExtended.as_imap_str(), "LIST-EXTENDED");
        assert_eq!(Capability::ListStatus.as_imap_str(), "LIST-STATUS");
        assert_eq!(Capability::LiteralPlus.as_imap_str(), "LITERAL+");
        assert_eq!(Capability::LoginDisabled.as_imap_str(), "LOGINDISABLED");
        assert_eq!(Capability::LiteralMinus.as_imap_str(), "LITERAL-");
        assert_eq!(Capability::Metadata.as_imap_str(), "METADATA");
        assert_eq!(Capability::MetadataServer.as_imap_str(), "METADATA-SERVER");
        assert_eq!(Capability::Move.as_imap_str(), "MOVE");
        assert_eq!(Capability::MultiAppend.as_imap_str(), "MULTIAPPEND");
        assert_eq!(Capability::Namespace.as_imap_str(), "NAMESPACE");
        assert_eq!(Capability::ObjectId.as_imap_str(), "OBJECTID");
        assert_eq!(Capability::Preview.as_imap_str(), "PREVIEW");
        assert_eq!(Capability::QResync.as_imap_str(), "QRESYNC");
        assert_eq!(Capability::Quota.as_imap_str(), "QUOTA");
        assert_eq!(
            Capability::Rights("texk".into()).as_imap_str(),
            "RIGHTS=texk"
        );
        assert_eq!(Capability::SaslIr.as_imap_str(), "SASL-IR");
        assert_eq!(Capability::SaveDate.as_imap_str(), "SAVEDATE");
        assert_eq!(Capability::SearchRes.as_imap_str(), "SEARCHRES");
        assert_eq!(Capability::Sort.as_imap_str(), "SORT");
        assert_eq!(
            Capability::SortDisplay("DISPLAY".into()).as_imap_str(),
            "SORT=DISPLAY"
        );
        assert_eq!(Capability::StartTls.as_imap_str(), "STARTTLS");
        assert_eq!(Capability::SpecialUse.as_imap_str(), "SPECIAL-USE");
        assert_eq!(
            Capability::Thread("REFERENCES".into()).as_imap_str(),
            "THREAD=REFERENCES"
        );
        assert_eq!(Capability::StatusSize.as_imap_str(), "STATUS=SIZE");
        assert_eq!(Capability::Unauthenticate.as_imap_str(), "UNAUTHENTICATE");
        assert_eq!(Capability::UidPlus.as_imap_str(), "UIDPLUS");
        assert_eq!(Capability::Unselect.as_imap_str(), "UNSELECT");
        assert_eq!(Capability::Within.as_imap_str(), "WITHIN");
        assert_eq!(Capability::Utf8Accept.as_imap_str(), "UTF8=ACCEPT");
        assert_eq!(Capability::Utf8Only.as_imap_str(), "UTF8=ONLY");
        assert_eq!(
            Capability::Auth("XOAUTH2".into()).as_imap_str(),
            "AUTH=XOAUTH2"
        );
        assert_eq!(
            Capability::Other("XSPECIAL".into()).as_imap_str(),
            "XSPECIAL"
        );
    }

    // --- Capability PartialEq for string-carrying variants ---

    #[test]
    fn capability_sort_display_equality() {
        // RFC 5957: SORT=DISPLAY capability.
        // SortDisplay variants with same payload must be equal (case-insensitive).
        assert_eq!(
            Capability::SortDisplay("DISPLAY".into()),
            Capability::SortDisplay("display".into()),
            "SortDisplay must compare case-insensitively per RFC 3501 Section 7.2.1"
        );
        assert_ne!(
            Capability::SortDisplay("DISPLAY".into()),
            Capability::SortDisplay("OTHER".into()),
        );
    }

    #[test]
    fn capability_rights_equality() {
        // RFC 4314 Section 6: RIGHTS=<chars> capability.
        // Rights variants with same payload must be equal (case-insensitive).
        assert_eq!(
            Capability::Rights("texk".into()),
            Capability::Rights("TEXK".into()),
            "Rights must compare case-insensitively per RFC 3501 Section 7.2.1"
        );
        assert_ne!(
            Capability::Rights("texk".into()),
            Capability::Rights("abc".into()),
        );
    }

    // --- TaggedResponse::require_ok() tests ---
    // RFC 3501 Section 7.1 / RFC 9051 Section 7.1: OK/NO/BAD status dispatch.

    #[test]
    fn require_ok_succeeds_on_ok() {
        // RFC 3501 Section 7.1: OK indicates success.
        let tagged = TaggedResponse {
            tag: "A001".into(),
            status: StatusKind::Ok,
            code: Some(ResponseCode::ReadWrite),
            text: "SELECT completed".into(),
        };
        let result = tagged.require_ok();
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.tag, "A001");
        assert_eq!(resp.code, Some(ResponseCode::ReadWrite));
    }

    #[test]
    fn require_ok_returns_error_on_no() {
        use crate::error::Error;
        // RFC 3501 Section 7.1: NO indicates an operational error.
        let tagged = TaggedResponse {
            tag: "A002".into(),
            status: StatusKind::No,
            code: Some(ResponseCode::NonExistent),
            text: "mailbox not found".into(),
        };
        let result = tagged.require_ok();
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::No { text, code } => {
                assert_eq!(text, "mailbox not found");
                assert_eq!(code, Some(ResponseCode::NonExistent));
            }
            other => panic!("expected Error::No, got {other:?}"),
        }
    }

    #[test]
    fn require_ok_returns_error_on_bad() {
        use crate::error::Error;
        // RFC 3501 Section 7.1: BAD indicates a protocol-level error.
        let tagged = TaggedResponse {
            tag: "A003".into(),
            status: StatusKind::Bad,
            code: None,
            text: "syntax error in command".into(),
        };
        let result = tagged.require_ok();
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::Bad { text, code } => {
                assert_eq!(text, "syntax error in command");
                assert!(code.is_none());
            }
            other => panic!("expected Error::Bad, got {other:?}"),
        }
    }

    #[test]
    fn require_ok_no_without_code() {
        use crate::error::Error;
        // RFC 3501 Section 7.1: NO without a response code.
        let tagged = TaggedResponse {
            tag: "A004".into(),
            status: StatusKind::No,
            code: None,
            text: "operation failed".into(),
        };
        let result = tagged.require_ok();
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::No { text, code } => {
                assert_eq!(text, "operation failed");
                assert!(code.is_none());
            }
            other => panic!("expected Error::No, got {other:?}"),
        }
    }

    #[test]
    fn require_ok_bad_with_code() {
        use crate::error::Error;
        // RFC 3501 Section 7.1: BAD with a response code.
        let tagged = TaggedResponse {
            tag: "A005".into(),
            status: StatusKind::Bad,
            code: Some(ResponseCode::ClientBug),
            text: "invalid arguments".into(),
        };
        let result = tagged.require_ok();
        assert!(result.is_err());
        match result.unwrap_err() {
            Error::Bad { text, code } => {
                assert_eq!(text, "invalid arguments");
                assert_eq!(code, Some(ResponseCode::ClientBug));
            }
            other => panic!("expected Error::Bad, got {other:?}"),
        }
    }
}