daaki-smtp 0.1.0

An async SMTP 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
//! SMTP response parser.
//!
//! Parses multi-line SMTP responses (RFC 5321 Section 4.2) into [`SmtpResponse`],
//! including optional enhanced status codes (RFC 1893 / RFC 2034).
//!
//! # Wire format
//!
//! ```text
//! reply-line = reply-code [ SP textstring ] CRLF
//! reply-code = 3DIGIT             ; RFC 5321 Section 4.2
//! ```
//!
//! Multi-line responses use `-` after the code for continuation lines
//! and SP (or end-of-line) for the final line.

use nom::IResult;
#[cfg(test)]
use nom::{
    bytes::streaming::{tag, take_while},
    character::streaming::crlf,
    combinator::opt,
};

use crate::types::{
    AuthMechanism, EnhancedStatusCode, ServerCapabilities, SmtpExtension, SmtpResponse,
};

/// Parse a complete SMTP response (one or more lines, terminated by a final line
/// with SP or CRLF after the reply code).
///
/// RFC 5321 Section 4.2: Multi-line replies use `-` after the code for continuation
/// and SP for the final line. The code on the final line is used for the response.
/// The first enhanced status code found (RFC 2034 Section 3) is preserved.
#[cfg(test)]
pub(crate) fn parse_response(input: &[u8]) -> IResult<&[u8], SmtpResponse> {
    let mut remaining = input;
    let mut lines: Vec<String> = Vec::new();
    let mut first_enhanced: Option<EnhancedStatusCode> = None;
    let mut first_code: Option<u16> = None;
    let mut final_code: u16;

    loop {
        // Parse the 3-digit reply code
        let (rest, code) = reply_code(remaining)?;

        // RFC 5321 Section 4.2: "In a multiline reply, the reply code on
        // each of the lines MUST be the same."
        if let Some(expected) = first_code {
            if code != expected {
                return Err(nom::Err::Error(nom::error::Error::new(
                    remaining,
                    nom::error::ErrorKind::Verify,
                )));
            }
        } else {
            first_code = Some(code);
        }

        // Determine if this is a continuation line (hyphen) or final line (SP or CRLF)
        // RFC 5321 Section 4.2: continuation lines have `-`, final line has SP or goes
        // directly to CRLF.
        if rest.is_empty() {
            // Need more data to determine separator
            return Err(nom::Err::Incomplete(nom::Needed::Unknown));
        }

        let separator = rest[0];
        let is_continuation = separator == b'-';
        let has_space = separator == b' ';

        if !is_continuation && !has_space && separator != b'\r' {
            return Err(nom::Err::Error(nom::error::Error::new(
                rest,
                nom::error::ErrorKind::Char,
            )));
        }

        // Skip separator (hyphen or space), but not if the separator is \r
        let rest = if separator == b'\r' { rest } else { &rest[1..] };

        // Try to parse an enhanced status code at the start of the text.
        // RFC 2034 Section 3: enhanced code appears after the reply code and separator.
        // RFC 2034 Section 4: the enhanced code class MUST match the reply code class.
        let pre_esc = rest;
        let (rest_after_esc, enhanced) = opt(enhanced_status_code_with_trailing_space)(rest)?;

        // RFC 2034 Section 3: "Any additional text … if any, SHOULD be a
        // complete line." — try enhanced code without trailing space when
        // the code is the entire text (next byte is \r).
        let (rest_after_esc, enhanced) = if enhanced.is_none() {
            match enhanced_status_code(rest) {
                Ok((remaining, esc)) if remaining.first() == Some(&b'\r') => (remaining, Some(esc)),
                _ => (rest_after_esc, None),
            }
        } else {
            (rest_after_esc, enhanced)
        };

        let text_start = if let Some(ref esc) = enhanced {
            let reply_class = code / 100;
            if u16::from(esc.class) == reply_class {
                // Class matches — keep enhanced code, text starts after it.
                if first_enhanced.is_none() {
                    first_enhanced = Some(*esc);
                }
                rest_after_esc
            } else {
                // Class mismatch (RFC 2034 §4) — discard enhanced code,
                // include its digits in the text.
                pre_esc
            }
        } else {
            rest_after_esc
        };

        // Collect the remaining text up to CRLF
        let (rest, text_bytes) = take_while(|b: u8| b != b'\r' && b != b'\n')(text_start)?;

        // Consume CRLF — RFC 5321 Section 2.3.8
        let (rest, _) = crlf(rest)?;

        // Lossy-convert text from bytes to String (servers may send non-UTF-8 data)
        let text = String::from_utf8_lossy(text_bytes).into_owned();
        lines.push(text);

        final_code = code;
        remaining = rest;

        if !is_continuation {
            break;
        }
    }

    Ok((
        remaining,
        SmtpResponse {
            code: final_code,
            enhanced_code: first_enhanced,
            lines,
        },
    ))
}

/// Parse a single SMTP reply code (3 ASCII digits).
///
/// RFC 5321 Section 4.2: `reply-code = %x32-35 %x30-35 %x30-39`
/// - First digit: 2-5 (severity class)
/// - Second digit: 0-5 (category)
/// - Third digit: 0-9 (fine-grained status)
#[cfg(test)]
pub(crate) fn reply_code(input: &[u8]) -> IResult<&[u8], u16> {
    // We need exactly 3 bytes
    if input.len() < 3 {
        return Err(nom::Err::Incomplete(nom::Needed::new(3 - input.len())));
    }

    let d0 = input[0];
    let d1 = input[1];
    let d2 = input[2];

    // All three must be ASCII digits
    if !d0.is_ascii_digit() || !d1.is_ascii_digit() || !d2.is_ascii_digit() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Digit,
        )));
    }

    // RFC 5321 Section 4.2: reply-code = %x32-35 %x30-35 %x30-39
    // First digit must be 2-5, second digit must be 0-5.
    if !(b'2'..=b'5').contains(&d0) || !(b'0'..=b'5').contains(&d1) {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }

    let code = u16::from(d0 - b'0') * 100 + u16::from(d1 - b'0') * 10 + u16::from(d2 - b'0');

    Ok((&input[3..], code))
}

/// Generate an enhanced status code parser for a given nom mode (streaming or complete).
///
/// RFC 1893 Section 2: `status-code = class "." subject "." detail`
/// - class: single digit, one of 2, 4, 5
/// - subject: 1-3 digit number
/// - detail: 1-3 digit number
///
/// RFC 2034 Section 3: enhanced status codes appear in SMTP responses
/// after the three-digit reply code.
macro_rules! define_enhanced_status_code_parser {
    ($name:ident, $(#[$meta:meta])*, $one_of:path, $tag:path, $take_while1:path) => {
        $(#[$meta])*
        fn $name(input: &[u8]) -> IResult<&[u8], EnhancedStatusCode> {
            // Parse class digit (must be 2, 4, or 5) — RFC 1893 Section 2
            let (rest, class_char) = $one_of("245")(input)?;
            // one_of("245") guarantees the digit is ASCII 2/4/5; the subtraction yields {2, 4, 5}
            #[allow(clippy::cast_possible_truncation)]
            let class = (class_char as u32 - '0' as u32) as u8;

            // Parse '.'
            let (rest, _) = $tag(b".")(rest)?;

            // Parse subject (1-3 digits) — RFC 1893 Section 2
            let (rest, subject_bytes) = $take_while1(|b: u8| b.is_ascii_digit())(rest)?;
            if subject_bytes.len() > 3 {
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::TooLarge,
                )));
            }
            let subject = parse_digits(subject_bytes);

            // Parse '.'
            let (rest, _) = $tag(b".")(rest)?;

            // Parse detail (1-3 digits) — RFC 1893 Section 2
            let (rest, detail_bytes) = $take_while1(|b: u8| b.is_ascii_digit())(rest)?;
            if detail_bytes.len() > 3 {
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::TooLarge,
                )));
            }
            let detail = parse_digits(detail_bytes);

            Ok((
                rest,
                EnhancedStatusCode {
                    class,
                    subject,
                    detail,
                },
            ))
        }
    };
}

define_enhanced_status_code_parser!(
    enhanced_status_code,
    #[cfg(test)],
    nom::character::streaming::one_of,
    nom::bytes::streaming::tag,
    nom::bytes::streaming::take_while1
);

/// Parse an enhanced status code followed by a trailing space.
///
/// This ensures we only consume an enhanced code when it's properly delimited,
/// preventing false matches on strings like `2.0` in the text body.
///
/// RFC 2034 Section 3: The enhanced status code is separated from the
/// following text by a single space.
#[cfg(test)]
fn enhanced_status_code_with_trailing_space(input: &[u8]) -> IResult<&[u8], EnhancedStatusCode> {
    let (rest, esc) = enhanced_status_code(input)?;
    // Must be followed by a space to be a valid enhanced code in a response line
    let (rest, _) = tag(b" ")(rest)?;
    Ok((rest, esc))
}

/// Convert a slice of ASCII digit bytes to a u16 per RFC 1893 Section 2.
///
/// Used to parse the subject and detail components of enhanced status codes
/// (`class.subject.detail`), where each component is 1-3 ASCII digits.
///
/// # Panics
///
/// This function is only called with validated digit slices of length 1-3,
/// so overflow is impossible for u16 (max value 999).
fn parse_digits(bytes: &[u8]) -> u16 {
    let mut val: u16 = 0;
    for &b in bytes {
        // Caller guarantees all bytes are ASCII digits
        val = val * 10 + u16::from(b - b'0');
    }
    val
}

/// Parse the EHLO response lines into server capabilities.
///
/// RFC 5321 Section 4.1.1.1: The first line of the EHLO response is the
/// server greeting name. Subsequent lines advertise extensions.
///
/// Each extension keyword is matched case-insensitively per RFC 5321 Section 2.4.
pub(crate) fn parse_ehlo_capabilities(response: &SmtpResponse) -> ServerCapabilities {
    let mut caps = ServerCapabilities::default();

    for (i, line) in response.lines.iter().enumerate() {
        if i == 0 {
            // RFC 5321 Section 4.1.1.1:
            //   ehlo-ok-rsp = "250" SP Domain [ SP ehlo-greet ] CRLF
            // The Domain is the first whitespace-delimited token; the
            // optional ehlo-greet text that follows is informational.
            caps.greeting_name = match line.find(' ') {
                Some(pos) => line[..pos].to_owned(),
                None => line.clone(),
            };
            continue;
        }

        // Split on first space to get keyword and optional parameters
        let (keyword, params) = match line.find(' ') {
            Some(pos) => (&line[..pos], Some(line[pos + 1..].trim())),
            None => (line.as_str(), None),
        };

        // RFC 5321 Section 2.4: SMTP keywords are case-insensitive
        let keyword_upper = keyword.to_ascii_uppercase();

        // RFC 2554 §3 (obsoleted by RFC 4954 §3): some legacy servers
        // advertise AUTH using the deprecated "AUTH=PLAIN LOGIN" form
        // instead of the standard "AUTH PLAIN LOGIN". Normalize by
        // treating the mechanism after '=' as the first in the list.
        if keyword_upper.starts_with("AUTH=") && keyword_upper.len() > 5 {
            // Extract the mechanism name after '=' using original case
            // from the keyword (everything after "AUTH=").
            let first_mech = &keyword[5..];
            let all_mechs = match params {
                Some(p) if !p.is_empty() => format!("{first_mech} {p}"),
                _ => first_mech.to_owned(),
            };
            let mechanisms: Vec<AuthMechanism> = all_mechs
                .split_whitespace()
                .map(parse_auth_mechanism)
                .collect();
            caps.extensions.push(SmtpExtension::Auth(mechanisms));
            continue;
        }

        let extension = match keyword_upper.as_str() {
            // RFC 1652: 8bit-MIMEtransport
            "8BITMIME" => SmtpExtension::EightBitMime,
            // RFC 1854 (also RFC 2920): Command Pipelining
            "PIPELINING" => SmtpExtension::Pipelining,
            // RFC 1870: Message Size Declaration
            "SIZE" => {
                let size_limit = params
                    .and_then(|p| if p.is_empty() { None } else { Some(p) })
                    .and_then(|p| p.parse::<u64>().ok())
                    // RFC 1870 Section 5: a value of 0 means the server
                    // does not have a fixed maximum message size.
                    .and_then(|n| if n == 0 { None } else { Some(n) });
                SmtpExtension::Size(size_limit)
            }
            // RFC 3207: SMTP Service Extension for Secure SMTP over TLS
            "STARTTLS" => SmtpExtension::StartTls,
            // RFC 4954: SMTP Service Extension for Authentication
            "AUTH" => {
                let mechanisms = params
                    .map(|p| {
                        p.split_whitespace()
                            .map(parse_auth_mechanism)
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default();
                SmtpExtension::Auth(mechanisms)
            }
            // RFC 3030: SMTP Service Extensions for Transmission of Large and Binary MIME Messages
            "CHUNKING" => SmtpExtension::Chunking,
            // RFC 3030: BINARYMIME extension (RFC 1830 used "BINARY")
            "BINARYMIME" | "BINARY" => SmtpExtension::BinaryMime,
            // RFC 6531: SMTP Extension for Internationalized Email
            "SMTPUTF8" => SmtpExtension::SmtpUtf8,
            // RFC 2034 / RFC 1893: Enhanced Status Codes
            "ENHANCEDSTATUSCODES" => SmtpExtension::EnhancedStatusCodes,
            // RFC 4959: SASL Initial Response
            "SASL-IR" => SmtpExtension::SaslIr,
            // RFC 3461: Delivery Status Notifications
            "DSN" => SmtpExtension::Dsn,
            // RFC 8689: REQUIRETLS per-message TLS enforcement
            "REQUIRETLS" => SmtpExtension::RequireTls,
            // RFC 4865: FUTURERELEASE scheduled delivery
            "FUTURERELEASE" => {
                // RFC 4865 Section 4: EHLO keyword may include
                // "max-interval max-datetime" parameters.
                let (max_interval, max_datetime) = match params {
                    Some(p) if !p.is_empty() => {
                        let mut parts = p.splitn(2, ' ');
                        let interval = parts.next().and_then(|s| s.parse::<u64>().ok());
                        let datetime = parts.next().map(str::to_owned);
                        (interval, datetime)
                    }
                    _ => (None, None),
                };
                SmtpExtension::FutureRelease {
                    max_interval,
                    max_datetime,
                }
            }
            // RFC 2852: DELIVERBY time-bound delivery
            "DELIVERBY" => {
                let max_seconds = params
                    .and_then(|p| if p.is_empty() { None } else { Some(p) })
                    .and_then(|p| p.parse::<u64>().ok());
                SmtpExtension::DeliverBy(max_seconds)
            }
            // RFC 6758: MT-PRIORITY message priority signaling
            "MT-PRIORITY" => SmtpExtension::MtPriority,
            // RFC 5321 Section 4.1.1.6: VRFY command support
            "VRFY" => SmtpExtension::Vrfy,
            // RFC 5321 Section 4.1.1.7: EXPN command support
            "EXPN" => SmtpExtension::Expn,
            // RFC 3865: NO-SOLICITING advertising policy
            "NO-SOLICITING" => {
                let keyword = params
                    .and_then(|p| if p.is_empty() { None } else { Some(p) })
                    .map(str::to_owned);
                SmtpExtension::NoSoliciting(keyword)
            }
            // Unrecognized extension — preserve the full line
            _ => SmtpExtension::Other(line.clone()),
        };

        caps.extensions.push(extension);
    }

    caps
}

/// Parse an auth mechanism name to the corresponding enum variant.
///
/// RFC 4954 Section 3: AUTH mechanism names are case-insensitive.
fn parse_auth_mechanism(name: &str) -> AuthMechanism {
    match name.to_ascii_uppercase().as_str() {
        "PLAIN" => AuthMechanism::Plain,
        // AUTH LOGIN: de-facto standard (draft-murchison-sasl-login),
        // two-step challenge-response following RFC 4954 Section 4 pattern.
        "LOGIN" => AuthMechanism::Login,
        // RFC 7628 Section 3.1: OAUTHBEARER SASL mechanism.
        "OAUTHBEARER" => AuthMechanism::OAuthBearer,
        "XOAUTH2" => AuthMechanism::XOAuth2,
        _ => AuthMechanism::Other(name.to_owned()),
    }
}

/// Try to strip an enhanced status code prefix from a response text line.
///
/// If the text starts with a valid enhanced status code followed by a space
/// or end-of-string (RFC 2034 Section 3), returns `Some((code, remaining_text))`.
/// Otherwise returns `None` and the text is unchanged.
///
/// RFC 2034 Section 3: Enhanced status codes appear in SMTP response text
/// after the three-digit reply code and separator. "Any additional text in
/// the reply, if any, SHOULD be a complete line." — the "if any" means
/// trailing text is optional.
pub(crate) fn strip_enhanced_code(text: &str) -> Option<(EnhancedStatusCode, &str)> {
    use nom::bytes::complete::tag as tag_complete;

    let bytes = text.as_bytes();
    match enhanced_status_code_complete(bytes) {
        Ok((rest, esc)) => {
            // RFC 2034 Section 3: enhanced code followed by space and text.
            match tag_complete::<_, _, nom::error::Error<&[u8]>>(b" ")(rest) {
                Ok((after_space, _)) => {
                    let consumed = bytes.len() - after_space.len();
                    Some((esc, &text[consumed..]))
                }
                _ => {
                    // RFC 2034 Section 3: text after enhanced code is optional.
                    // Accept the code when it comprises the entire text.
                    if rest.is_empty() {
                        Some((esc, ""))
                    } else {
                        None
                    }
                }
            }
        }
        _ => None,
    }
}

/// Parse an enhanced status code from a complete string (for use in capability
/// parsing or other non-wire contexts).
///
/// RFC 1893 Section 2: Parses the `class.subject.detail` format.
#[cfg(test)]
pub(crate) fn parse_enhanced_code_from_str(s: &str) -> Option<EnhancedStatusCode> {
    // Use a complete (non-streaming) parser since we have the full input.
    match enhanced_status_code_complete(s.as_bytes()) {
        Ok(([], esc)) => Some(esc),
        _ => None,
    }
}

// Non-streaming variant of `enhanced_status_code` for use when the full
// input is available (e.g., parsing from owned strings).
//
// RFC 1893 Section 2: `status-code = class "." subject "." detail`
define_enhanced_status_code_parser!(
    enhanced_status_code_complete,
    ,
    nom::character::complete::one_of,
    nom::bytes::complete::tag,
    nom::bytes::complete::take_while1
);

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::similar_names)]
mod tests {
    use super::*;

    // ── reply_code ──────────────────────────────────────────────────────

    #[test]
    fn reply_code_250() {
        let (rest, code) = reply_code(b"250 OK").unwrap();
        assert_eq!(code, 250);
        assert_eq!(rest, b" OK");
    }

    #[test]
    fn reply_code_421() {
        let (rest, code) = reply_code(b"421 ").unwrap();
        assert_eq!(code, 421);
        assert_eq!(rest, b" ");
    }

    #[test]
    fn reply_code_550() {
        let (_, code) = reply_code(b"550-User").unwrap();
        assert_eq!(code, 550);
    }

    #[test]
    fn reply_code_out_of_range_100() {
        assert!(reply_code(b"100 ").is_err());
    }

    #[test]
    fn reply_code_out_of_range_600() {
        assert!(reply_code(b"600 ").is_err());
    }

    #[test]
    fn reply_code_non_digit() {
        assert!(reply_code(b"2x0 ").is_err());
    }

    #[test]
    fn reply_code_too_short() {
        let result = reply_code(b"25");
        assert!(matches!(result, Err(nom::Err::Incomplete(_))));
    }

    // ── enhanced_status_code ────────────────────────────────────────────

    #[test]
    fn enhanced_code_2_1_0() {
        let (rest, esc) = enhanced_status_code(b"2.1.0 OK").unwrap();
        assert_eq!(esc.class, 2);
        assert_eq!(esc.subject, 1);
        assert_eq!(esc.detail, 0);
        assert_eq!(rest, b" OK");
    }

    #[test]
    fn enhanced_code_4_7_0() {
        let (rest, esc) = enhanced_status_code(b"4.7.0 Try again").unwrap();
        assert_eq!(esc.class, 4);
        assert_eq!(esc.subject, 7);
        assert_eq!(esc.detail, 0);
        assert_eq!(rest, b" Try again");
    }

    #[test]
    fn enhanced_code_5_1_1() {
        let (_, esc) = enhanced_status_code(b"5.1.1 ").unwrap();
        assert_eq!(esc.class, 5);
        assert_eq!(esc.subject, 1);
        assert_eq!(esc.detail, 1);
    }

    #[test]
    fn enhanced_code_multi_digit_subject_detail() {
        let (rest, esc) = enhanced_status_code(b"2.123.456 ").unwrap();
        assert_eq!(esc.class, 2);
        assert_eq!(esc.subject, 123);
        assert_eq!(esc.detail, 456);
        assert_eq!(rest, b" ");
    }

    #[test]
    fn enhanced_code_invalid_class_3() {
        // Class 3 is not valid per RFC 1893
        assert!(enhanced_status_code(b"3.1.0 ").is_err());
    }

    #[test]
    fn enhanced_code_invalid_class_1() {
        assert!(enhanced_status_code(b"1.0.0 ").is_err());
    }

    // ── parse_response ──────────────────────────────────────────────────

    #[test]
    fn single_line_250_ok() {
        let input = b"250 OK\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        assert_eq!(resp.lines, vec!["OK"]);
        assert!(resp.enhanced_code.is_none());
    }

    #[test]
    fn single_line_with_enhanced_code() {
        let input = b"250 2.1.0 OK\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        assert_eq!(resp.lines, vec!["OK"]);
        let esc = resp.enhanced_code.unwrap();
        assert_eq!(esc.class, 2);
        assert_eq!(esc.subject, 1);
        assert_eq!(esc.detail, 0);
    }

    #[test]
    fn multi_line_ehlo_response() {
        let input = b"250-mail.example.com\r\n250-PIPELINING\r\n250 SIZE 10485760\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        assert_eq!(resp.lines.len(), 3);
        assert_eq!(resp.lines[0], "mail.example.com");
        assert_eq!(resp.lines[1], "PIPELINING");
        assert_eq!(resp.lines[2], "SIZE 10485760");
    }

    #[test]
    fn response_4xx_with_enhanced() {
        let input = b"421 4.7.0 Try again later\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 421);
        assert!(resp.is_transient_error());
        assert_eq!(resp.lines, vec!["Try again later"]);
        let esc = resp.enhanced_code.unwrap();
        assert_eq!(esc.class, 4);
        assert_eq!(esc.subject, 7);
        assert_eq!(esc.detail, 0);
    }

    #[test]
    fn response_5xx_with_enhanced() {
        let input = b"550 5.1.1 User unknown\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 550);
        assert!(resp.is_permanent_error());
        assert_eq!(resp.lines, vec!["User unknown"]);
        let esc = resp.enhanced_code.unwrap();
        assert_eq!(esc.class, 5);
        assert_eq!(esc.subject, 1);
        assert_eq!(esc.detail, 1);
    }

    #[test]
    fn truncated_no_crlf() {
        let input = b"250 OK";
        let result = parse_response(input);
        assert!(matches!(result, Err(nom::Err::Incomplete(_))));
    }

    #[test]
    fn truncated_partial_code() {
        let input = b"25";
        let result = parse_response(input);
        assert!(matches!(result, Err(nom::Err::Incomplete(_))));
    }

    #[test]
    fn response_no_text_bare_code() {
        // "250\r\n" — code followed directly by CRLF, no space, no text
        let input = b"250\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        assert_eq!(resp.lines, vec![""]);
    }

    #[test]
    fn response_empty_text_after_space() {
        // "250 \r\n" — code + space but no text
        let input = b"250 \r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        assert_eq!(resp.lines, vec![""]);
    }

    #[test]
    fn multi_line_with_enhanced_on_some_lines() {
        // Enhanced code on first line, not on second
        let input = b"250-2.1.0 Sender OK\r\n250 Recipient OK\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        assert_eq!(resp.lines.len(), 2);
        assert_eq!(resp.lines[0], "Sender OK");
        assert_eq!(resp.lines[1], "Recipient OK");
        // First enhanced code is preserved
        let esc = resp.enhanced_code.unwrap();
        assert_eq!(esc.class, 2);
        assert_eq!(esc.subject, 1);
        assert_eq!(esc.detail, 0);
    }

    #[test]
    fn multi_line_enhanced_only_on_later_line() {
        // No enhanced code on first line, enhanced on second
        let input = b"250-Hello there\r\n250 2.0.0 OK\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        assert_eq!(resp.lines, vec!["Hello there", "OK"]);
        let esc = resp.enhanced_code.unwrap();
        assert_eq!(esc.class, 2);
        assert_eq!(esc.subject, 0);
        assert_eq!(esc.detail, 0);
    }

    #[test]
    fn continuation_lines_with_different_codes_must_fail() {
        // RFC 5321 Section 4.2: "In a multiline reply, the reply code on
        // each of the lines MUST be the same." Inconsistent codes are a
        // protocol violation and must be rejected.
        let input = b"251-Forwarding\r\n250 OK\r\n";
        let result = parse_response(input);
        assert!(
            result.is_err(),
            "inconsistent reply codes in multi-line response must be rejected (RFC 5321 Section 4.2)"
        );
    }

    #[test]
    fn response_354_intermediate() {
        let input = b"354 Start mail input\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 354);
        assert!(resp.is_intermediate());
        assert_eq!(resp.lines, vec!["Start mail input"]);
    }

    #[test]
    fn response_with_remaining_data() {
        // Parser should stop after the response and leave remaining data
        let input = b"250 OK\r\n220 Ready\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert_eq!(rest, b"220 Ready\r\n");
        assert_eq!(resp.code, 250);
    }

    #[test]
    fn response_non_ascii_text() {
        // Servers may send non-ASCII bytes; we do lossy UTF-8 conversion
        let mut input = Vec::new();
        input.extend_from_slice(b"250 Hello \xC0\xC1\r\n");
        let (rest, resp) = parse_response(&input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        // Lossy conversion replaces invalid bytes with U+FFFD
        assert!(resp.lines[0].contains('\u{FFFD}'));
    }

    // ── parse_ehlo_capabilities ─────────────────────────────────────────

    #[test]
    fn ehlo_full_capabilities() {
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec![
                "mail.example.com".into(),
                "8BITMIME".into(),
                "PIPELINING".into(),
                "SIZE 10485760".into(),
                "STARTTLS".into(),
                "AUTH PLAIN XOAUTH2".into(),
                "CHUNKING".into(),
                "BINARYMIME".into(),
                "SMTPUTF8".into(),
                "ENHANCEDSTATUSCODES".into(),
            ],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert_eq!(caps.greeting_name, "mail.example.com");
        assert_eq!(caps.extensions.len(), 9);
        assert!(caps.extensions.contains(&SmtpExtension::EightBitMime));
        assert!(caps.extensions.contains(&SmtpExtension::Pipelining));
        assert!(caps
            .extensions
            .contains(&SmtpExtension::Size(Some(10_485_760))));
        assert!(caps.extensions.contains(&SmtpExtension::StartTls));
        assert!(caps.extensions.contains(&SmtpExtension::Chunking));
        assert!(caps.extensions.contains(&SmtpExtension::BinaryMime));
        assert!(caps.extensions.contains(&SmtpExtension::SmtpUtf8));
        assert!(caps
            .extensions
            .contains(&SmtpExtension::EnhancedStatusCodes));
        assert!(caps.supports_auth(&AuthMechanism::Plain));
        assert!(caps.supports_auth(&AuthMechanism::XOAuth2));
    }

    #[test]
    fn ehlo_size_without_limit() {
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "SIZE".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.extensions.contains(&SmtpExtension::Size(None)));
    }

    #[test]
    fn ehlo_size_zero_means_no_limit() {
        // RFC 1870 Section 5: "A numeric value of zero in the SIZE
        // parameter of the EHLO response indicates that the server does
        // not have a fixed maximum message size."
        // SIZE 0 must be stored as Size(None), not Size(Some(0)).
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "SIZE 0".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.extensions.contains(&SmtpExtension::Size(None)),
            "SIZE 0 must be treated as no limit (RFC 1870 Section 5), \
             got: {:?}",
            caps.extensions
        );
        assert!(
            caps.size_limit().is_none(),
            "size_limit() must return None for SIZE 0"
        );
    }

    #[test]
    fn ehlo_unknown_extensions() {
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec![
                "mx.example.org".into(),
                "XFORWARD".into(),
                "PIPELINING".into(),
                "XCLIENT".into(),
            ],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert_eq!(caps.greeting_name, "mx.example.org");
        assert_eq!(caps.extensions.len(), 3);
        assert!(caps
            .extensions
            .contains(&SmtpExtension::Other("XFORWARD".into())));
        assert!(caps.extensions.contains(&SmtpExtension::Pipelining));
        assert!(caps
            .extensions
            .contains(&SmtpExtension::Other("XCLIENT".into())));
    }

    #[test]
    fn ehlo_auth_multiple_mechanisms() {
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec![
                "mail.example.com".into(),
                "AUTH PLAIN LOGIN XOAUTH2 CRAM-MD5".into(),
            ],
        };
        let caps = parse_ehlo_capabilities(&response);
        let auth_ext = caps
            .extensions
            .iter()
            .find(|e| matches!(e, SmtpExtension::Auth(_)));
        assert!(auth_ext.is_some());
        if let Some(SmtpExtension::Auth(mechs)) = auth_ext {
            assert_eq!(mechs.len(), 4);
            assert_eq!(mechs[0], AuthMechanism::Plain);
            assert_eq!(mechs[1], AuthMechanism::Login);
            assert_eq!(mechs[2], AuthMechanism::XOAuth2);
            assert_eq!(mechs[3], AuthMechanism::Other("CRAM-MD5".into()));
        }
    }

    #[test]
    fn ehlo_case_insensitive_keywords() {
        // RFC 5321 Section 2.4: keywords are case-insensitive
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec![
                "mail.example.com".into(),
                "pipelining".into(),
                "Starttls".into(),
                "size 1024".into(),
            ],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.extensions.contains(&SmtpExtension::Pipelining));
        assert!(caps.extensions.contains(&SmtpExtension::StartTls));
        assert!(caps.extensions.contains(&SmtpExtension::Size(Some(1024))));
    }

    #[test]
    fn ehlo_empty_response() {
        // Edge case: single-line EHLO with only greeting
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert_eq!(caps.greeting_name, "mail.example.com");
        assert!(caps.extensions.is_empty());
    }

    #[test]
    fn ehlo_auth_case_insensitive() {
        // Auth mechanism names should be matched case-insensitively
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "AUTH plain xoauth2".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.supports_auth(&AuthMechanism::Plain));
        assert!(caps.supports_auth(&AuthMechanism::XOAuth2));
    }

    #[test]
    fn parse_enhanced_code_from_str_valid() {
        let esc = parse_enhanced_code_from_str("2.1.0").unwrap();
        assert_eq!(esc.class, 2);
        assert_eq!(esc.subject, 1);
        assert_eq!(esc.detail, 0);
    }

    #[test]
    fn parse_enhanced_code_from_str_invalid() {
        assert!(parse_enhanced_code_from_str("2.1").is_none());
        assert!(parse_enhanced_code_from_str("invalid").is_none());
        assert!(parse_enhanced_code_from_str("3.0.0").is_none());
    }

    // ── streaming / complete parity tests (lock down before refactoring) ──

    /// Streaming and complete parsers must produce identical results for
    /// valid inputs. This locks down parity before deduplication.
    #[test]
    fn enhanced_status_code_streaming_complete_parity() {
        let cases: &[&[u8]] = &[b"2.1.0 ", b"4.7.0 ", b"5.1.1 ", b"2.123.456 ", b"5.0.0 "];
        for input in cases {
            let (s_rest, s_esc) = enhanced_status_code(input).unwrap();
            let (c_rest, c_esc) = enhanced_status_code_complete(input).unwrap();
            assert_eq!(
                s_esc,
                c_esc,
                "streaming and complete parsers disagree on {:?}",
                String::from_utf8_lossy(input)
            );
            assert_eq!(
                s_rest,
                c_rest,
                "streaming and complete parsers consumed different amounts on {:?}",
                String::from_utf8_lossy(input)
            );
        }
    }

    /// Both parsers must reject the same invalid classes.
    #[test]
    fn enhanced_status_code_streaming_complete_reject_same() {
        let invalid: &[&[u8]] = &[b"3.1.0 ", b"1.0.0 ", b"0.0.0 "];
        for input in invalid {
            assert!(
                enhanced_status_code(input).is_err(),
                "streaming should reject {:?}",
                String::from_utf8_lossy(input)
            );
            assert!(
                enhanced_status_code_complete(input).is_err(),
                "complete should reject {:?}",
                String::from_utf8_lossy(input)
            );
        }
    }

    #[test]
    fn multi_line_ehlo_real_world() {
        // Simulate a real-world EHLO response as received on the wire
        let input = b"250-smtp.gmail.com at your service\r\n\
                      250-SIZE 35882577\r\n\
                      250-8BITMIME\r\n\
                      250-STARTTLS\r\n\
                      250-ENHANCEDSTATUSCODES\r\n\
                      250-PIPELINING\r\n\
                      250-CHUNKING\r\n\
                      250 SMTPUTF8\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        assert_eq!(resp.lines.len(), 8);

        let caps = parse_ehlo_capabilities(&resp);
        // RFC 5321 Section 4.1.1.1: greeting_name is the Domain only.
        assert_eq!(caps.greeting_name, "smtp.gmail.com");
        assert!(caps
            .extensions
            .contains(&SmtpExtension::Size(Some(35_882_577))));
        assert!(caps.extensions.contains(&SmtpExtension::EightBitMime));
        assert!(caps.extensions.contains(&SmtpExtension::StartTls));
        assert!(caps
            .extensions
            .contains(&SmtpExtension::EnhancedStatusCodes));
        assert!(caps.extensions.contains(&SmtpExtension::Pipelining));
        assert!(caps.extensions.contains(&SmtpExtension::Chunking));
        assert!(caps.extensions.contains(&SmtpExtension::SmtpUtf8));
    }

    #[test]
    fn multi_line_all_with_enhanced_codes() {
        // Each line has an enhanced status code — only the first is captured
        let input = b"550-5.1.1 The email account does not exist\r\n\
                      550 5.1.1 Try again\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 550);
        assert_eq!(resp.lines.len(), 2);
        assert_eq!(resp.lines[0], "The email account does not exist");
        assert_eq!(resp.lines[1], "Try again");
        let esc = resp.enhanced_code.unwrap();
        assert_eq!(esc.class, 5);
        assert_eq!(esc.subject, 1);
        assert_eq!(esc.detail, 1);
    }

    #[test]
    fn response_220_greeting() {
        let input = b"220 mail.example.com ESMTP ready\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 220);
        assert_eq!(resp.lines, vec!["mail.example.com ESMTP ready"]);
    }

    #[test]
    fn multi_line_continuation_truncated() {
        // Continuation line without final line — should be Incomplete
        let input = b"250-line1\r\n250-line2\r\n";
        let result = parse_response(input);
        assert!(matches!(result, Err(nom::Err::Incomplete(_))));
    }

    // ── RFC 2034 §4 — enhanced status code class must match reply code ──

    #[test]
    fn enhanced_code_class_mismatch_discarded() {
        // RFC 2034 Section 4: "The class (first digit) of the enhanced
        // status code MUST match the basic-status class." A 250 reply
        // with a 5.x.x enhanced code is invalid — the enhanced code must
        // be discarded rather than stored.
        let input = b"250 5.1.1 Sender OK\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        // The enhanced code class (5) doesn't match reply class (2),
        // so it must be discarded.
        assert!(
            resp.enhanced_code.is_none(),
            "enhanced code with mismatched class must be discarded (RFC 2034 Section 4)"
        );
        // The text "5.1.1 Sender OK" must be preserved when the enhanced
        // code is discarded — the digits stay in the text.
        assert_eq!(resp.lines, vec!["5.1.1 Sender OK"]);
    }

    #[test]
    fn enhanced_code_class_match_preserved() {
        // When the class matches, the enhanced code is preserved.
        let input = b"250 2.1.0 Sender OK\r\n";
        let (_, resp) = parse_response(input).unwrap();
        assert_eq!(resp.code, 250);
        let esc = resp.enhanced_code.unwrap();
        assert_eq!(esc.class, 2);
    }

    // ── RFC 2034 §3 — enhanced code with no trailing text ─────────────

    #[test]
    fn enhanced_code_extracted_without_trailing_text() {
        // RFC 2034 Section 3: "Any additional text … if any, SHOULD be a
        // complete line." The "if any" means text after the enhanced code
        // is optional. The enhanced code must still be extracted when the
        // response text consists solely of the code (no trailing space).
        let input = b"550 5.1.1\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 550);
        let esc = resp.enhanced_code.unwrap();
        assert_eq!(esc.class, 5);
        assert_eq!(esc.subject, 1);
        assert_eq!(esc.detail, 1);
        assert_eq!(resp.lines, vec![""]);
    }

    #[test]
    fn enhanced_code_extracted_without_trailing_text_250() {
        // RFC 2034 Section 3: enhanced code with no trailing text on a
        // 250 success response.
        let input = b"250 2.0.0\r\n";
        let (rest, resp) = parse_response(input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        let esc = resp.enhanced_code.unwrap();
        assert_eq!(esc.class, 2);
        assert_eq!(esc.subject, 0);
        assert_eq!(esc.detail, 0);
        assert_eq!(resp.lines, vec![""]);
    }

    // ── RFC 2554 §3 / RFC 4954 §3 — AUTH= EHLO keyword form ──────────

    #[test]
    fn ehlo_auth_equals_form() {
        // RFC 2554 Section 3 (obsoleted by RFC 4954): some legacy
        // servers advertise AUTH using "AUTH=PLAIN LOGIN" instead of
        // "AUTH PLAIN LOGIN". The parser must handle both forms.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["legacy.server.com".into(), "AUTH=PLAIN LOGIN".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.supports_auth(&AuthMechanism::Plain),
            "AUTH=PLAIN form must be recognized (RFC 2554 Section 3)"
        );
        assert!(
            caps.supports_auth(&AuthMechanism::Login),
            "AUTH=PLAIN LOGIN must include LOGIN mechanism"
        );
    }

    #[test]
    fn ehlo_auth_equals_single_mechanism() {
        // "AUTH=PLAIN" with no additional mechanisms.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["legacy.server.com".into(), "AUTH=PLAIN".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.supports_auth(&AuthMechanism::Plain),
            "AUTH=PLAIN (single mechanism) must be recognized"
        );
    }

    #[test]
    fn ehlo_auth_equals_mixed_case() {
        // "auth=plain login" — lowercase AUTH= form.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["legacy.server.com".into(), "auth=plain login".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.supports_auth(&AuthMechanism::Plain),
            "auth=plain (lowercase) must be recognized"
        );
    }

    #[test]
    fn strip_enhanced_code_entire_text() {
        // RFC 2034 Section 3: when the text after the reply code IS the
        // enhanced code with no subsequent text, strip_enhanced_code must
        // return the code and empty remaining text.
        let result = strip_enhanced_code("5.1.1");
        assert!(result.is_some(), "expected Some for bare enhanced code");
        let (esc, rest) = result.unwrap();
        assert_eq!(esc.class, 5);
        assert_eq!(esc.subject, 1);
        assert_eq!(esc.detail, 1);
        assert_eq!(rest, "");
    }

    // ── RFC 5321 §4.1.1.1 — greeting_name must be Domain only ──────────

    #[test]
    fn ehlo_greeting_name_is_domain_only() {
        // RFC 5321 Section 4.1.1.1:
        //   ehlo-ok-rsp = "250" SP Domain [ SP ehlo-greet ] CRLF
        // The greeting_name must be just the Domain, not the full line
        // including the optional ehlo-greet text.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["smtp.gmail.com at your service".into(), "PIPELINING".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert_eq!(
            caps.greeting_name, "smtp.gmail.com",
            "RFC 5321 Section 4.1.1.1: greeting_name must be the Domain \
             only, not the full ehlo-greet text"
        );
    }

    #[test]
    fn ehlo_greeting_name_domain_only_no_greet() {
        // When the first line is just a domain with no ehlo-greet,
        // the greeting_name should be the domain as-is.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "PIPELINING".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert_eq!(caps.greeting_name, "mail.example.com");
    }

    // ── RFC 1830 — legacy BINARY keyword must be recognized ─────────

    #[test]
    fn ehlo_recognizes_legacy_binary_keyword() {
        // RFC 1830 (obsoleted by RFC 3030) used the keyword "BINARY"
        // for what RFC 3030 renamed to "BINARYMIME". Legacy servers
        // may still advertise "BINARY". The parser must recognize
        // both keywords so that supports_binarymime() returns true.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec![
                "legacy.server.com".into(),
                "BINARY".into(),
                "CHUNKING".into(),
            ],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.supports_binarymime(),
            "RFC 1830: legacy 'BINARY' keyword must be recognized \
             as BINARYMIME (RFC 3030 obsoletes RFC 1830 but the old \
             keyword may still appear in the wild)"
        );
    }

    #[test]
    fn ehlo_recognizes_legacy_binary_keyword_lowercase() {
        // RFC 5321 Section 2.4: EHLO keywords are case-insensitive.
        // "binary" (lowercase) must also be recognized.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["legacy.server.com".into(), "binary".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.supports_binarymime(),
            "RFC 1830 / RFC 5321 Section 2.4: lowercase 'binary' must \
             be recognized as BINARYMIME"
        );
    }

    // ── AUTH LOGIN — de-facto standard parsing ──────────────────────────

    #[test]
    fn ehlo_parses_login_as_dedicated_variant() {
        // AUTH LOGIN must be parsed as AuthMechanism::Login, not Other("LOGIN").
        // draft-murchison-sasl-login / RFC 4954 Section 4 pattern.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "AUTH PLAIN LOGIN".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.supports_auth(&AuthMechanism::Login));
        assert!(caps.supports_auth(&AuthMechanism::Plain));
    }

    #[test]
    fn ehlo_parses_login_case_insensitive() {
        // RFC 4954 Section 3 / RFC 4422 Section 3.1: SASL mechanism
        // names are case-insensitive. "login" (lowercase) must be
        // parsed as the dedicated Login variant.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "AUTH login".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.supports_auth(&AuthMechanism::Login),
            "lowercase 'login' must be parsed as AuthMechanism::Login"
        );
    }

    #[test]
    fn ehlo_auth_equals_form_with_login() {
        // Legacy "AUTH=LOGIN PLAIN" form (RFC 2554 Section 3).
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["legacy.server.com".into(), "AUTH=LOGIN PLAIN".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.supports_auth(&AuthMechanism::Login),
            "AUTH=LOGIN form must parse LOGIN as dedicated variant"
        );
        assert!(caps.supports_auth(&AuthMechanism::Plain));
    }

    // ── DSN — RFC 3461 EHLO parsing ─────────────────────────────────────

    #[test]
    fn ehlo_parses_dsn_extension() {
        // RFC 3461: DSN keyword in EHLO response.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "DSN".into(), "PIPELINING".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.extensions.contains(&SmtpExtension::Dsn));
        assert!(caps.supports_dsn());
    }

    #[test]
    fn ehlo_parses_dsn_case_insensitive() {
        // RFC 5321 Section 2.4: EHLO keywords are case-insensitive.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "dsn".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.supports_dsn(),
            "lowercase 'dsn' must be recognized as DSN extension"
        );
    }

    // ── REQUIRETLS — RFC 8689 EHLO parsing ──────────────────────────────

    #[test]
    fn ehlo_parses_requiretls_extension() {
        // RFC 8689: REQUIRETLS keyword in EHLO response.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec![
                "mail.example.com".into(),
                "REQUIRETLS".into(),
                "STARTTLS".into(),
            ],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.extensions.contains(&SmtpExtension::RequireTls));
        assert!(caps.supports_requiretls());
    }

    #[test]
    fn ehlo_parses_requiretls_case_insensitive() {
        // RFC 5321 Section 2.4: EHLO keywords are case-insensitive.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "requiretls".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.supports_requiretls(),
            "lowercase 'requiretls' must be recognized"
        );
    }

    // ── AUTH OAUTHBEARER — RFC 7628 EHLO parsing ────────────────────────

    #[test]
    fn ehlo_parses_oauthbearer_as_dedicated_variant() {
        // RFC 7628 Section 3.1: OAUTHBEARER must be parsed as
        // AuthMechanism::OAuthBearer, not Other("OAUTHBEARER").
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec![
                "mail.example.com".into(),
                "AUTH PLAIN OAUTHBEARER XOAUTH2".into(),
            ],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.supports_auth(&AuthMechanism::OAuthBearer));
        assert!(caps.supports_auth(&AuthMechanism::Plain));
        assert!(caps.supports_auth(&AuthMechanism::XOAuth2));
    }

    #[test]
    fn ehlo_parses_oauthbearer_case_insensitive() {
        // RFC 4954 Section 3: SASL mechanism names are case-insensitive.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "AUTH oauthbearer".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.supports_auth(&AuthMechanism::OAuthBearer),
            "lowercase 'oauthbearer' must be parsed as AuthMechanism::OAuthBearer"
        );
    }

    // ── FUTURERELEASE — RFC 4865 ────────────────────────────────────────

    #[test]
    fn ehlo_parses_futurerelease() {
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec![
                "mail.example.com".into(),
                "FUTURERELEASE 86400 2024-12-31T23:59:59Z".into(),
            ],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.supports_future_release());
    }

    #[test]
    fn ehlo_parses_futurerelease_no_params() {
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "FUTURERELEASE".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.supports_future_release());
    }

    // ── DELIVERBY — RFC 2852 ────────────────────────────────────────────

    #[test]
    fn ehlo_parses_deliverby_with_max() {
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "DELIVERBY 240".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.supports_deliver_by());
    }

    #[test]
    fn ehlo_parses_deliverby_no_max() {
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "DELIVERBY".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.supports_deliver_by());
    }

    // ── MT-PRIORITY — RFC 6758 ──────────────────────────────────────────

    #[test]
    fn ehlo_parses_mt_priority() {
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "MT-PRIORITY".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.supports_mt_priority());
    }

    // ── VRFY — RFC 5321 §4.1.1.6 ───────────────────────────────────────

    #[test]
    fn ehlo_parses_vrfy() {
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "VRFY".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.supports_vrfy());
    }

    // ── EXPN — RFC 5321 §4.1.1.7 ───────────────────────────────────────

    #[test]
    fn ehlo_parses_expn() {
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "EXPN".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(caps.supports_expn());
    }

    // ── Incomplete response — RFC 5321 Section 4.2 ──────────────────────

    #[test]
    fn parse_response_incomplete_after_code() {
        // RFC 5321 Section 4.2: After the 3-digit reply code, we need at
        // least one more byte to determine whether it is a continuation
        // line (hyphen), final line (SP), or bare code (CRLF).
        // Input "250" with no separator byte should return Incomplete.
        let input = b"250";
        let result = parse_response(input);
        assert!(
            matches!(result, Err(nom::Err::Incomplete(_))),
            "response with code but no separator must be Incomplete (RFC 5321 Section 4.2)"
        );
    }

    // ── Invalid reply code character — RFC 5321 Section 4.2 ─────────────

    #[test]
    fn reply_code_non_digit_first() {
        // RFC 5321 Section 4.2: reply-code = 3DIGIT. A non-digit character
        // in any position must be rejected.
        assert!(reply_code(b"X50 OK").is_err());
    }

    #[test]
    fn reply_code_non_digit_third() {
        // RFC 5321 Section 4.2: third character must be a digit 0-9.
        assert!(reply_code(b"25X OK").is_err());
    }

    #[test]
    fn parse_response_invalid_separator_byte() {
        // RFC 5321 Section 4.2: After the 3-digit reply code, the separator
        // must be '-' (continuation), SP (final line), or '\r' (bare code).
        // Any other byte (e.g., '!') is a protocol violation.
        let input = b"250!OK\r\n";
        let result = parse_response(input);
        assert!(
            result.is_err(),
            "invalid separator byte must be rejected (RFC 5321 Section 4.2)"
        );
    }

    // ── Enhanced status code TooLarge — RFC 1893 Section 2 ──────────────

    #[test]
    fn enhanced_code_subject_too_long() {
        // RFC 1893 Section 2: subject component is 1-3 digits.
        // A 4+ digit subject must be rejected as TooLarge.
        let input = b"2.1234.0 ";
        let result = enhanced_status_code(input);
        assert!(
            result.is_err(),
            "enhanced code with >3 digit subject must be rejected (RFC 1893 Section 2)"
        );
    }

    #[test]
    fn enhanced_code_detail_too_long() {
        // RFC 1893 Section 2: detail component is 1-3 digits.
        // A 4+ digit detail must be rejected as TooLarge.
        let input = b"2.1.1234 ";
        let result = enhanced_status_code(input);
        assert!(
            result.is_err(),
            "enhanced code with >3 digit detail must be rejected (RFC 1893 Section 2)"
        );
    }

    #[test]
    fn enhanced_code_complete_subject_too_long() {
        // Same TooLarge check for the complete (non-streaming) parser variant.
        // RFC 1893 Section 2: subject is 1-3 digits.
        let input = b"2.1234.0";
        let result = enhanced_status_code_complete(input);
        assert!(
            result.is_err(),
            "complete parser: enhanced code with >3 digit subject must be rejected"
        );
    }

    #[test]
    fn enhanced_code_complete_detail_too_long() {
        // Same TooLarge check for the complete (non-streaming) parser variant.
        // RFC 1893 Section 2: detail is 1-3 digits.
        let input = b"2.1.1234";
        let result = enhanced_status_code_complete(input);
        assert!(
            result.is_err(),
            "complete parser: enhanced code with >3 digit detail must be rejected"
        );
    }

    // ── NOSOLICITING — RFC 3865 ─────────────────────────────────────────

    #[test]
    fn ehlo_parses_nosoliciting_without_keyword() {
        // RFC 3865: NO-SOLICITING without a keyword parameter.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "NO-SOLICITING".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.extensions.contains(&SmtpExtension::NoSoliciting(None)),
            "NO-SOLICITING without keyword must parse as NoSoliciting(None) (RFC 3865)"
        );
    }

    #[test]
    fn ehlo_parses_nosoliciting_with_keyword() {
        // RFC 3865: NO-SOLICITING with a soliciting keyword parameter.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec![
                "mail.example.com".into(),
                "NO-SOLICITING org.example.adv".into(),
            ],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.extensions
                .contains(&SmtpExtension::NoSoliciting(Some("org.example.adv".into()))),
            "NO-SOLICITING with keyword must parse as NoSoliciting(Some(...)) (RFC 3865)"
        );
    }

    #[test]
    fn ehlo_parses_nosoliciting_case_insensitive() {
        // RFC 5321 Section 2.4: EHLO keywords are case-insensitive.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "no-soliciting".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        let has_nosoliciting = caps
            .extensions
            .iter()
            .any(|e| matches!(e, SmtpExtension::NoSoliciting(_)));
        assert!(
            has_nosoliciting,
            "lowercase 'no-soliciting' must be recognized (RFC 5321 Section 2.4)"
        );
    }

    // ── Pipelining parsed as extension with no parameter ────────────────

    #[test]
    fn ehlo_pipelining_has_no_parameter() {
        // RFC 1854 / RFC 2920: PIPELINING is advertised as a bare keyword
        // with no parameters. Verify it parses to the Pipelining variant
        // (not Other) even when there is no parameter.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec!["mail.example.com".into(), "PIPELINING".into()],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.extensions.contains(&SmtpExtension::Pipelining),
            "PIPELINING must parse to the dedicated variant, not Other"
        );
    }

    // ── Multi-line incomplete (continuation with no final line) ──────────

    #[test]
    fn multi_line_continuation_incomplete_at_code() {
        // RFC 5321 Section 4.2: A continuation line followed by a partial
        // reply code (fewer than 3 bytes) must return Incomplete.
        let input = b"250-Hello\r\n25";
        let result = parse_response(input);
        assert!(
            matches!(result, Err(nom::Err::Incomplete(_))),
            "partial code after continuation must be Incomplete"
        );
    }

    // ── Non-UTF8 text in response — Postel's law ────────────────────────

    #[test]
    fn response_non_utf8_replacement_in_error_text() {
        // RFC 5321 Section 4.2 / Postel's law: servers may send non-UTF-8
        // bytes in response text. The parser uses lossy UTF-8 conversion,
        // replacing invalid sequences with U+FFFD.
        let mut input = Vec::new();
        input.extend_from_slice(b"550 5.1.1 ");
        input.push(0xFF); // Invalid UTF-8 byte
        input.push(0xFE); // Another invalid byte
        input.extend_from_slice(b" rejected\r\n");
        let (rest, resp) = parse_response(&input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 550);
        // Lossy conversion replaces 0xFF and 0xFE with U+FFFD
        assert!(
            resp.lines[0].contains('\u{FFFD}'),
            "non-UTF-8 bytes must be replaced with U+FFFD (Postel's law)"
        );
        assert!(resp.lines[0].contains("rejected"));
    }

    #[test]
    fn multi_line_response_non_utf8_on_continuation() {
        // RFC 5321 Section 4.2: non-UTF-8 bytes on a continuation line
        // must also be handled gracefully with lossy conversion.
        let mut input = Vec::new();
        input.extend_from_slice(b"250-Hello\r\n250 ");
        input.push(0x80); // Invalid UTF-8 continuation byte without lead byte
        input.push(0x81);
        input.extend_from_slice(b"\r\n");
        let (rest, resp) = parse_response(&input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 250);
        assert_eq!(resp.lines.len(), 2);
        assert!(
            resp.lines[1].contains('\u{FFFD}'),
            "non-UTF-8 on continuation line must use lossy conversion"
        );
    }

    #[test]
    fn response_entirely_non_utf8_text() {
        // Postel's law: even if the entire text portion is non-UTF-8 bytes,
        // the parser must not panic — lossy conversion produces all U+FFFD.
        let mut input = Vec::new();
        input.extend_from_slice(b"421 ");
        input.extend_from_slice(&[0xFF, 0xFE, 0xFD, 0xFC]);
        input.extend_from_slice(b"\r\n");
        let (rest, resp) = parse_response(&input).unwrap();
        assert!(rest.is_empty());
        assert_eq!(resp.code, 421);
        assert!(resp.lines[0].contains('\u{FFFD}'));
    }

    // ── SASL-IR — RFC 4959 ──────────────────────────────────────────────

    #[test]
    fn ehlo_parses_sasl_ir() {
        // RFC 4959: SASL-IR keyword in EHLO response.
        let response = SmtpResponse {
            code: 250,
            enhanced_code: None,
            lines: vec![
                "mail.example.com".into(),
                "AUTH PLAIN".into(),
                "SASL-IR".into(),
            ],
        };
        let caps = parse_ehlo_capabilities(&response);
        assert!(
            caps.extensions.contains(&SmtpExtension::SaslIr),
            "SASL-IR must be recognized (RFC 4959)"
        );
        assert!(caps.supports_sasl_ir());
    }

    // ── strip_enhanced_code edge cases ──────────────────────────────────

    #[test]
    fn strip_enhanced_code_with_text() {
        // RFC 2034 Section 3: enhanced code followed by space and text.
        let result = strip_enhanced_code("2.1.0 Sender OK");
        assert!(result.is_some());
        let (esc, rest) = result.unwrap();
        assert_eq!(esc.class, 2);
        assert_eq!(esc.subject, 1);
        assert_eq!(esc.detail, 0);
        assert_eq!(rest, "Sender OK");
    }

    #[test]
    fn strip_enhanced_code_not_a_code() {
        // Non-enhanced-code text must return None.
        assert!(strip_enhanced_code("Hello world").is_none());
    }

    #[test]
    fn strip_enhanced_code_partial_code_with_trailing_text() {
        // "2.1" is not a valid enhanced code (missing detail) — must return None.
        assert!(strip_enhanced_code("2.1 text").is_none());
    }

    #[test]
    fn strip_enhanced_code_followed_by_non_space() {
        // "2.1.0text" — enhanced code not followed by space or end —
        // must return None.
        assert!(strip_enhanced_code("2.1.0text").is_none());
    }
}