daaki-smtp 0.2.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
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
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
#![allow(clippy::unwrap_used)]

use super::*;
use crate::types::{DomainOrLiteral, EnvidValue, ForwardPath, Mailbox, ReversePath};

/// Test helper: construct a [`DomainOrLiteral`] from a string.
fn dol(s: &str) -> DomainOrLiteral {
    DomainOrLiteral::new(s).unwrap()
}

/// Test helper: construct a [`ReversePath`] from a string.
fn rp(s: &str) -> ReversePath {
    ReversePath::new(s).unwrap()
}

/// Test helper: construct a [`ForwardPath`] from a string.
fn fp(s: &str) -> ForwardPath {
    ForwardPath::new(s).unwrap()
}

#[test]
fn encode_ehlo_command() {
    let mut buf = BytesMut::new();
    encode_ehlo(&mut buf, &dol("client.example.com")).unwrap();
    assert_eq!(&buf[..], b"EHLO client.example.com\r\n");
}

#[test]
fn encode_ehlo_rejects_empty_label() {
    // RFC 5321 Section 4.1.2: Domain labels are `sub-domain`, so
    // consecutive dots are invalid and must be rejected by the newtype.
    let err = DomainOrLiteral::new("mail..example.com").unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("RFC 5321 Section 4.1.2"),
        "error should cite the violated EHLO domain grammar: {msg}"
    );
}

#[test]
fn encode_ehlo_rejects_overlong_domain_label() {
    let domain = format!("{}.example.com", "a".repeat(64));
    let err = DomainOrLiteral::new(&domain).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("63-octet") || msg.contains("63 octet"),
        "error should cite the per-label DNS limit, got: {msg}"
    );
}

#[test]
fn encode_mail_from_without_size() {
    let mut buf = BytesMut::new();
    encode_mail_from(&mut buf, &rp("sender@example.com"), None).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com>\r\n");
}

#[test]
fn encode_mail_from_with_size() {
    let mut buf = BytesMut::new();
    encode_mail_from(&mut buf, &rp("sender@example.com"), Some(1024)).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> SIZE=1024\r\n");
}

#[test]
fn encode_rcpt_to_command() {
    let mut buf = BytesMut::new();
    encode_rcpt_to(&mut buf, &fp("recipient@example.com")).unwrap();
    assert_eq!(&buf[..], b"RCPT TO:<recipient@example.com>\r\n");
}

#[test]
fn encode_mail_from_rejects_overlong_domain_label() {
    // Validation now happens in the Mailbox newtype constructor.
    let mailbox = format!("sender@{}.example", "a".repeat(64));
    let err = ReversePath::new(&mailbox).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("63-octet") || msg.contains("63 octet") || msg.contains("invalid"),
        "MAIL FROM should reject overlong domain labels, got: {msg}"
    );
}

#[test]
fn dot_stuffing_no_dots() {
    assert_eq!(dot_stuff(b"hello\r\nworld\r\n"), b"hello\r\nworld\r\n");
}

#[test]
fn dot_stuffing_leading_dot() {
    assert_eq!(
        dot_stuff(b".hidden\r\n.also\r\n"),
        b"..hidden\r\n..also\r\n"
    );
}

#[test]
fn dot_stuffing_dot_in_middle() {
    // Dot not at line start should not be stuffed.
    assert_eq!(dot_stuff(b"no.dot\r\n"), b"no.dot\r\n");
}

#[test]
fn dot_stuffing_at_start_of_data() {
    assert_eq!(dot_stuff(b".start"), b"..start");
}

#[test]
fn dot_stuffing_bare_lf_not_treated_as_line_start() {
    // RFC 5321 Section 2.3.8: lines are terminated by CRLF, not bare LF.
    // RFC 5321 Section 4.5.2: dot-stuffing applies to dots at the start
    // of CRLF-delimited lines only. A dot after bare LF is NOT at a line
    // start and MUST NOT be stuffed, otherwise the receiver (which uses
    // CRLF boundaries) will not remove the extra dot, corrupting the message.
    assert_eq!(
        dot_stuff(b"test\n.notastart\r\n"),
        b"test\n.notastart\r\n",
        "dot after bare LF must not be stuffed (RFC 5321 Section 4.5.2)"
    );
}

#[test]
fn dot_stuffing_crlf_dot_is_stuffed() {
    // Dot after proper CRLF line ending MUST be stuffed.
    assert_eq!(
        dot_stuff(b"test\r\n.start\r\n"),
        b"test\r\n..start\r\n",
        "dot after CRLF must be stuffed (RFC 5321 Section 4.5.2)"
    );
}

// ── dot_stuff_size — RFC 5321 §4.5.2 / RFC 1870 §3 ──────────────

#[test]
fn dot_stuff_size_matches_dot_stuff_len() {
    // dot_stuff_size must return the same value as dot_stuff().len()
    // for all inputs.
    let cases: &[&[u8]] = &[
        b"hello\r\nworld\r\n",
        b".hidden\r\n.also\r\n",
        b"no.dot\r\n",
        b".start",
        b"test\n.notastart\r\n",
        b"test\r\n.start\r\n",
        b"",
        b"Subject: Test\r\n\r\n.line1\r\n.line2\r\n",
    ];
    for data in cases {
        assert_eq!(
            dot_stuff_size(data),
            dot_stuff(data).len(),
            "dot_stuff_size mismatch for {:?}",
            String::from_utf8_lossy(data)
        );
    }
}

/// Regression test: `dot_stuff` capacity hint uses saturating arithmetic
/// to avoid wrapping overflow on large inputs.
///
/// # References
/// - RFC 5321 Section 4.5.2 (dot-stuffing)
#[test]
fn dot_stuff_capacity_does_not_overflow() {
    // Verify the capacity formula doesn't panic in debug mode
    // on a large-but-feasible input. The actual dot-stuffing logic
    // is tested elsewhere; this only checks the arithmetic is safe.
    let data = vec![b'.'; 1024 * 1024]; // 1 MiB of dots
    let stuffed = dot_stuff(&data);
    // Every byte is a dot at line-start (at_line_start starts true,
    // but only the FIRST dot is at line start since there are no CRLF).
    // So only the first dot gets stuffed.
    assert_eq!(stuffed.len(), data.len() + 1);
    assert_eq!(stuffed[0], b'.');
    assert_eq!(stuffed[1], b'.');
}

#[test]
fn auth_plain_encoding() {
    use base64::Engine;

    let mut buf = BytesMut::new();
    encode_auth_plain(&mut buf, "user", "pass");
    // \0user\0pass -> base64
    let line = std::str::from_utf8(&buf).unwrap();
    assert!(line.starts_with("AUTH PLAIN "));
    assert!(line.ends_with("\r\n"));

    // Verify the base64 decodes correctly.
    let b64 = &line["AUTH PLAIN ".len()..line.len() - 2];
    let decoded = base64::engine::general_purpose::STANDARD
        .decode(b64)
        .unwrap();
    assert_eq!(decoded, b"\0user\0pass");
}

#[test]
fn auth_xoauth2_encoding() {
    use base64::Engine;

    let mut buf = BytesMut::new();
    encode_auth_xoauth2(&mut buf, "user@example.com", "ya29.token");
    let line = std::str::from_utf8(&buf).unwrap();
    assert!(line.starts_with("AUTH XOAUTH2 "));

    let b64 = &line["AUTH XOAUTH2 ".len()..line.len() - 2];
    let decoded = base64::engine::general_purpose::STANDARD
        .decode(b64)
        .unwrap();
    let expected = "user=user@example.com\x01auth=Bearer ya29.token\x01\x01";
    assert_eq!(decoded, expected.as_bytes());
}

/// Verify that `encode_auth_plain` produces exact base64 matching
/// the RFC 4616 credential format. This locks down the output
/// before refactoring to eliminate duplicate credential computation
/// in `connection.rs` `auth_plain()`.
#[test]
fn auth_plain_exact_base64_matches_manual_computation() {
    use base64::Engine;

    let user = "testuser";
    let pass = "testpass";

    // Manual RFC 4616 Section 2 computation: [authzid] NUL authcid NUL passwd
    let mut credentials = Vec::with_capacity(1 + user.len() + 1 + pass.len());
    credentials.push(0);
    credentials.extend_from_slice(user.as_bytes());
    credentials.push(0);
    credentials.extend_from_slice(pass.as_bytes());
    let expected_b64 = base64::engine::general_purpose::STANDARD.encode(&credentials);

    // Extract base64 from encode_auth_plain output
    let mut buf = BytesMut::new();
    encode_auth_plain(&mut buf, user, pass);
    let line = std::str::from_utf8(&buf).unwrap();
    let actual_b64 = &line["AUTH PLAIN ".len()..line.len() - 2];

    assert_eq!(
        actual_b64, expected_b64,
        "encode_auth_plain base64 must match manual RFC 4616 computation"
    );
}

/// Verify that `encode_auth_xoauth2` produces exact base64 matching
/// the Google XOAUTH2 SASL format. This locks down the output
/// before refactoring to eliminate duplicate credential computation
/// in `connection.rs` `auth_xoauth2()`.
#[test]
fn auth_xoauth2_exact_base64_matches_manual_computation() {
    use base64::Engine;

    let user = "user@example.com";
    let token = "ya29.a0token";

    // Manual XOAUTH2 SASL string: user=<user>\x01auth=Bearer <token>\x01\x01
    let sasl_string = format!("user={user}\x01auth=Bearer {token}\x01\x01");
    let expected_b64 = base64::engine::general_purpose::STANDARD.encode(sasl_string.as_bytes());

    // Extract base64 from encode_auth_xoauth2 output
    let mut buf = BytesMut::new();
    encode_auth_xoauth2(&mut buf, user, token);
    let line = std::str::from_utf8(&buf).unwrap();
    let actual_b64 = &line["AUTH XOAUTH2 ".len()..line.len() - 2];

    assert_eq!(
        actual_b64, expected_b64,
        "encode_auth_xoauth2 base64 must match manual XOAUTH2 SASL computation"
    );
}

#[test]
fn encode_bdat_without_last() {
    let mut buf = BytesMut::new();
    encode_bdat(&mut buf, 1024, false);
    assert_eq!(&buf[..], b"BDAT 1024\r\n");
}

#[test]
fn encode_bdat_with_last() {
    let mut buf = BytesMut::new();
    encode_bdat(&mut buf, 512, true);
    assert_eq!(&buf[..], b"BDAT 512 LAST\r\n");
}

#[test]
fn encode_lhlo_command() {
    let mut buf = BytesMut::new();
    encode_lhlo(&mut buf, &dol("client.example.com")).unwrap();
    assert_eq!(&buf[..], b"LHLO client.example.com\r\n");
}

#[test]
fn encode_helo_command() {
    let mut buf = BytesMut::new();
    encode_helo(&mut buf, &dol("client.example.com")).unwrap();
    assert_eq!(&buf[..], b"HELO client.example.com\r\n");
}

#[test]
fn encode_helo_accepts_address_literal() {
    // RFC 5321 Section 4.1.1.1: when the client lacks a meaningful
    // domain name, it SHOULD send an address-literal.
    let mut buf = BytesMut::new();
    encode_helo(&mut buf, &dol("[127.0.0.1]")).unwrap();
    assert_eq!(&buf[..], b"HELO [127.0.0.1]\r\n");
}

#[test]
fn encode_ehlo_rejects_invalid_lowercase_ipv6_address_literal() {
    // Validation now happens in the DomainOrLiteral constructor.
    let err = DomainOrLiteral::new("[ipv6:not-an-ip]").unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("RFC 5321 Section 4.1.3"),
        "invalid lowercase ipv6 literal must be rejected with RFC 5321 Section 4.1.3 context: {msg}"
    );
}

#[test]
fn encode_mail_from_full_no_params() {
    let mut buf = BytesMut::new();
    encode_mail_from_full(
        &mut buf,
        &rp("sender@example.com"),
        &MailFromParams::default(),
    )
    .unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com>\r\n");
}

#[test]
fn encode_mail_from_full_rejects_invalid_address_literal_domain() {
    // Validation now happens in the ReversePath/Mailbox constructor.
    let err = ReversePath::new("sender@[bad literal]").unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("RFC 5321") || msg.contains("invalid"),
        "invalid mailbox address-literal must be rejected: {msg}"
    );
}

#[test]
fn encode_mail_from_full_with_size() {
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        size: Some(2048),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> SIZE=2048\r\n");
}

#[test]
fn encode_mail_from_full_with_body_8bitmime() {
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        body: Some(BodyType::EightBitMime),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> BODY=8BITMIME\r\n"
    );
}

#[test]
fn encode_mail_from_full_with_body_binarymime() {
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        body: Some(BodyType::BinaryMime),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> BODY=BINARYMIME\r\n"
    );
}

#[test]
fn encode_mail_from_full_with_body_7bit() {
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        body: Some(BodyType::SevenBit),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> BODY=7BIT\r\n");
}

#[test]
fn encode_mail_from_full_with_smtputf8() {
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        smtputf8: true,
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> BODY=8BITMIME SMTPUTF8\r\n"
    );
}

#[test]
fn encode_mail_from_rejects_non_ascii_reverse_path_without_smtputf8() {
    let mut buf = BytesMut::new();
    let result = encode_mail_from(&mut buf, &rp("pelé@example.com"), None);
    assert!(
        result.is_err(),
        "non-ASCII reverse-paths must be rejected unless MAIL FROM declares SMTPUTF8"
    );
}

#[test]
fn encode_mail_from_full_rejects_non_ascii_reverse_path_without_smtputf8() {
    let mut buf = BytesMut::new();
    let result = encode_mail_from_full(
        &mut buf,
        &rp("pelé@example.com"),
        &MailFromParams::default(),
    );
    assert!(
        result.is_err(),
        "RFC 6531 Sections 3.3 and 3.4 require SMTPUTF8 for non-ASCII reverse-paths"
    );
}

#[test]
fn encode_mail_from_full_allows_non_ascii_reverse_path_with_smtputf8() {
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        smtputf8: true,
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("pelé@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        "MAIL FROM:<pelé@example.com> BODY=8BITMIME SMTPUTF8\r\n".as_bytes()
    );
}

/// RFC 6531 Section 3.6: SMTPUTF8 is only valid with BODY=8BITMIME or
/// BODY=BINARYMIME, never with BODY=7BIT.
#[test]
fn encode_mail_from_full_rejects_smtputf8_with_body_7bit() {
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        body: Some(BodyType::SevenBit),
        smtputf8: true,
        ..Default::default()
    };
    let result = encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params);
    assert!(
        result.is_err(),
        "SMTPUTF8 + BODY=7BIT must be rejected (RFC 6531 Section 3.6)"
    );
}

#[test]
fn encode_mail_from_full_all_params() {
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        size: Some(4096),
        body: Some(BodyType::EightBitMime),
        smtputf8: true,
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> SIZE=4096 BODY=8BITMIME SMTPUTF8\r\n"
    );
}

// ── RFC 5321 §4.1.1.4 — end-of-data terminator ──

#[test]
fn data_end_no_extra_blank_line_when_data_ends_with_crlf() {
    // RFC 5321 Section 4.1.1.4: end-of-data is "<CRLF>.<CRLF>" where
    // the first CRLF is "actually the terminator of the previous line."
    // When message data already ends with CRLF, only ".\r\n" should be
    // appended — not "\r\n.\r\n" which injects a spurious blank line.
    let data = b"Subject: Test\r\n\r\nHello\r\n";
    let stuffed = dot_stuff(data);
    let mut terminator = BytesMut::new();
    encode_data_end(&mut terminator, &stuffed);

    // Assemble what goes on the wire: stuffed data + terminator.
    let mut wire = Vec::new();
    wire.extend_from_slice(&stuffed);
    wire.extend_from_slice(&terminator);

    // Must end with "Hello\r\n.\r\n" — NOT "Hello\r\n\r\n.\r\n".
    assert!(
        wire.ends_with(b"Hello\r\n.\r\n"),
        "expected wire to end with 'Hello\\r\\n.\\r\\n', got trailing bytes: {:?}",
        String::from_utf8_lossy(&wire[wire.len().saturating_sub(20)..])
    );
}

#[test]
fn data_end_adds_crlf_when_data_does_not_end_with_crlf() {
    // If the data does NOT end with CRLF, the terminator must prepend
    // CRLF so the dot is on its own line (RFC 5321 Section 4.1.1.4).
    let data = b"incomplete line";
    let mut buf = BytesMut::new();
    encode_data_end(&mut buf, data);
    assert_eq!(&buf[..], b"\r\n.\r\n");
}

#[test]
fn data_end_with_empty_data() {
    // Empty data (e.g. aborting DATA phase) — must still produce
    // a valid terminator with leading CRLF.
    let mut buf = BytesMut::new();
    encode_data_end(&mut buf, b"");
    assert_eq!(&buf[..], b"\r\n.\r\n");
}

/// SMTP-002: Verify that `dot_stuff_and_terminate` produces a single
/// combined buffer containing the dot-stuffed body followed by the
/// correct DATA terminator (RFC 5321 Section 4.5.2 / Section 4.1.1.4).
///
/// This ensures the body and terminator can be sent in a single write
/// operation rather than two separate write+flush cycles.
#[test]
fn dot_stuff_and_terminate_combines_body_and_terminator() {
    // RFC 5321 Section 4.5.2: dot-stuff the body, then append the
    // end-of-data terminator per Section 4.1.1.4.
    let message = b"Subject: Test\r\n\r\n.Hello\r\n";
    let combined = dot_stuff_and_terminate(message);

    // The dot-stuffed body for ".Hello" becomes "..Hello" (dot-stuffing).
    // Since the data ends with CRLF, the terminator is just ".\r\n".
    assert_eq!(
        &combined[..],
        b"Subject: Test\r\n\r\n..Hello\r\n.\r\n",
        "combined buffer must contain dot-stuffed body + terminator \
         (RFC 5321 Sections 4.5.2 / 4.1.1.4)"
    );
}

/// SMTP-002: Verify combined buffer when body does NOT end with CRLF.
///
/// RFC 5321 Section 4.1.1.4: the terminator must prepend CRLF so
/// the dot appears on its own line.
#[test]
fn dot_stuff_and_terminate_adds_crlf_when_body_does_not_end_with_crlf() {
    let message = b"incomplete line";
    let combined = dot_stuff_and_terminate(message);
    assert_eq!(
        &combined[..],
        b"incomplete line\r\n.\r\n",
        "combined buffer must insert CRLF before terminator when body \
         does not end with CRLF (RFC 5321 Section 4.1.1.4)"
    );
}

/// SMTP-002: Verify combined buffer with empty body.
#[test]
fn dot_stuff_and_terminate_empty_body() {
    let combined = dot_stuff_and_terminate(b"");
    assert_eq!(
        &combined[..],
        b"\r\n.\r\n",
        "empty body must still produce CRLF + terminator \
         (RFC 5321 Section 4.1.1.4)"
    );
}

#[test]
fn encode_quit_command() {
    // RFC 5321 Section 4.1.1.10: "QUIT" CRLF
    let mut buf = BytesMut::new();
    encode_quit(&mut buf);
    assert_eq!(&buf[..], b"QUIT\r\n");
}

#[test]
fn encode_vrfy_command() {
    // RFC 5321 Section 4.1.1.6: VRFY SP String CRLF
    // RFC 5321 Section 4.1.2: `String = Atom / Quoted-string`.
    // A mailbox-like identifier contains `@` and `.` which are not valid
    // `atext`, so it must be emitted as a quoted-string.
    let mut buf = BytesMut::new();
    encode_vrfy(&mut buf, "user@example.com").unwrap();
    assert_eq!(&buf[..], b"VRFY \"user@example.com\"\r\n");
}

#[test]
fn encode_vrfy_quotes_argument_with_spaces() {
    // RFC 5321 Section 4.1.2: `String = Atom / Quoted-string`.
    // An argument containing SP must therefore use quoted-string form.
    let mut buf = BytesMut::new();
    encode_vrfy(&mut buf, "Jane Doe").unwrap();
    assert_eq!(&buf[..], b"VRFY \"Jane Doe\"\r\n");
}

#[test]
fn encode_vrfy_rejects_malformed_prequoted_argument() {
    // RFC 5321 Section 4.1.2: a pre-quoted String must still be a valid
    // quoted-string. An unescaped DQUOTE inside the quoted content is not.
    let mut buf = BytesMut::new();
    let result = encode_vrfy(&mut buf, "\"bad\"quote\"");
    assert!(
        result.is_err(),
        "malformed pre-quoted VRFY argument must be rejected instead of emitted verbatim"
    );
}

/// Regression test SMTP-001: RFC 5321 Section 4.1.2 defines
/// `quoted-pairSMTP = %d92 %d32-126` — only bytes 0x20..=0x7E are
/// valid after a backslash. HTAB (0x09) is NOT in that range and must
/// be rejected even though it is technically WSP. The validator
/// previously accepted `\<TAB>` due to an erroneous `|| next == b'\t'`
/// check. This test verifies that a quoted-string containing
/// `\<TAB>` is now correctly rejected.
#[test]
fn quoted_pair_smtp_rejects_htab_after_backslash() {
    // Build a pre-quoted string: "test\<TAB>value" where the backslash
    // is followed by HTAB (0x09). Per quoted-pairSMTP = %d92 %d32-126,
    // HTAB (0x09) is outside the valid range and must be rejected.
    let quoted = "\"test\\\tvalue\"";
    let result = validate_smtp_quoted_string(quoted, false);
    assert!(
        result.is_err(),
        "quoted-pairSMTP must reject HTAB (0x09) after backslash; \
         only %d32-126 is valid (RFC 5321 Section 4.1.2)"
    );
}

/// Complementary check: RFC 5321 Section 4.1.2 quoted-pairSMTP allows
/// SP (0x20) after backslash since SP is within %d32-126.
#[test]
fn quoted_pair_smtp_allows_sp_after_backslash() {
    // "test\ value" — backslash followed by SP (0x20), which is valid
    // per quoted-pairSMTP = %d92 %d32-126.
    let quoted = "\"test\\ value\"";
    let result = validate_smtp_quoted_string(quoted, false);
    assert!(
        result.is_ok(),
        "quoted-pairSMTP must accept SP (0x20) after backslash; \
         it is within %d32-126 (RFC 5321 Section 4.1.2)"
    );
}

#[test]
fn encode_vrfy_rejects_empty_argument() {
    let mut buf = BytesMut::new();
    let result = encode_vrfy(&mut buf, "");
    assert!(
        result.is_err(),
        "VRFY with an empty String argument must be rejected (RFC 5321 Section 4.1.1.6)"
    );
}

#[test]
fn encode_vrfy_rejects_non_ascii_argument() {
    let mut buf = BytesMut::new();
    let result = encode_vrfy(&mut buf, "usér@example.com");
    assert!(
        result.is_err(),
        "VRFY String arguments must be printable ASCII only \
         (RFC 5321 Section 4.1.1.6 / Section 4.1.2)"
    );
}

#[test]
fn encode_expn_command() {
    // RFC 5321 Section 4.1.1.7: EXPN SP String CRLF
    let mut buf = BytesMut::new();
    encode_expn(&mut buf, "staff").unwrap();
    assert_eq!(&buf[..], b"EXPN staff\r\n");
}

#[test]
fn encode_help_command_without_argument() {
    // RFC 5321 Section 4.1.1.8: HELP may be issued without an argument.
    let mut buf = BytesMut::new();
    encode_help(&mut buf);
    assert_eq!(&buf[..], b"HELP\r\n");
}

#[test]
fn encode_help_command_with_argument() {
    // RFC 5321 Section 4.1.1.8 / Section 4.1.2: HELP SP String CRLF.
    // Command names are valid SMTP atoms and therefore do not need
    // quoting.
    let mut buf = BytesMut::new();
    encode_help_with_arg(&mut buf, "MAIL").unwrap();
    assert_eq!(&buf[..], b"HELP MAIL\r\n");
}

#[test]
fn encode_help_quotes_argument_with_spaces() {
    // RFC 5321 Section 4.1.2: a HELP String containing SP must use
    // quoted-string form.
    let mut buf = BytesMut::new();
    encode_help_with_arg(&mut buf, "MAIL FROM").unwrap();
    assert_eq!(&buf[..], b"HELP \"MAIL FROM\"\r\n");
}

#[test]
fn encode_help_rejects_empty_argument() {
    let mut buf = BytesMut::new();
    let result = encode_help_with_arg(&mut buf, "");
    assert!(
        result.is_err(),
        "HELP with an empty String argument must be rejected (RFC 5321 Section 4.1.1.8)"
    );
}

#[test]
fn encode_expn_smtputf8_quotes_argument_with_spaces() {
    // RFC 5321 Section 4.1.2: `String = Atom / Quoted-string`.
    // RFC 6531 Section 3.7.4.2 permits UTF-8 in this argument when
    // SMTPUTF8 is present, but whitespace still requires quoted-string.
    let mut buf = BytesMut::new();
    encode_expn_smtputf8(&mut buf, "équipe support").unwrap();
    assert_eq!(&buf[..], "EXPN \"équipe support\" SMTPUTF8\r\n".as_bytes());
}

#[test]
fn encode_vrfy_smtputf8_quotes_mailbox_argument() {
    // RFC 5321 Section 4.1.2: `String = Atom / Quoted-string`.
    // RFC 6531 Section 3.7.4.2 permits UTF-8 in the string, but mailbox
    // punctuation such as `@` and `.` still requires quoted-string form.
    let mut buf = BytesMut::new();
    encode_vrfy_smtputf8(&mut buf, "usér@example.com").unwrap();
    assert_eq!(
        &buf[..],
        "VRFY \"usér@example.com\" SMTPUTF8\r\n".as_bytes()
    );
}

#[test]
fn encode_vrfy_smtputf8_rejects_escaped_non_ascii_in_prequoted_argument() {
    // RFC 5321 Section 4.1.2 keeps quoted-pairSMTP ASCII-only:
    // backslash may only escape VCHAR / WSP. RFC 6531 Section 3.3
    // extends qtextSMTP with UTF-8 but does not extend quoted-pairSMTP,
    // so `\"\\é\"` is invalid and must return an error rather than panic.
    let mut buf = BytesMut::new();
    let result = encode_vrfy_smtputf8(&mut buf, "\"\\é\"");
    assert!(
        result.is_err(),
        "escaped non-ASCII in a pre-quoted SMTPUTF8 argument must be rejected \
         per RFC 5321 Section 4.1.2 / RFC 6531 Section 3.3"
    );
}

#[test]
fn encode_expn_rejects_empty_argument() {
    let mut buf = BytesMut::new();
    let result = encode_expn(&mut buf, "");
    assert!(
        result.is_err(),
        "EXPN with an empty String argument must be rejected (RFC 5321 Section 4.1.1.7)"
    );
}

#[test]
fn encode_expn_rejects_control_character_argument() {
    let mut buf = BytesMut::new();
    let result = encode_expn(&mut buf, "staff\u{0007}");
    assert!(
        result.is_err(),
        "EXPN String arguments must reject ASCII control characters \
         (RFC 5321 Section 4.1.1.7 / Section 4.1.2)"
    );
}

// ── equivalence tests: lock down before refactoring ──

/// `encode_mail_from(from, None)` must produce the same output as
/// `encode_mail_from_full(from, &MailFromParams::default())`.
#[test]
fn encode_mail_from_equiv_no_params() {
    let mut a = BytesMut::new();
    let mut b = BytesMut::new();
    encode_mail_from(&mut a, &rp("test@example.com"), None).unwrap();
    encode_mail_from_full(&mut b, &rp("test@example.com"), &MailFromParams::default()).unwrap();
    assert_eq!(&a[..], &b[..]);
}

/// `encode_mail_from(from, Some(size))` must produce the same output as
/// `encode_mail_from_full(from, &MailFromParams { size: Some(size), .. })`.
#[test]
fn encode_mail_from_equiv_with_size() {
    let mut a = BytesMut::new();
    let mut b = BytesMut::new();
    encode_mail_from(&mut a, &rp("test@example.com"), Some(5000)).unwrap();
    let params = MailFromParams {
        size: Some(5000),
        ..Default::default()
    };
    encode_mail_from_full(&mut b, &rp("test@example.com"), &params).unwrap();
    assert_eq!(&a[..], &b[..]);
}

// ── AUTH LOGIN encoder — draft-murchison-sasl-login ──────────────

#[test]
fn auth_login_initial_encoding() {
    // AUTH LOGIN initial command: "AUTH LOGIN\r\n" with no credentials.
    // The server responds with 334 challenges for username and password.
    let mut buf = BytesMut::new();
    encode_auth_login_initial(&mut buf);
    assert_eq!(&buf[..], b"AUTH LOGIN\r\n");
}

// ── RCPT TO with params — RFC 5321 §4.1.1.3 ────────────────────────

#[test]
fn encode_rcpt_to_full_empty_params() {
    // RFC 5321 Section 4.1.1.3: with no params, output matches
    // encode_rcpt_to exactly.
    let mut a = BytesMut::new();
    let mut b = BytesMut::new();
    encode_rcpt_to(&mut a, &fp("user@example.com")).unwrap();
    encode_rcpt_to_full(&mut b, &fp("user@example.com"), &RcptToParams::default()).unwrap();
    assert_eq!(&a[..], &b[..]);
}

// ── DSN — RFC 3461 ──────────────────────────────────────────────────

#[test]
fn encode_mail_from_full_with_ret_full() {
    // RFC 3461 Section 4.3: RET=FULL
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        ret: Some(DsnRet::Full),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> RET=FULL\r\n");
}

#[test]
fn encode_mail_from_full_with_ret_hdrs() {
    // RFC 3461 Section 4.3: RET=HDRS
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        ret: Some(DsnRet::Hdrs),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> RET=HDRS\r\n");
}

#[test]
fn encode_mail_from_full_with_envid() {
    // RFC 3461 Section 4.4: ENVID=<xtext>
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        envid: Some(EnvidValue::new("msg-12345").unwrap()),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> ENVID=msg-12345\r\n"
    );
}

#[test]
fn encode_mail_from_full_envid_xtext_encoding() {
    // RFC 3461 Section 4: characters outside xchar range must be
    // hex-encoded as +XX.
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        envid: Some(EnvidValue::new("id with+plus").unwrap()),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    // SP (0x20) -> +20, '+' (0x2B) -> +2B
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> ENVID=id+20with+2Bplus\r\n"
    );
}

#[test]
fn encode_mail_from_full_with_ret_and_envid() {
    // RFC 3461: both RET and ENVID on the same MAIL FROM.
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        ret: Some(DsnRet::Hdrs),
        envid: Some(EnvidValue::new("envelope-42").unwrap()),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> RET=HDRS ENVID=envelope-42\r\n"
    );
}

#[test]
fn encode_rcpt_to_full_with_notify_success() {
    // RFC 3461 Section 4.1: NOTIFY=SUCCESS
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        notify: Some(vec![DsnNotify::Success]),
        ..Default::default()
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"RCPT TO:<user@example.com> NOTIFY=SUCCESS\r\n");
}

#[test]
fn encode_rcpt_to_full_with_notify_multiple() {
    // RFC 3461 Section 4.1: NOTIFY=SUCCESS,FAILURE,DELAY
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        notify: Some(vec![
            DsnNotify::Success,
            DsnNotify::Failure,
            DsnNotify::Delay,
        ]),
        ..Default::default()
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"RCPT TO:<user@example.com> NOTIFY=SUCCESS,FAILURE,DELAY\r\n"
    );
}

#[test]
fn encode_rcpt_to_full_with_notify_never() {
    // RFC 3461 Section 4.1: NOTIFY=NEVER (must not combine with others)
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        notify: Some(vec![DsnNotify::Never]),
        ..Default::default()
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"RCPT TO:<user@example.com> NOTIFY=NEVER\r\n");
}

#[test]
fn encode_rcpt_to_full_with_orcpt() {
    // RFC 3461 Section 4.2: ORCPT=rfc822;<xtext-addr>
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        orcpt: Some("user@example.com".into()),
        ..Default::default()
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"RCPT TO:<user@example.com> ORCPT=rfc822;user@example.com\r\n"
    );
}

#[test]
fn encode_rcpt_to_full_with_notify_and_orcpt() {
    // RFC 3461: both NOTIFY and ORCPT on the same RCPT TO.
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        notify: Some(vec![DsnNotify::Success, DsnNotify::Failure]),
        orcpt: Some("original@example.com".into()),
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"RCPT TO:<user@example.com> NOTIFY=SUCCESS,FAILURE ORCPT=rfc822;original@example.com\r\n"
    );
}

#[test]
fn encode_rcpt_to_full_with_non_ascii_orcpt_uses_utf8_addr_type() {
    // RFC 6533 Section 3: when the ORCPT address contains non-ASCII
    // characters (internationalized email), the addr-type must be
    // "utf-8" instead of "rfc822".
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        orcpt: Some("user@example.日本".into()),
        ..Default::default()
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    let result = std::str::from_utf8(&buf).unwrap();
    assert!(
        result.contains("ORCPT=utf-8;"),
        "non-ASCII ORCPT must use utf-8 addr-type per RFC 6533 Section 3, got: {result}"
    );
}

#[test]
fn encode_rcpt_to_full_with_ascii_orcpt_uses_rfc822_addr_type() {
    // RFC 3461 Section 4.2: plain ASCII ORCPT addresses use rfc822 addr-type.
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        orcpt: Some("user@example.com".into()),
        ..Default::default()
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    let result = std::str::from_utf8(&buf).unwrap();
    assert!(
        result.contains("ORCPT=rfc822;"),
        "ASCII ORCPT must use rfc822 addr-type per RFC 3461 Section 4.2, got: {result}"
    );
}

#[test]
fn rcpt_to_params_is_empty() {
    // RcptToParams::is_empty must be true when no DSN fields are set.
    assert!(RcptToParams::default().is_empty());
    assert!(
        RcptToParams {
            notify: Some(vec![]),
            ..Default::default()
        }
        .is_empty(),
        "empty NOTIFY vector must be treated as absent because RFC 3461 Section 4.1 requires at least one notify value"
    );
    assert!(!RcptToParams {
        notify: Some(vec![DsnNotify::Success]),
        ..Default::default()
    }
    .is_empty());
    assert!(!RcptToParams {
        orcpt: Some("user@example.com".into()),
        ..Default::default()
    }
    .is_empty());
}

#[test]
fn xtext_encoding_printable_ascii_passthrough() {
    // RFC 3461 Section 4: printable ASCII (except SP and +) passes through.
    let mut buf = BytesMut::new();
    encode_xtext(&mut buf, "user@example.com");
    assert_eq!(&buf[..], b"user@example.com");
}

#[test]
fn xtext_encoding_plus_is_encoded() {
    // RFC 3461 Section 4: '+' (0x2B) must be encoded as +2B.
    let mut buf = BytesMut::new();
    encode_xtext(&mut buf, "a+b");
    assert_eq!(&buf[..], b"a+2Bb");
}

#[test]
fn xtext_encoding_space_is_encoded() {
    // RFC 3461 Section 4: SP (0x20) is outside xchar range.
    let mut buf = BytesMut::new();
    encode_xtext(&mut buf, "a b");
    assert_eq!(&buf[..], b"a+20b");
}

#[test]
fn xtext_encoding_equals_is_encoded() {
    // RFC 3461 Section 4: xchar excludes both "+" and "=".
    // "=" (0x3D) must be hex-encoded as +3D.
    let mut buf = BytesMut::new();
    encode_xtext(&mut buf, "a=b");
    assert_eq!(
        &buf[..],
        b"a+3Db",
        "\"=\" (0x3D) must be hex-encoded per RFC 3461 Section 4: \
         xchar = any ASCII CHAR between ! and ~ inclusive, except for + and ="
    );
}

// ── REQUIRETLS — RFC 8689 ───────────────────────────────────────────

#[test]
fn encode_mail_from_full_with_requiretls() {
    // RFC 8689 Section 3: REQUIRETLS parameter on MAIL FROM.
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        requiretls: true,
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> REQUIRETLS\r\n");
}

#[test]
fn encode_mail_from_full_requiretls_false_omitted() {
    // When requiretls is false, no REQUIRETLS param should appear.
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        requiretls: false,
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com>\r\n");
}

// ── AUTH OAUTHBEARER — RFC 7628 ─────────────────────────────────────

#[test]
fn auth_oauthbearer_encoding() {
    use base64::Engine;

    let mut buf = BytesMut::new();
    encode_auth_oauthbearer(&mut buf, "ya29.token");
    let line = std::str::from_utf8(&buf).unwrap();
    assert!(line.starts_with("AUTH OAUTHBEARER "));
    assert!(line.ends_with("\r\n"));

    // Verify the SASL payload decodes correctly.
    let b64 = &line["AUTH OAUTHBEARER ".len()..line.len() - 2];
    let decoded = base64::engine::general_purpose::STANDARD
        .decode(b64)
        .unwrap();
    let expected = "n,,\x01auth=Bearer ya29.token\x01\x01";
    assert_eq!(decoded, expected.as_bytes());
}

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

#[test]
fn encode_mail_from_full_with_holdfor() {
    // RFC 4865 Section 5: HOLDFOR=<seconds>
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        hold_for: Some(86400),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> HOLDFOR=86400\r\n"
    );
}

#[test]
fn encode_mail_from_full_with_holduntil() {
    // RFC 4865 Section 5: HOLDUNTIL=<datetime>
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        hold_until: Some("2024-12-25T00:00:00Z".into()),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> HOLDUNTIL=2024-12-25T00:00:00Z\r\n"
    );
}

#[test]
fn encode_mail_from_full_rejects_zero_holdfor() {
    // RFC 4865 Section 5: hold-for-seconds is a positive decimal integer.
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        hold_for: Some(0),
        ..Default::default()
    };
    let result = encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params);
    assert!(
        result.is_err(),
        "HOLDFOR=0 must be rejected because RFC 4865 Section 5 requires a positive interval"
    );
}

#[test]
fn encode_mail_from_full_rejects_ten_digit_holdfor() {
    // RFC 4865 Section 5: hold-for-seconds is limited to 1*9DIGIT.
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        hold_for: Some(1_000_000_000),
        ..Default::default()
    };
    let result = encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params);
    assert!(
        result.is_err(),
        "HOLDFOR with more than 9 digits must be rejected (RFC 4865 Section 5)"
    );
}

#[test]
fn encode_mail_from_full_rejects_malformed_holduntil() {
    // RFC 4865 Section 5 / RFC 3339 Section 5.6: HOLDUNTIL uses an RFC 3339 date-time.
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        hold_until: Some("2024-12-25 00:00:00Z".into()),
        ..Default::default()
    };
    let result = encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params);
    assert!(
        result.is_err(),
        "malformed HOLDUNTIL must be rejected instead of being emitted on the wire"
    );
}

#[test]
fn encode_mail_from_full_rejects_holdfor_and_holduntil_together() {
    // RFC 4865 Section 5: HOLDFOR and HOLDUNTIL are mutually exclusive.
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        hold_for: Some(3600),
        hold_until: Some("2024-12-25T00:00:00Z".into()),
        ..Default::default()
    };
    let result = encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params);
    assert!(
        result.is_err(),
        "HOLDFOR and HOLDUNTIL together must be rejected per RFC 4865 Section 5"
    );
}

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

#[test]
fn encode_mail_from_full_with_deliver_by_return() {
    use crate::types::{DeliverBy, DeliverByMode};
    // RFC 2852 Section 4: BY=<seconds>;R
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        deliver_by: Some(DeliverBy {
            seconds: 3600,
            mode: DeliverByMode::Return,
            trace: false,
        }),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> BY=3600;R\r\n");
}

#[test]
fn encode_mail_from_full_with_deliver_by_notify() {
    use crate::types::{DeliverBy, DeliverByMode};
    // RFC 2852 Section 4: BY=<seconds>;N
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        deliver_by: Some(DeliverBy {
            seconds: -120,
            mode: DeliverByMode::Notify,
            trace: false,
        }),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> BY=-120;N\r\n");
}

#[test]
fn encode_mail_from_full_with_deliver_by_trace_flag() {
    use crate::types::{DeliverBy, DeliverByMode};
    // RFC 2852 Section 4: by-trace = "T" appended after by-mode
    // BY=3600;RT means Return mode with trace
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        deliver_by: Some(DeliverBy {
            seconds: 3600,
            mode: DeliverByMode::Return,
            trace: true,
        }),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> BY=3600;RT\r\n");

    // BY=3600;NT means Notify mode with trace
    buf.clear();
    let params = MailFromParams {
        deliver_by: Some(DeliverBy {
            seconds: 3600,
            mode: DeliverByMode::Notify,
            trace: true,
        }),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> BY=3600;NT\r\n");

    // trace: false should not append T
    buf.clear();
    let params = MailFromParams {
        deliver_by: Some(DeliverBy {
            seconds: 3600,
            mode: DeliverByMode::Return,
            trace: false,
        }),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> BY=3600;R\r\n");
}

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

#[test]
fn encode_mail_from_full_with_mt_priority() {
    // RFC 6758 Section 4: MT-PRIORITY=<n>
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        mt_priority: Some(3),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> MT-PRIORITY=3\r\n"
    );
}

#[test]
fn encode_mail_from_full_with_mt_priority_negative() {
    // RFC 6758 Section 4: MT-PRIORITY supports negative values (-9 to 9).
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        mt_priority: Some(-4),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> MT-PRIORITY=-4\r\n"
    );
}

#[test]
fn mt_priority_valid_range_accepted() {
    // RFC 6758 Section 4: priority values range from -9 to 9.
    for value in [-9, 0, 9] {
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            mt_priority: Some(value),
            ..Default::default()
        };
        encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
        let expected = format!("MAIL FROM:<sender@example.com> MT-PRIORITY={value}\r\n");
        assert_eq!(
            &buf[..],
            expected.as_bytes(),
            "MT-PRIORITY={value} must be accepted (RFC 6758 Section 4)"
        );
    }
}

#[test]
fn mt_priority_out_of_range_rejected() {
    // RFC 6758 Section 4: priority values range from -9 to 9.
    // Values outside this range must be rejected.
    for value in [-10, 10] {
        let mut buf = BytesMut::new();
        let params = MailFromParams {
            mt_priority: Some(value),
            ..Default::default()
        };
        let result = encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params);
        assert!(
            result.is_err(),
            "MT-PRIORITY={value} must be rejected as out of range (RFC 6758 Section 4)"
        );
    }
}

/// RFC 3461 Section 4.1: "NEVER" MUST NOT be combined with other NOTIFY
/// values. The encoder must reject such input with an error rather than
/// silently discarding the other values.
#[test]
fn encode_rcpt_to_full_notify_never_combined_with_others_is_error() {
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        notify: Some(vec![DsnNotify::Never, DsnNotify::Success]),
        ..Default::default()
    };
    let result = encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params);
    // RFC 3461 Section 4.1: NEVER MUST NOT be used with any other value.
    assert!(
        result.is_err(),
        "NOTIFY=NEVER combined with other values must return an error \
         (RFC 3461 Section 4.1)"
    );
}

/// RFC 3461 Section 4.1: NEVER combined with other values must also be
/// rejected when NEVER appears after other values, not just before them.
#[test]
fn encode_rcpt_to_full_notify_never_after_others_is_error() {
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        notify: Some(vec![DsnNotify::Failure, DsnNotify::Never]),
        ..Default::default()
    };
    let result = encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params);
    // RFC 3461 Section 4.1: NEVER MUST NOT be used with any other value.
    assert!(
        result.is_err(),
        "NOTIFY=NEVER combined with other values must return an error \
         regardless of ordering (RFC 3461 Section 4.1)"
    );
}

/// RFC 3461 Section 4.1: When only NEVER is present (no combination
/// violation), output must be `NOTIFY=NEVER`.
#[test]
fn encode_rcpt_to_full_notify_never_alone_unchanged() {
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        notify: Some(vec![DsnNotify::Never]),
        ..Default::default()
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"RCPT TO:<user@example.com> NOTIFY=NEVER\r\n");
}

/// RFC 3461 Section 4.1: an empty NOTIFY vector (`Some(vec![])`) must
/// be treated as absent — the NOTIFY parameter must be omitted entirely
/// rather than producing the invalid syntax `NOTIFY=` with no value.
#[test]
fn encode_rcpt_to_full_empty_notify_vector_omitted() {
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        notify: Some(vec![]),
        ..Default::default()
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"RCPT TO:<user@example.com>\r\n",
        "empty NOTIFY vector must be omitted, not produce invalid 'NOTIFY=' \
         (RFC 3461 Section 4.1)"
    );
}

// ── CRLF injection defense-in-depth — RFC 5321 §4.1.2 ──────────────

/// RFC 5321 Section 4.1.2: SMTP commands are terminated by CRLF, so
/// embedded CR/LF in the domain parameter would split the command and
/// inject arbitrary commands. The encoder returns an error at runtime
/// for inputs containing CR or LF, ensuring safety even when used
/// standalone without the connection layer's validation.
#[test]
fn test_encode_ehlo_rejects_crlf() {
    // Validation now happens in the DomainOrLiteral constructor.
    let err = DomainOrLiteral::new("evil.com\r\nMAIL FROM:<bad>");
    assert!(err.is_err(), "EHLO with CRLF must return Err");
}

/// RFC 5321 Section 4.1.2: embedded CR/LF in the RCPT TO address would
/// inject arbitrary SMTP commands after the RCPT TO line.
#[test]
fn test_encode_rcpt_to_rejects_crlf() {
    // Validation now happens in the ForwardPath constructor.
    let err = ForwardPath::new("a@b\r\nDATA");
    assert!(err.is_err(), "RCPT TO with CRLF must return Err");
}

/// RFC 5321 Section 4.1.2: embedded CR/LF in the MAIL FROM address would
/// inject arbitrary SMTP commands after the MAIL FROM line.
#[test]
fn test_encode_mail_from_rejects_crlf() {
    // Validation now happens in the ReversePath constructor.
    let err = ReversePath::new("a@b\r\nRCPT TO:<evil>");
    assert!(err.is_err(), "MAIL FROM with CRLF must return Err");
}

/// RFC 5321 Section 4.1.2: embedded CR/LF in the RCPT TO address with
/// extension parameters would inject arbitrary SMTP commands.
#[test]
fn test_encode_rcpt_to_full_rejects_crlf() {
    // Validation now happens in the ForwardPath constructor.
    let err = ForwardPath::new("a@b\r\nDATA");
    assert!(err.is_err(), "RCPT TO (full) with CRLF must return Err");
}

/// RFC 5321 Section 4.1.2: embedded CR/LF in the MAIL FROM address
/// (full variant) would inject arbitrary SMTP commands.
#[test]
fn test_encode_mail_from_full_rejects_crlf() {
    // Validation now happens in the ReversePath constructor.
    let err = ReversePath::new("a@b\r\nRCPT TO:<evil>");
    assert!(err.is_err(), "MAIL FROM (full) with CRLF must return Err");
}

/// RFC 5321 Section 4.1.2: embedded CR/LF in the VRFY argument would
/// inject arbitrary SMTP commands after the VRFY line.
#[test]
fn encode_vrfy_rejects_crlf() {
    let mut buf = BytesMut::new();
    let err = encode_vrfy(&mut buf, "user\r\n@example.com");
    assert!(err.is_err(), "VRFY with CRLF must return Err");
}

/// RFC 5321 Section 4.1.2: embedded CR/LF in the EXPN argument would
/// inject arbitrary SMTP commands after the EXPN line.
#[test]
fn encode_expn_rejects_crlf() {
    let mut buf = BytesMut::new();
    let err = encode_expn(&mut buf, "list\r\n@example.com");
    assert!(err.is_err(), "EXPN with CRLF must return Err");
}

#[test]
fn holduntil_rejects_crlf_injection() {
    // RFC 5321 Section 4.1.2: SMTP command lines are terminated by
    // CRLF. Embedded CR/LF in a HOLDUNTIL datetime value would split
    // the MAIL FROM command, potentially injecting arbitrary commands.
    // The encoder must reject such values with an error, consistent
    // with the treatment of all other string parameters.
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        hold_until: Some("2024-12-25T00:00:00Z\r\nRCPT TO:<evil@attacker.com>".into()),
        ..Default::default()
    };
    let result = encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params);
    assert!(
        result.is_err(),
        "HOLDUNTIL with embedded CRLF must return error, not silently strip"
    );
}

#[test]
fn holduntil_valid_datetime() {
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        hold_until: Some("2024-12-25T00:00:00Z".into()),
        ..Default::default()
    };
    let result = encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params);
    assert!(result.is_ok());
    let output = String::from_utf8_lossy(&buf);
    assert!(
        output.contains("HOLDUNTIL=2024-12-25T00:00:00Z"),
        "valid HOLDUNTIL must be included verbatim: {output}"
    );
}

// ===== Edge-case bug-hunting tests =====

/// RFC 5321 Section 4.5.2: a message whose first line is exactly ".\r\n"
/// (the end-of-data indicator) must be dot-stuffed to "..\r\n" so the
/// receiver doesn't prematurely terminate the DATA phase.
#[test]
fn edge_dot_stuff_first_line_dot_crlf() {
    assert_eq!(
        dot_stuff(b".\r\n"),
        b"..\r\n",
        "First line '.' followed by CRLF must be dot-stuffed \
         (RFC 5321 Section 4.5.2)"
    );
}

/// RFC 5321 Section 4.5.2: a message consisting of only a dot (no CRLF)
/// must still be dot-stuffed.
#[test]
fn edge_dot_stuff_single_dot_no_crlf() {
    assert_eq!(
        dot_stuff(b"."),
        b"..",
        "Single dot at start of data must be stuffed (RFC 5321 Section 4.5.2)"
    );
}

/// RFC 5321 Section 4.5.2: consecutive CRLF-dot sequences must each be
/// dot-stuffed independently.
#[test]
fn edge_dot_stuff_consecutive_dot_lines() {
    assert_eq!(
        dot_stuff(b".\r\n.\r\n.\r\n"),
        b"..\r\n..\r\n..\r\n",
        "Consecutive dot-only lines must all be stuffed (RFC 5321 Section 4.5.2)"
    );
}

/// RFC 5321 Section 4.5.2: a bare dot at a CRLF-delimited line start
/// followed by more data must be stuffed. But bare LF must NOT trigger stuffing.
#[test]
fn edge_dot_stuff_mixed_line_endings() {
    // Only CRLF is a valid line boundary for dot-stuffing.
    // bare-LF followed by dot should NOT be stuffed.
    assert_eq!(
        dot_stuff(b"line1\r\n.line2\nline3\n.line4\r\n"),
        b"line1\r\n..line2\nline3\n.line4\r\n",
        "Dot after CRLF must be stuffed; dot after bare LF must not \
         (RFC 5321 Section 4.5.2)"
    );
}

/// RFC 5321 Section 4.5.2: `dot_stuff_size` must agree with `dot_stuff`
/// for edge cases including the termination sequence.
#[test]
fn edge_dot_stuff_size_termination_sequence() {
    let cases: &[&[u8]] = &[b".\r\n", b".", b".\r\n.\r\n.\r\n", b"\r\n.\r\n"];
    for data in cases {
        assert_eq!(
            dot_stuff_size(data),
            dot_stuff(data).len(),
            "dot_stuff_size mismatch for {:?}",
            String::from_utf8_lossy(data)
        );
    }
}

// ── Reverse-path/forward-path 256-octet limit — RFC 5321 §4.5.3.1.3 ──

#[test]
fn mail_from_rejects_overlength_reverse_path() {
    // RFC 5321 Section 4.5.3.1.3: reverse-path max 256 octets including <>
    // So address max is 254 bytes.
    let mut buf = BytesMut::new();
    let domain_189 = format!("{}.{}.{}", "b".repeat(63), "c".repeat(63), "d".repeat(61));
    let addr_254 = format!("{}@{domain_189}", "a".repeat(64));
    assert_eq!(addr_254.len(), 254);
    let rp_254 = ReversePath::new(&addr_254).unwrap();
    assert!(
        encode_mail_from(&mut buf, &rp_254, None).is_ok(),
        "254-byte address should be accepted"
    );

    let domain_190 = format!("{}.{}.{}", "b".repeat(63), "c".repeat(63), "d".repeat(62));
    let addr_255 = format!("{}@{domain_190}", "a".repeat(64));
    assert_eq!(addr_255.len(), 255);
    // Validation now happens in the ReversePath constructor.
    assert!(
        ReversePath::new(&addr_255).is_err(),
        "255-byte address should be rejected"
    );
}

#[test]
fn rcpt_to_rejects_overlength_forward_path() {
    // RFC 5321 Section 4.5.3.1.3: forward-path max 256 octets including <>
    let mut buf = BytesMut::new();
    let domain_189 = format!("{}.{}.{}", "f".repeat(63), "g".repeat(63), "h".repeat(61));
    let addr_254 = format!("{}@{domain_189}", "e".repeat(64));
    assert_eq!(addr_254.len(), 254);
    let fp_254 = ForwardPath::new(&addr_254).unwrap();
    assert!(
        encode_rcpt_to(&mut buf, &fp_254).is_ok(),
        "254-byte address should be accepted"
    );

    let domain_190 = format!("{}.{}.{}", "f".repeat(63), "g".repeat(63), "h".repeat(62));
    let addr_255 = format!("{}@{domain_190}", "e".repeat(64));
    assert_eq!(addr_255.len(), 255);
    // Validation now happens in the ForwardPath constructor.
    assert!(
        ForwardPath::new(&addr_255).is_err(),
        "255-byte address should be rejected"
    );
}

#[test]
fn mail_from_rejects_local_part_longer_than_64_octets() {
    // RFC 5321 Section 4.5.3.1.1: the local-part itself is capped at 64 octets.
    // Validation now happens in the ReversePath/Mailbox constructor.
    let address = format!("{}@example.com", "a".repeat(65));
    let result = ReversePath::new(&address);
    assert!(
        result.is_err(),
        "MAIL FROM local-part >64 octets must be rejected per RFC 5321 \
         Section 4.5.3.1.1"
    );
}

#[test]
fn rcpt_to_rejects_local_part_longer_than_64_octets() {
    // RFC 5321 Section 4.5.3.1.1 applies to forward-path mailboxes too.
    // Validation now happens in the ForwardPath/Mailbox constructor.
    let address = format!("{}@example.com", "a".repeat(65));
    let result = ForwardPath::new(&address);
    assert!(
        result.is_err(),
        "RCPT TO local-part >64 octets must be rejected per RFC 5321 \
         Section 4.5.3.1.1"
    );
}

#[test]
fn mail_from_allows_empty_reverse_path() {
    // RFC 5321 Section 4.1.1.2: empty reverse-path <> is valid for bounces.
    let mut buf = BytesMut::new();
    assert!(encode_mail_from(&mut buf, &rp(""), None).is_ok());
    assert_eq!(&buf[..], b"MAIL FROM:<>\r\n");
}

#[test]
fn mail_from_rejects_invalid_mailbox_syntax() {
    // Validation now happens in the ReversePath/Mailbox constructor.
    let result = ReversePath::new("sender example.com");
    assert!(
        result.is_err(),
        "MAIL FROM must reject invalid Mailbox syntax (RFC 5321 Section 4.1.1.2 / Section 4.1.2)"
    );
}

#[test]
fn rcpt_to_rejects_name_addr_syntax() {
    // Validation now happens in the ForwardPath/Mailbox constructor.
    let result = ForwardPath::new("Recipient <user@example.com>");
    assert!(
        result.is_err(),
        "RCPT TO must reject name-addr syntax and require a bare Mailbox \
         (RFC 5321 Section 4.1.1.3 / Section 4.1.2)"
    );
}

// ── VRFY/EXPN 512-octet line limit — RFC 5321 §4.5.3.1.4 ──────────

#[test]
fn vrfy_within_512_octet_limit() {
    // RFC 5321 Section 4.1.1.6: a short VRFY must succeed.
    // RFC 5321 Section 4.1.2: mailbox-like strings must be quoted because
    // `@` and `.` are not valid `atext`.
    // "VRFY " (5) + DQUOTE (1) + "user@example.com" (16) + DQUOTE (1)
    // + CRLF (2) = 25 octets — well within 512.
    let mut buf = BytesMut::new();
    encode_vrfy(&mut buf, "user@example.com").unwrap();
    assert_eq!(&buf[..], b"VRFY \"user@example.com\"\r\n");
}

#[test]
fn vrfy_exceeds_512_octet_limit() {
    // RFC 5321 Section 4.5.3.1.4: command lines MUST NOT exceed 512 octets
    // including the trailing CRLF.
    // "VRFY " (5) + 510-char arg + CRLF (2) = 517 octets — must be rejected.
    let long_arg = "a".repeat(510);
    let mut buf = BytesMut::new();
    let result = encode_vrfy(&mut buf, &long_arg);
    assert!(
        result.is_err(),
        "VRFY with a 510-char argument produces a 517-octet line and must be rejected \
         (RFC 5321 Section 4.5.3.1.4)"
    );
}

#[test]
fn test_ehlo_rejects_overlong_domain_rfc5321() {
    // RFC 5321 Section 4.5.3.1.4: command line must not exceed 512 octets.
    // Validation now happens in the DomainOrLiteral constructor (255-octet limit).
    let long_domain = "a".repeat(510);
    let result = DomainOrLiteral::new(&long_domain);
    assert!(
        result.is_err(),
        "EHLO with overlong domain must be rejected"
    );
}

#[test]
fn ehlo_rejects_domain_longer_than_255_octets_even_within_line_limit() {
    // RFC 5321 Section 4.5.3.1.2 caps the domain name itself at 255 octets.
    // Validation now happens in the DomainOrLiteral constructor.
    let long_domain = format!("{}.com", "a".repeat(252));
    let result = DomainOrLiteral::new(&long_domain);
    assert!(
        result.is_err(),
        "EHLO domain >255 octets must be rejected even when the command line \
         is shorter than 512 octets (RFC 5321 Section 4.5.3.1.2)"
    );
}

#[test]
fn lhlo_rejects_address_literal_longer_than_255_octets() {
    // RFC 5321 Section 4.5.3.1.2 applies to a domain name or number.
    // Validation now happens in the DomainOrLiteral constructor.
    let long_literal = format!("[TAG:{}]", "a".repeat(250));
    let result = DomainOrLiteral::new(&long_literal);
    assert!(
        result.is_err(),
        "LHLO address-literal >255 octets must be rejected per RFC 5321 \
         Section 4.5.3.1.2"
    );
}

#[test]
fn expn_exceeds_512_octet_limit() {
    // RFC 5321 Section 4.5.3.1.4: command lines MUST NOT exceed 512 octets
    // including the trailing CRLF.
    // "EXPN " (5) + 510-char arg + CRLF (2) = 517 octets — must be rejected.
    let long_arg = "a".repeat(510);
    let mut buf = BytesMut::new();
    let result = encode_expn(&mut buf, &long_arg);
    assert!(
        result.is_err(),
        "EXPN with a 510-char argument produces a 517-octet line and must be rejected \
         (RFC 5321 Section 4.5.3.1.4)"
    );
}

// ===== Targeted edge-case bug-hunting tests =====

// ── MAIL FROM with all parameters simultaneously ──

/// RFC 5321 Section 4.1.1.2 / RFC 1870 / RFC 1652 / RFC 6531 /
/// RFC 3461 / RFC 4865 / RFC 2852: Encode MAIL FROM with SIZE,
/// BODY, SMTPUTF8, RET, ENVID, and HOLDFOR all set at once.
/// Verify that all parameters appear in the correct order and
/// are separated by spaces.
#[test]
fn edge_mail_from_all_params_simultaneously() {
    use crate::types::{BodyType, DeliverBy, DeliverByMode, DsnRet};

    let mut buf = BytesMut::new();
    let params = MailFromParams {
        size: Some(102_400),
        body: Some(BodyType::EightBitMime),
        smtputf8: true,
        requiretls: false,
        ret: Some(DsnRet::Full),
        envid: Some(EnvidValue::new("msg-id-42").unwrap()),
        hold_for: Some(3600),
        hold_until: None,
        deliver_by: Some(DeliverBy {
            seconds: 7200,
            mode: DeliverByMode::Return,
            trace: false,
        }),
        mt_priority: None,
        auth: None,
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    let output = std::str::from_utf8(&buf).unwrap();

    // Verify the command starts correctly
    assert!(
        output.starts_with("MAIL FROM:<sender@example.com>"),
        "command must start with MAIL FROM:<addr>: {output}"
    );
    // Verify ends with CRLF
    assert!(
        output.ends_with("\r\n"),
        "command must end with CRLF: {output}"
    );

    // All parameters must be present
    assert!(
        output.contains(" SIZE=102400"),
        "SIZE param missing: {output}"
    );
    assert!(
        output.contains(" BODY=8BITMIME"),
        "BODY param missing: {output}"
    );
    assert!(
        output.contains(" SMTPUTF8"),
        "SMTPUTF8 param missing: {output}"
    );
    assert!(output.contains(" RET=FULL"), "RET param missing: {output}");
    assert!(
        output.contains(" ENVID=msg-id-42"),
        "ENVID param missing: {output}"
    );
    assert!(
        output.contains(" HOLDFOR=3600"),
        "HOLDFOR param missing: {output}"
    );
    assert!(output.contains(" BY=7200;R"), "BY param missing: {output}");

    // REQUIRETLS and MT-PRIORITY should NOT appear
    assert!(
        !output.contains("REQUIRETLS"),
        "REQUIRETLS should not appear when false: {output}"
    );
    assert!(
        !output.contains("MT-PRIORITY"),
        "MT-PRIORITY should not appear when None: {output}"
    );

    // Verify parameter ordering: SIZE before BODY before SMTPUTF8
    // before RET before ENVID before HOLDFOR before BY
    // (matches the encoding order in the implementation)
    let pos_size = output.find("SIZE=").unwrap();
    let pos_body = output.find("BODY=").unwrap();
    let pos_utf8 = output.find("SMTPUTF8").unwrap();
    let pos_ret = output.find("RET=").unwrap();
    let pos_envid = output.find("ENVID=").unwrap();
    let pos_holdfor = output.find("HOLDFOR=").unwrap();
    let pos_by = output.find("BY=").unwrap();
    assert!(
        pos_size < pos_body
            && pos_body < pos_utf8
            && pos_utf8 < pos_ret
            && pos_ret < pos_envid
            && pos_envid < pos_holdfor
            && pos_holdfor < pos_by,
        "parameters must appear in canonical order: {output}"
    );
}

// ── Xtext encoding of + and = — RFC 3461 §4 ──

/// RFC 3461 Section 4: The '+' character (0x2B) must be encoded as
/// +2B and the '=' character (0x3D) must be encoded as +3D. Verify
/// both in a single string that also contains normal printable ASCII.
#[test]
fn edge_xtext_encoding_plus_and_equals() {
    let mut buf = BytesMut::new();
    encode_xtext(&mut buf, "a+b=c");
    assert_eq!(
        &buf[..],
        b"a+2Bb+3Dc",
        "'+' must become +2B and '=' must become +3D per RFC 3461 Section 4"
    );
}

/// RFC 3461 Section 4: Multiple special characters in sequence.
/// Test that each is encoded independently as +XX hex.
#[test]
fn edge_xtext_encoding_consecutive_specials() {
    let mut buf = BytesMut::new();
    encode_xtext(&mut buf, "++=");
    // '+' -> +2B, '+' -> +2B, '=' -> +3D
    assert_eq!(
        &buf[..],
        b"+2B+2B+3D",
        "consecutive '+' and '=' must each be hex-encoded per RFC 3461 Section 4"
    );
}

/// RFC 3461 Section 4: Characters below 0x21 (except for '+' and '=')
/// must be hex-encoded. Verify NUL, TAB, and DEL (0x7F) are encoded.
#[test]
fn edge_xtext_encoding_control_and_high_chars() {
    let mut buf = BytesMut::new();
    encode_xtext(&mut buf, "\x00\x09\x7f");
    // NUL (0x00) -> +00, TAB (0x09) -> +09, DEL (0x7F) -> +7F
    assert_eq!(
        &buf[..],
        b"+00+09+7F",
        "control characters and DEL must be hex-encoded per RFC 3461 Section 4"
    );
}

// ── DELIVERBY with negative seconds — RFC 2852 §4 ──

/// RFC 2852 Section 4: "A signed-by-time of 0 or less is used to
/// indicate that the message has already been in transit for too long."
/// Negative seconds indicate the message has been in transit for that
/// many seconds. Verify BY=-300;N is encoded correctly.
#[test]
fn edge_deliver_by_negative_seconds() {
    use crate::types::{DeliverBy, DeliverByMode};

    let mut buf = BytesMut::new();
    let params = MailFromParams {
        deliver_by: Some(DeliverBy {
            seconds: -300,
            mode: DeliverByMode::Notify,
            trace: false,
        }),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> BY=-300;N\r\n",
        "negative DELIVERBY seconds must be encoded with minus sign \
         (RFC 2852 Section 4)"
    );
}

/// RFC 2852 Section 4: a by-mode of `R` forbids zero or negative by-time.
#[test]
fn edge_deliver_by_negative_seconds_with_return_mode_rejected() {
    use crate::types::{DeliverBy, DeliverByMode};

    let mut buf = BytesMut::new();
    let params = MailFromParams {
        deliver_by: Some(DeliverBy {
            seconds: -600,
            mode: DeliverByMode::Return,
            trace: true,
        }),
        ..Default::default()
    };
    let result = encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params);
    assert!(
        result.is_err(),
        "BY=-600;RT must be rejected because RFC 2852 Section 4 forbids non-positive by-time with Return mode"
    );
}

#[test]
fn encode_mail_from_full_rejects_ten_digit_deliverby() {
    use crate::types::{DeliverBy, DeliverByMode};

    // RFC 2852 Section 4: by-time = ["-" / "+"]1*9DIGIT.
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        deliver_by: Some(DeliverBy {
            seconds: 1_000_000_000,
            mode: DeliverByMode::Notify,
            trace: false,
        }),
        ..Default::default()
    };
    let result = encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params);
    assert!(
        result.is_err(),
        "DELIVERBY with more than 9 digits must be rejected (RFC 2852 Section 4)"
    );
}

// ── RCPT TO line length validation — RFC 5321 §4.5.3.1 ──

/// RFC 5321 Section 4.5.3.1.3: The forward-path (RCPT TO address)
/// must not exceed 256 octets including angle brackets. An address
/// of exactly 254 bytes produces `<254-byte-addr>` = 256 octets,
/// which is the limit.
#[test]
fn edge_rcpt_to_at_exact_path_limit() {
    // 254-byte address is the maximum: <addr> = 256 octets
    let domain_189 = format!("{}.{}.{}", "j".repeat(63), "k".repeat(63), "l".repeat(61));
    let addr = format!("{}@{domain_189}", "i".repeat(64));
    assert_eq!(addr.len(), 254);

    let fp_addr = ForwardPath::new(&addr).unwrap();
    let mut buf = BytesMut::new();
    assert!(
        encode_rcpt_to(&mut buf, &fp_addr).is_ok(),
        "254-byte address must be accepted (RFC 5321 Section 4.5.3.1.3)"
    );
}

/// RFC 5321 Section 4.5.3.1.3: A 255-byte address produces
/// `<255-byte-addr>` = 257 octets, which exceeds the 256-octet limit.
#[test]
fn edge_rcpt_to_exceeds_path_limit() {
    let domain_190 = format!("{}.{}.{}", "n".repeat(63), "o".repeat(63), "p".repeat(62));
    let addr = format!("{}@{domain_190}", "m".repeat(64));
    assert_eq!(addr.len(), 255);

    // Validation now happens in the ForwardPath constructor.
    assert!(
        ForwardPath::new(&addr).is_err(),
        "255-byte address must be rejected (RFC 5321 Section 4.5.3.1.3)"
    );
}

/// RFC 5321 Section 4.5.3.1.3 / RFC 3461 Section 4: path-length limit
/// is on the address, not the command line. 254-byte address with DSN
/// parameters must still be accepted.
#[test]
fn edge_rcpt_to_with_dsn_params_path_limit_is_on_address() {
    let domain_189 = format!("{}.{}.{}", "r".repeat(63), "s".repeat(63), "t".repeat(61));
    let addr = format!("{}@{domain_189}", "q".repeat(64));
    assert_eq!(addr.len(), 254);

    let fp_addr = ForwardPath::new(&addr).unwrap();
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        notify: Some(vec![
            DsnNotify::Success,
            DsnNotify::Failure,
            DsnNotify::Delay,
        ]),
        orcpt: Some("original@example.com".into()),
    };
    assert!(
        encode_rcpt_to_full(&mut buf, &fp_addr, &params).is_ok(),
        "254-byte address with DSN params must be accepted: the 256-octet \
         limit applies to <forward-path>, not the entire command line \
         (RFC 5321 Section 4.5.3.1.3)"
    );

    let output = std::str::from_utf8(&buf).unwrap();
    assert!(
        output.contains("NOTIFY=SUCCESS,FAILURE,DELAY"),
        "NOTIFY params must be present: {output}"
    );
    assert!(
        output.contains("ORCPT=rfc822;original@example.com"),
        "ORCPT param must be present: {output}"
    );
}

/// RFC 5321 Section 4.5.3.1.3: A 255-byte address must be
/// rejected even when using the full RCPT TO variant with DSN params.
#[test]
fn edge_rcpt_to_full_overlength_address_rejected_with_dsn() {
    let local = "a".repeat(246);
    let addr = format!("{local}@test.com"); // 255 bytes
    assert_eq!(addr.len(), 255);

    // Validation now happens in the ForwardPath constructor.
    assert!(
        ForwardPath::new(&addr).is_err(),
        "255-byte address must be rejected even with DSN params \
         (RFC 5321 Section 4.5.3.1.3)"
    );
}

/// RFC 3461 Section 5: when DSN parameters are present, RCPT TO command
/// lines may grow beyond 512 octets but MUST still remain within 1012.
/// The standalone codec encoder must enforce that limit too, not just the
/// connection layer.
#[test]
fn edge_rcpt_to_full_rejects_line_over_1012_with_dsn() {
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        notify: Some(vec![DsnNotify::Success]),
        orcpt: Some("a".repeat(980)),
    };

    let result = encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params);
    assert!(
        result.is_err(),
        "RCPT TO with DSN params exceeding 1012 octets must be rejected \
         (RFC 3461 Section 5)"
    );
}

#[test]
fn encode_mail_from_full_rejects_empty_envid() {
    // RFC 3461 Section 4.4: ENVID=xtext where xtext = 1*xchar (non-empty)
    // Validation now happens in the EnvidValue constructor.
    assert!(
        EnvidValue::new("").is_err(),
        "RFC 3461 Section 4.4: empty ENVID must be rejected (xtext = 1*xchar)"
    );
}

#[test]
fn encode_mail_from_full_rejects_non_ascii_envid() {
    // RFC 3461 Section 4.4: the envelope identifier must be printable US-ASCII.
    // Validation now happens in the EnvidValue constructor.
    assert!(
        EnvidValue::new("résumé-42").is_err(),
        "RFC 3461 Section 4.4: non-ASCII ENVID must be rejected before xtext encoding"
    );
}

#[test]
fn encode_mail_from_full_rejects_envid_longer_than_100_chars() {
    // RFC 3461 Section 4.4: "The ENVID parameter MAY be up to 100 characters in length."
    // Validation now happens in the EnvidValue constructor.
    assert!(
        EnvidValue::new("a".repeat(101)).is_err(),
        "RFC 3461 Section 4.4: ENVID values longer than 100 characters must be rejected"
    );
}

#[test]
fn encode_rcpt_to_full_rejects_empty_orcpt() {
    // RFC 3461 Section 4.2: ORCPT=addr-type;xtext where xtext = 1*xchar (non-empty)
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        orcpt: Some(String::new()),
        ..Default::default()
    };
    let result = encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params);
    assert!(
        result.is_err(),
        "RFC 3461 Section 4.2: empty ORCPT must be rejected (xtext = 1*xchar)"
    );
}

// ── AUTH= parameter — RFC 4954 Section 5 ──────────────────────────

#[test]
fn encode_mail_from_auth_mailbox() {
    // RFC 4954 Section 5: AUTH=<mailbox> declares the original
    // authenticated sender. The mailbox is xtext-encoded.
    use crate::types::SmtpAuthParam;
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        auth: Some(SmtpAuthParam::Mailbox(
            Mailbox::new("user@example.com").unwrap(),
        )),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(
        &buf[..],
        b"MAIL FROM:<sender@example.com> AUTH=user@example.com\r\n"
    );
}

// ── utf-8-addr-xtext encoding — RFC 6533 §3 ──

#[test]
fn orcpt_utf8_passes_multibyte_through() {
    // RFC 6533 Section 3: utf-8-addr-xtext passes multi-byte UTF-8
    // (EXT-UTF8-CHAR = UTF8-2 / UTF8-3 / UTF8-4) through literally,
    // unlike RFC 3461 xtext which hex-encodes all bytes > 0x7E.
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        orcpt: Some("user@example.日本".into()),
        ..Default::default()
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    // "日本" is U+65E5 U+672C, encoded as 3-byte UTF-8 sequences.
    // RFC 6533 Section 3: these must pass through literally, NOT be hex-encoded.
    // Use bytes comparison to avoid from_utf8 issues if the output is not valid UTF-8.
    let output = &buf[..];
    let expected_suffix = "user@example.日本\r\n";
    assert!(
        output.ends_with(expected_suffix.as_bytes()),
        "multi-byte UTF-8 must pass through literally per RFC 6533 Section 3, got: {:?}",
        String::from_utf8_lossy(output)
    );
}

#[test]
fn orcpt_utf8_hex_encodes_backslash() {
    // RFC 6533 Section 3: QCHAR excludes backslash (0x5C), so it must be
    // hex-encoded as +5C in utf-8-addr-xtext.
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        // Use a non-ASCII char to trigger utf-8 addr-type, plus a backslash.
        orcpt: Some("user\\name@example.日本".into()),
        ..Default::default()
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    let output = String::from_utf8_lossy(&buf);
    assert!(
        output.contains("+5C"),
        "backslash must be hex-encoded as +5C per RFC 6533 Section 3 QCHAR, got: {output}"
    );
    // The literal backslash character must NOT appear in the encoded output.
    let after_semicolon = output.split(';').nth(1).unwrap_or("");
    assert!(
        !after_semicolon.contains('\\'),
        "literal backslash must not appear in utf-8-addr-xtext, got: {output}"
    );
}

#[test]
fn orcpt_utf8_hex_encodes_plus_and_equals() {
    // RFC 6533 Section 3: QCHAR excludes '+' (0x2B) and '=' (0x3D),
    // same as RFC 3461 xtext.
    let mut buf = BytesMut::new();
    let params = RcptToParams {
        // Use a non-ASCII char to trigger utf-8 addr-type, plus '+' and '='.
        orcpt: Some("user+tag=val@example.日本".into()),
        ..Default::default()
    };
    encode_rcpt_to_full(&mut buf, &fp("user@example.com"), &params).unwrap();
    let output = String::from_utf8_lossy(&buf);
    assert!(
        output.contains("+2B"),
        "'+' must be hex-encoded as +2B per RFC 6533 Section 3 QCHAR, got: {output}"
    );
    assert!(
        output.contains("+3D"),
        "'=' must be hex-encoded as +3D per RFC 6533 Section 3 QCHAR, got: {output}"
    );
}

#[test]
fn encode_utf8_addr_xtext_full_coverage() {
    // RFC 6533 Section 3: Direct unit test of encode_utf8_addr_xtext.
    // Multi-byte UTF-8 passes through, backslash is hex-encoded,
    // '+' and '=' are hex-encoded, printable ASCII passes through.
    let mut buf = BytesMut::new();
    encode_utf8_addr_xtext(&mut buf, "abc\\+=@日本");
    assert_eq!(
        std::str::from_utf8(&buf).unwrap(),
        "abc+5C+2B+3D@日本",
        "utf-8-addr-xtext must encode \\, +, = and pass through multibyte UTF-8"
    );
}

#[test]
fn encode_utf8_addr_xtext_control_chars() {
    // RFC 6533 Section 3: SP and control characters must be hex-encoded.
    let mut buf = BytesMut::new();
    encode_utf8_addr_xtext(&mut buf, "a b\x00\x7f");
    assert_eq!(
        &buf[..],
        b"a+20b+00+7F",
        "SP, NUL, DEL must be hex-encoded per RFC 6533 Section 3"
    );
}

#[test]
fn encode_mail_from_auth_empty() {
    // RFC 4954 Section 5: AUTH=<> indicates the identity of the
    // original submitter is unknown or unauthenticated.
    use crate::types::SmtpAuthParam;
    let mut buf = BytesMut::new();
    let params = MailFromParams {
        auth: Some(SmtpAuthParam::Empty),
        ..Default::default()
    };
    encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params).unwrap();
    assert_eq!(&buf[..], b"MAIL FROM:<sender@example.com> AUTH=<>\r\n");
}

#[test]
fn encode_mail_from_auth_rejects_empty_mailbox() {
    // RFC 4954 Section 5 / Section 8: the decoded AUTH xtext must be
    // either a mailbox or "<>", not an empty string.
    // Validation now happens in the Mailbox constructor — empty is rejected.
    assert!(
        Mailbox::new("").is_err(),
        "MAIL FROM AUTH= with an empty mailbox must be rejected (RFC 4954 Section 8)"
    );
}

#[test]
fn encode_mail_from_auth_rejects_name_addr_form() {
    // RFC 4954 Section 5: AUTH= carries a mailbox identity, not an
    // RFC 5322 name-addr. Validation now happens in the Mailbox constructor.
    assert!(
        Mailbox::new("Submitter <user@example.com>").is_err(),
        "MAIL FROM AUTH= must reject name-addr values and accept only mailbox syntax \
         (RFC 4954 Section 5 / RFC 5321 Section 4.1.2)"
    );
}

#[test]
fn encode_mail_from_auth_rejects_non_ascii_mailbox() {
    // RFC 4954 Section 5 references the SMTP `Mailbox` production from
    // RFC 5321 Section 4.1.2, which is US-ASCII only. SMTPUTF8 extends
    // MAIL FROM / RCPT TO, but not the AUTH= submitter identity.
    // The Mailbox newtype allows non-ASCII, but the encoder checks ASCII
    // for the AUTH= parameter specifically.
    use crate::types::SmtpAuthParam;

    let mut buf = BytesMut::new();
    let params = MailFromParams {
        auth: Some(SmtpAuthParam::Mailbox(
            Mailbox::new("pelé@example.com").unwrap(),
        )),
        ..Default::default()
    };
    let result = encode_mail_from_full(&mut buf, &rp("sender@example.com"), &params);
    assert!(
        result.is_err(),
        "MAIL FROM AUTH= must reject non-ASCII mailbox identities \
         (RFC 4954 Section 5 / RFC 5321 Section 4.1.2)"
    );
}

#[test]
fn mail_from_line_limit_matches_registered_extension_budget() {
    // RFC 4954 Section 3 adds 500 octets for AUTH=.
    // RFC 4865 Section 5 adds 34 octets for HOLDFOR/HOLDUNTIL.
    // With the currently supported MAIL FROM extensions, the exact
    // client-side limit is therefore 1252 octets.
    assert!(
        validate_mail_from_line_length(1252).is_ok(),
        "MAIL FROM at the RFC-extended 1252-octet limit must pass"
    );
    assert!(
        validate_mail_from_line_length(1253).is_err(),
        "MAIL FROM above the RFC-extended 1252-octet limit must fail"
    );
}

// ========================================================================
// Property-based round-trip and invariant tests
// ========================================================================

#[allow(clippy::expect_used)]
mod prop_roundtrip {
    use super::*;
    use crate::codec::decode;
    use crate::types::{AuthMechanism, EnhancedStatusCode, SmtpExtension, SmtpResponse};
    use proptest::prelude::*;

    // ── Generators ──────────────────────────────────────────────────

    /// Generate a valid DNS label (1-63 chars, starts/ends with alnum,
    /// internal chars are alnum or hyphen).
    /// RFC 1035 Section 2.3.1, RFC 5321 Section 4.1.2.
    fn arb_dns_label() -> impl Strategy<Value = String> {
        // Length 1: single alnum char
        // Length 2+: start alnum, middle alnum/hyphen, end alnum
        prop::string::string_regex("[a-zA-Z0-9]([a-zA-Z0-9-]{0,10}[a-zA-Z0-9])?")
            .expect("valid regex")
    }

    /// Generate a valid SMTP domain (1-3 labels, total ≤ 255 octets).
    /// RFC 5321 Section 4.1.2.
    fn arb_domain() -> impl Strategy<Value = String> {
        prop::collection::vec(arb_dns_label(), 1..=3)
            .prop_map(|labels| labels.join("."))
            .prop_filter("domain ≤ 255 octets", |d| d.len() <= 255)
    }

    /// Generate a valid IPv4 address literal.
    /// RFC 5321 Section 4.1.3.
    fn arb_ipv4_literal() -> impl Strategy<Value = String> {
        (any::<u8>(), any::<u8>(), any::<u8>(), any::<u8>())
            .prop_map(|(a, b, c, d)| format!("[{a}.{b}.{c}.{d}]"))
    }

    /// Generate a valid IPv6 address literal.
    /// RFC 5321 Section 4.1.3.
    fn arb_ipv6_literal() -> impl Strategy<Value = String> {
        any::<u128>().prop_map(|n| {
            let addr = std::net::Ipv6Addr::from(n);
            format!("[IPv6:{addr}]")
        })
    }

    /// Generate a domain-or-address-literal (for EHLO).
    fn arb_domain_or_literal() -> impl Strategy<Value = String> {
        prop_oneof![arb_domain(), arb_ipv4_literal(), arb_ipv6_literal(),]
    }

    /// Generate a valid local-part (≤ 64 octets, printable ASCII, no specials).
    /// RFC 5321 Section 4.1.2 / RFC 5322 Section 3.2.3.
    fn arb_local_part() -> impl Strategy<Value = String> {
        prop::string::string_regex("[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]{1,30}")
            .expect("valid regex")
            .prop_filter("local-part ≤ 64 octets", |lp| lp.len() <= 64)
    }

    /// Generate a valid SMTP mailbox (local-part@domain).
    /// RFC 5321 Section 4.1.2.
    fn arb_mailbox() -> impl Strategy<Value = String> {
        (arb_local_part(), arb_domain())
            .prop_map(|(lp, dom)| format!("{lp}@{dom}"))
            .prop_filter("mailbox ≤ 254 octets", |m| m.len() <= 254)
    }

    /// Generate a valid ENVID value (printable ASCII, 1-100 chars).
    /// RFC 3461 Section 4.4.
    fn arb_envid() -> impl Strategy<Value = String> {
        prop::string::string_regex("[!-~]{1,50}").expect("valid regex")
    }

    /// Generate a valid printable ASCII query string for VRFY/EXPN.
    fn arb_query_string() -> impl Strategy<Value = String> {
        // Must be valid SMTP atom chars, non-empty, short enough for 512 line limit
        prop::string::string_regex("[a-zA-Z0-9.!#$%&'*+/=?^_-]{1,50}").expect("valid regex")
    }

    // ── dot_stuff round-trip ────────────────────────────────────────

    /// Reverse dot-stuffing: remove the extra dot prepended by the sender.
    ///
    /// RFC 5321 Section 4.5.2: "When a line of mail text is received by
    /// the SMTP server, it checks the line. If the line is composed of a
    /// single period, it is treated as the end of mail indicator. If the
    /// first character is a period and there are other characters on the
    /// line, the first character is deleted."
    fn dot_unstuff(data: &[u8]) -> Vec<u8> {
        let mut result = Vec::with_capacity(data.len());
        let mut at_line_start = true;
        let mut prev_cr = false;
        let mut skip_next = false;

        for &byte in data {
            if skip_next {
                skip_next = false;
                result.push(byte);
                at_line_start = byte == b'\n' && prev_cr;
                prev_cr = byte == b'\r';
                continue;
            }
            if at_line_start && byte == b'.' {
                // RFC 5321 Section 4.5.2: strip the leading dot
                skip_next = true;
                at_line_start = false;
                prev_cr = false;
                continue;
            }
            result.push(byte);
            at_line_start = byte == b'\n' && prev_cr;
            prev_cr = byte == b'\r';
        }

        result
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(500))]

        /// dot_stuff round-trip: unstuff(stuff(data)) == data for any
        /// CRLF-terminated message body.
        /// RFC 5321 Section 4.5.2.
        #[test]
        fn dot_stuff_roundtrip(data in prop::collection::vec(any::<u8>(), 0..1000)) {
            let stuffed = dot_stuff(&data);
            let unstuffed = dot_unstuff(&stuffed);
            prop_assert_eq!(
                &unstuffed, &data,
                "dot_unstuff(dot_stuff(data)) must equal data"
            );
        }

        /// dot_stuff output never contains the end-of-data marker
        /// (a line consisting of just ".") as a false positive.
        /// RFC 5321 Section 4.5.2.
        #[test]
        fn dot_stuff_no_false_terminator(data in prop::collection::vec(any::<u8>(), 0..500)) {
            let stuffed = dot_stuff(&data);
            // Check that "\r\n.\r\n" does not appear in the stuffed output
            // unless it was genuinely preceded by data ending in CRLF and
            // followed by CRLF (which would be "..CRLF" after stuffing).
            // The simpler check: no line in the stuffed output is exactly ".".
            let mut at_line_start = true;
            let mut prev_cr = false;
            for (i, &byte) in stuffed.iter().enumerate() {
                if at_line_start && byte == b'.' {
                    // Next byte must exist (the extra dot from stuffing)
                    // or this dot is at the very end of the data (which is
                    // fine — only CRLF.CRLF is the terminator).
                    if i + 1 < stuffed.len() {
                        let next = stuffed[i + 1];
                        // After stuffing, a dot at line start should always
                        // be followed by another dot (the original content).
                        // It should never be followed by \r (which would
                        // make it look like ".\r\n" = end-of-data).
                        prop_assert_ne!(
                            next, b'\r',
                            "stuffed output must not contain a bare dot line \
                             (would be mistaken for end-of-data)"
                        );
                    }
                }
                at_line_start = byte == b'\n' && prev_cr;
                prev_cr = byte == b'\r';
            }
        }

        /// dot_stuff_size matches dot_stuff().len() for arbitrary input.
        /// RFC 5321 Section 4.5.2 / RFC 1870 Section 3.
        #[test]
        fn dot_stuff_size_matches_len(data in prop::collection::vec(any::<u8>(), 0..500)) {
            prop_assert_eq!(
                dot_stuff_size(&data),
                dot_stuff(&data).len(),
                "dot_stuff_size must match dot_stuff().len()"
            );
        }
    }

    // ── xtext round-trip ────────────────────────────────────────────

    /// Decode xtext encoding per RFC 3461 Section 4.
    fn decode_xtext(encoded: &[u8]) -> Option<Vec<u8>> {
        let mut result = Vec::with_capacity(encoded.len());
        let mut i = 0;
        while i < encoded.len() {
            if encoded[i] == b'+' {
                if i + 2 >= encoded.len() {
                    return None;
                }
                let hi = char::from(encoded[i + 1]).to_digit(16)?;
                let lo = char::from(encoded[i + 2]).to_digit(16)?;
                #[allow(clippy::cast_possible_truncation)]
                result.push((hi * 16 + lo) as u8);
                i += 3;
            } else {
                result.push(encoded[i]);
                i += 1;
            }
        }
        Some(result)
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(500))]

        /// xtext encoding round-trip: decode(encode(s)) == s for printable
        /// ASCII strings.
        /// RFC 3461 Section 4.
        #[test]
        fn xtext_roundtrip(s in "[!-~]{0,80}") {
            let mut buf = BytesMut::new();
            encode_xtext(&mut buf, &s);
            let decoded = decode_xtext(&buf)
                .expect("xtext decode must succeed on encode output");
            prop_assert_eq!(
                &decoded, s.as_bytes(),
                "decode_xtext(encode_xtext(s)) must equal s"
            );
        }

        /// xtext output contains only valid xchar bytes.
        /// RFC 3461 Section 4: xchar = %x21-2A / %x2C-3C / %x3E-7E / hexchar.
        #[test]
        fn xtext_output_valid(s in "[!-~]{0,80}") {
            let mut buf = BytesMut::new();
            encode_xtext(&mut buf, &s);
            let mut i = 0;
            while i < buf.len() {
                let b = buf[i];
                if b == b'+' {
                    // hexchar: + 2HEXDIG
                    prop_assert!(i + 2 < buf.len(), "truncated hexchar at {i}");
                    prop_assert!(
                        buf[i + 1].is_ascii_hexdigit() && buf[i + 2].is_ascii_hexdigit(),
                        "invalid hexchar at {i}: {:?}",
                        &buf[i..i + 3]
                    );
                    i += 3;
                } else {
                    // xchar: must be in allowed ranges
                    prop_assert!(
                        (0x21..=0x2A).contains(&b)
                            || (0x2C..=0x3C).contains(&b)
                            || (0x3E..=0x7E).contains(&b),
                        "byte {b:#04x} at {i} is not a valid xchar"
                    );
                    i += 1;
                }
            }
        }
    }

    // ── EHLO capability round-trip ──────────────────────────────────

    /// Generate an `SmtpExtension` for EHLO round-trip testing.
    fn arb_extension() -> impl Strategy<Value = SmtpExtension> {
        prop_oneof![
            Just(SmtpExtension::EightBitMime),
            Just(SmtpExtension::Pipelining),
            prop_oneof![
                Just(SmtpExtension::Size(None)),
                any::<u32>().prop_map(|n| SmtpExtension::Size(Some(u64::from(n)))),
            ],
            Just(SmtpExtension::StartTls),
            prop::collection::vec(
                prop_oneof![
                    Just(AuthMechanism::Plain),
                    Just(AuthMechanism::Login),
                    Just(AuthMechanism::OAuthBearer),
                    Just(AuthMechanism::XOAuth2),
                ],
                1..=3
            )
            .prop_map(SmtpExtension::Auth),
            Just(SmtpExtension::Chunking),
            Just(SmtpExtension::BinaryMime),
            Just(SmtpExtension::SmtpUtf8),
            Just(SmtpExtension::EnhancedStatusCodes),
            Just(SmtpExtension::Dsn),
            Just(SmtpExtension::RequireTls),
            Just(SmtpExtension::MtPriority),
            Just(SmtpExtension::Vrfy),
            Just(SmtpExtension::Expn),
            prop_oneof![
                Just(SmtpExtension::DeliverBy(None)),
                (0_u64..=999_999_999_u64).prop_map(|n| SmtpExtension::DeliverBy(Some(n))),
            ],
        ]
    }

    /// Format a single EHLO extension as the line it would appear in an
    /// EHLO response (without the "250-" prefix).
    fn format_extension(ext: &SmtpExtension) -> Option<String> {
        Some(match ext {
            SmtpExtension::EightBitMime => "8BITMIME".into(),
            SmtpExtension::Pipelining => "PIPELINING".into(),
            SmtpExtension::Size(None) => "SIZE".into(),
            SmtpExtension::Size(Some(n)) => format!("SIZE {n}"),
            SmtpExtension::StartTls => "STARTTLS".into(),
            SmtpExtension::Auth(mechs) => {
                let names: Vec<&str> = mechs
                    .iter()
                    .map(|m| match m {
                        AuthMechanism::Plain => "PLAIN",
                        AuthMechanism::Login => "LOGIN",
                        AuthMechanism::OAuthBearer => "OAUTHBEARER",
                        AuthMechanism::XOAuth2 => "XOAUTH2",
                        AuthMechanism::Other(s) => s.as_str(),
                    })
                    .collect();
                format!("AUTH {}", names.join(" "))
            }
            SmtpExtension::Chunking => "CHUNKING".into(),
            SmtpExtension::BinaryMime => "BINARYMIME".into(),
            SmtpExtension::SmtpUtf8 => "SMTPUTF8".into(),
            SmtpExtension::EnhancedStatusCodes => "ENHANCEDSTATUSCODES".into(),
            SmtpExtension::Dsn => "DSN".into(),
            SmtpExtension::RequireTls => "REQUIRETLS".into(),
            SmtpExtension::MtPriority => "MT-PRIORITY".into(),
            SmtpExtension::Vrfy => "VRFY".into(),
            SmtpExtension::Expn => "EXPN".into(),
            SmtpExtension::DeliverBy(None) => "DELIVERBY".into(),
            SmtpExtension::DeliverBy(Some(n)) => format!("DELIVERBY {n}"),
            _ => return None,
        })
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(200))]

        /// EHLO capability round-trip: format extensions as EHLO response
        /// lines → parse_ehlo_capabilities → compare extensions.
        /// RFC 5321 Section 4.1.1.1.
        #[test]
        fn ehlo_capability_roundtrip(
            greeting in arb_domain(),
            extensions in prop::collection::vec(arb_extension(), 0..=5)
                .prop_map(|exts| {
                    // Deduplicate: the parser merges multiple AUTH lines into
                    // one and collapses duplicate extension keywords. Keep at
                    // most one of each variant kind to make the comparison
                    // straightforward.
                    let mut seen_auth = false;
                    let mut seen_kinds = std::collections::HashSet::new();
                    exts.into_iter().filter(|ext| {
                        let kind = std::mem::discriminant(ext);
                        if matches!(ext, SmtpExtension::Auth(_)) {
                            if seen_auth { return false; }
                            seen_auth = true;
                            return true;
                        }
                        seen_kinds.insert(kind)
                    }).collect::<Vec<_>>()
                })
        ) {
            // Build an SmtpResponse mimicking a 250 EHLO reply.
            let mut lines = Vec::new();
            lines.push(greeting.clone());
            for ext in &extensions {
                if let Some(line) = format_extension(ext) {
                    lines.push(line);
                }
            }
            let response = SmtpResponse {
                code: 250,
                enhanced_code: None,
                lines,
            };

            let caps = decode::parse_ehlo_capabilities(&response);

            // Greeting name should match (first token of first line).
            prop_assert_eq!(&caps.greeting_name, &greeting);

            // Each generated extension should be present in parsed caps.
            for ext in &extensions {
                #[allow(clippy::match_same_arms)]
                let found = caps.extensions.iter().any(|parsed| {
                    match (parsed, ext) {
                        (SmtpExtension::EightBitMime, SmtpExtension::EightBitMime)
                        | (SmtpExtension::Pipelining, SmtpExtension::Pipelining)
                        | (SmtpExtension::StartTls, SmtpExtension::StartTls)
                        | (SmtpExtension::Chunking, SmtpExtension::Chunking)
                        | (SmtpExtension::BinaryMime, SmtpExtension::BinaryMime)
                        | (SmtpExtension::SmtpUtf8, SmtpExtension::SmtpUtf8)
                        | (SmtpExtension::EnhancedStatusCodes, SmtpExtension::EnhancedStatusCodes)
                        | (SmtpExtension::Dsn, SmtpExtension::Dsn)
                        | (SmtpExtension::RequireTls, SmtpExtension::RequireTls)
                        | (SmtpExtension::MtPriority, SmtpExtension::MtPriority)
                        | (SmtpExtension::Vrfy, SmtpExtension::Vrfy)
                        | (SmtpExtension::Expn, SmtpExtension::Expn) => true,
                        (SmtpExtension::Size(a), SmtpExtension::Size(b)) => a == b,
                        (SmtpExtension::Auth(a), SmtpExtension::Auth(b)) => {
                            a.len() == b.len()
                                && a.iter().zip(b.iter()).all(|(x, y)| x.eq_mechanism(y))
                        }
                        (SmtpExtension::DeliverBy(a), SmtpExtension::DeliverBy(b)) => a == b,
                        _ => false,
                    }
                });
                prop_assert!(
                    found,
                    "extension {:?} not found in parsed capabilities: {:?}",
                    ext, caps.extensions
                );
            }
        }
    }

    // ── SmtpResponse round-trip ─────────────────────────────────────

    /// Format an `SmtpResponse` as wire bytes for parsing.
    fn format_response(resp: &SmtpResponse) -> Vec<u8> {
        let mut out = Vec::new();
        let code = resp.code;
        let enhanced = resp
            .enhanced_code
            .map(|e| format!("{}.{}.{} ", e.class, e.subject, e.detail))
            .unwrap_or_default();

        for (i, line) in resp.lines.iter().enumerate() {
            let sep = if i + 1 < resp.lines.len() { '-' } else { ' ' };
            out.extend_from_slice(format!("{code}{sep}{enhanced}{line}\r\n").as_bytes());
        }
        if resp.lines.is_empty() {
            out.extend_from_slice(format!("{code} {enhanced}\r\n").as_bytes());
        }
        out
    }

    /// Generate a safe response text line (no CRLF, printable ASCII).
    fn arb_response_text() -> impl Strategy<Value = String> {
        prop::string::string_regex("[a-zA-Z0-9 _.,-]{0,60}").expect("valid regex")
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(300))]

        /// SmtpResponse round-trip: format → parse → compare.
        /// RFC 5321 Section 4.2.
        #[test]
        fn smtp_response_roundtrip(
            code in prop_oneof![
                200u16..=299,
                400u16..=499,
                500u16..=599,
            ],
            has_enhanced in any::<bool>(),
            subject in 0..=99u16,
            detail in 0..=99u16,
            lines in prop::collection::vec(arb_response_text(), 1..=3),
        ) {
            // RFC 2034: enhanced code class must be 2, 4, or 5
            // matching the reply code class.
            let enhanced = if has_enhanced {
                #[allow(clippy::cast_possible_truncation)]
                let class = (code / 100) as u8;
                Some(EnhancedStatusCode { class, subject, detail })
            } else {
                None
            };

            let original = SmtpResponse {
                code,
                enhanced_code: enhanced,
                lines,
            };

            let wire = format_response(&original);
            let parsed = decode::parse_response(&wire);
            match parsed {
                Ok((remaining, resp)) => {
                    prop_assert!(
                        remaining.is_empty(),
                        "parser left unconsumed bytes: {:?}",
                        remaining
                    );
                    prop_assert_eq!(resp.code, original.code, "reply code mismatch");
                    prop_assert_eq!(
                        resp.enhanced_code, original.enhanced_code,
                        "enhanced code mismatch"
                    );
                    // Response text lines: the parser may strip the enhanced code
                    // prefix from each line, so compare after accounting for that.
                    prop_assert_eq!(
                        resp.lines.len(),
                        original.lines.len(),
                        "line count mismatch"
                    );
                    for (idx, (parsed_line, orig_line)) in
                        resp.lines.iter().zip(original.lines.iter()).enumerate()
                    {
                        prop_assert!(
                            parsed_line == orig_line,
                            "line {} mismatch: {:?} != {:?}",
                            idx, parsed_line, orig_line
                        );
                    }
                }
                Err(e) => {
                    prop_assert!(
                        false,
                        "parse_response failed on formatted input: {e:?}\nwire: {:?}",
                        String::from_utf8_lossy(&wire)
                    );
                }
            }
        }
    }

    // ── Command well-formedness invariants ──────────────────────────

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(300))]

        /// Every EHLO command ends with CRLF and starts with "EHLO ".
        /// RFC 5321 Section 4.1.1.1.
        #[test]
        fn ehlo_well_formed(domain in arb_domain_or_literal()) {
            let Ok(dol) = DomainOrLiteral::new(&domain) else { return Ok(()); };
            let mut buf = BytesMut::new();
            if matches!(encode_ehlo(&mut buf, &dol), Ok(())) {
                let bytes = &buf[..];
                prop_assert!(
                    bytes.ends_with(b"\r\n"),
                    "EHLO must end with CRLF"
                );
                prop_assert!(
                    bytes.starts_with(b"EHLO "),
                    "EHLO must start with 'EHLO '"
                );
                // No internal CRLF (only trailing)
                let body = &bytes[..bytes.len() - 2];
                prop_assert!(
                    !body.windows(2).any(|w| w == b"\r\n"),
                    "EHLO must not contain internal CRLF"
                );
                // Total length ≤ 512 (RFC 5321 Section 4.5.3.1.4)
                prop_assert!(
                    bytes.len() <= 512,
                    "EHLO line must be ≤ 512 octets, got {}",
                    bytes.len()
                );
            }
        }

        /// Every MAIL FROM command ends with CRLF and starts with "MAIL FROM:<".
        /// RFC 5321 Section 4.1.1.2.
        #[test]
        fn mail_from_well_formed(address in arb_mailbox()) {
            let Ok(reverse_path) = ReversePath::new(&address) else { return Ok(()); };
            let mut buf = BytesMut::new();
            if matches!(encode_mail_from(&mut buf, &reverse_path, None), Ok(())) {
                let bytes = &buf[..];
                prop_assert!(
                    bytes.ends_with(b"\r\n"),
                    "MAIL FROM must end with CRLF"
                );
                prop_assert!(
                    bytes.starts_with(b"MAIL FROM:<"),
                    "MAIL FROM must start with 'MAIL FROM:<'"
                );
                let body = &bytes[..bytes.len() - 2];
                prop_assert!(
                    !body.windows(2).any(|w| w == b"\r\n"),
                    "MAIL FROM must not contain internal CRLF"
                );
            }
        }

        /// MAIL FROM with null reverse-path produces "MAIL FROM:<>".
        /// RFC 5321 Section 4.1.1.2.
        #[test]
        fn mail_from_null_path_well_formed(_dummy in Just(())) {
            let mut buf = BytesMut::new();
            encode_mail_from(&mut buf, &rp(""), None).unwrap();
            prop_assert_eq!(&buf[..], b"MAIL FROM:<>\r\n");
        }

        /// Every RCPT TO command ends with CRLF and starts with "RCPT TO:<".
        /// RFC 5321 Section 4.1.1.3.
        #[test]
        fn rcpt_to_well_formed(address in arb_mailbox()) {
            let Ok(forward_path) = ForwardPath::new(&address) else { return Ok(()); };
            let mut buf = BytesMut::new();
            if matches!(encode_rcpt_to(&mut buf, &forward_path), Ok(())) {
                let bytes = &buf[..];
                prop_assert!(
                    bytes.ends_with(b"\r\n"),
                    "RCPT TO must end with CRLF"
                );
                prop_assert!(
                    bytes.starts_with(b"RCPT TO:<"),
                    "RCPT TO must start with 'RCPT TO:<'"
                );
                // Address should appear between < and >
                let line = std::str::from_utf8(bytes).unwrap();
                prop_assert!(
                    line.contains(&format!("<{address}>")),
                    "RCPT TO must contain the address in angle brackets"
                );
            }
        }

        /// Every VRFY command ends with CRLF and starts with "VRFY ".
        /// RFC 5321 Section 4.1.1.6.
        #[test]
        fn vrfy_well_formed(query in arb_query_string()) {
            let mut buf = BytesMut::new();
            if matches!(encode_vrfy(&mut buf, &query), Ok(())) {
                let bytes = &buf[..];
                prop_assert!(
                    bytes.ends_with(b"\r\n"),
                    "VRFY must end with CRLF"
                );
                prop_assert!(
                    bytes.starts_with(b"VRFY "),
                    "VRFY must start with 'VRFY '"
                );
                prop_assert!(
                    bytes.len() <= 512,
                    "VRFY line must be ≤ 512 octets"
                );
            }
        }

        /// Every EXPN command ends with CRLF and starts with "EXPN ".
        /// RFC 5321 Section 4.1.1.7.
        #[test]
        fn expn_well_formed(query in arb_query_string()) {
            let mut buf = BytesMut::new();
            if matches!(encode_expn(&mut buf, &query), Ok(())) {
                let bytes = &buf[..];
                prop_assert!(
                    bytes.ends_with(b"\r\n"),
                    "EXPN must end with CRLF"
                );
                prop_assert!(
                    bytes.starts_with(b"EXPN "),
                    "EXPN must start with 'EXPN '"
                );
                prop_assert!(
                    bytes.len() <= 512,
                    "EXPN line must be ≤ 512 octets"
                );
            }
        }

        /// MAIL FROM with all extension parameters produces well-formed output.
        /// RFC 5321 Section 4.1.1.2, RFC 1870, RFC 3461, RFC 6531.
        #[test]
        fn mail_from_full_well_formed(
            address in arb_mailbox(),
            size in proptest::option::of(0u64..1_000_000),
            body in proptest::option::of(prop_oneof![
                Just(BodyType::SevenBit),
                Just(BodyType::EightBitMime),
                Just(BodyType::BinaryMime),
            ]),
            ret in proptest::option::of(prop_oneof![
                Just(DsnRet::Full),
                Just(DsnRet::Hdrs),
            ]),
            envid in proptest::option::of(arb_envid()),
            mt_priority in proptest::option::of(-9i8..=9),
        ) {
            let Ok(reverse_path) = ReversePath::new(&address) else { return Ok(()); };
            let envid = envid.and_then(|s| EnvidValue::new(s).ok());
            let params = MailFromParams {
                size,
                body,
                ret,
                envid,
                mt_priority,
                ..Default::default()
            };
            let mut buf = BytesMut::new();
            if matches!(encode_mail_from_full(&mut buf, &reverse_path, &params), Ok(())) {
                let bytes = &buf[..];
                prop_assert!(
                    bytes.ends_with(b"\r\n"),
                    "MAIL FROM must end with CRLF"
                );
                prop_assert!(
                    bytes.starts_with(b"MAIL FROM:<"),
                    "MAIL FROM must start with 'MAIL FROM:<'"
                );
                let body_bytes = &bytes[..bytes.len() - 2];
                prop_assert!(
                    !body_bytes.windows(2).any(|w| w == b"\r\n"),
                    "MAIL FROM must not contain internal CRLF"
                );
                // Verify SIZE parameter appears if set
                if let Some(s) = size {
                    let line = std::str::from_utf8(bytes).unwrap();
                    prop_assert!(
                        line.contains(&format!("SIZE={s}")),
                        "SIZE parameter must appear in output"
                    );
                }
            }
        }

        /// RCPT TO with DSN parameters produces well-formed output.
        /// RFC 3461 Section 4.1-4.2.
        #[test]
        fn rcpt_to_full_well_formed(
            address in arb_mailbox(),
            notify in proptest::option::of(prop::collection::vec(
                prop_oneof![
                    Just(DsnNotify::Success),
                    Just(DsnNotify::Failure),
                    Just(DsnNotify::Delay),
                ],
                1..=3
            )),
            orcpt in proptest::option::of(arb_mailbox()),
        ) {
            let Ok(forward_path) = ForwardPath::new(&address) else { return Ok(()); };
            let params = RcptToParams {
                notify,
                orcpt,
            };
            let mut buf = BytesMut::new();
            if matches!(encode_rcpt_to_full(&mut buf, &forward_path, &params), Ok(())) {
                let bytes = &buf[..];
                prop_assert!(
                    bytes.ends_with(b"\r\n"),
                    "RCPT TO must end with CRLF"
                );
                prop_assert!(
                    bytes.starts_with(b"RCPT TO:<"),
                    "RCPT TO must start with 'RCPT TO:<'"
                );
            }
        }

        /// HELO accepts only plain domains (no address literals).
        /// RFC 5321 Section 4.1.1.1.
        #[test]
        fn helo_well_formed(domain in arb_domain()) {
            let Ok(dol) = DomainOrLiteral::new(&domain) else { return Ok(()); };
            let mut buf = BytesMut::new();
            if matches!(encode_helo(&mut buf, &dol), Ok(())) {
                let bytes = &buf[..];
                prop_assert!(
                    bytes.starts_with(b"HELO "),
                    "HELO must start with 'HELO '"
                );
                prop_assert!(
                    bytes.ends_with(b"\r\n"),
                    "HELO must end with CRLF"
                );
            }
        }

        /// LHLO is well-formed (RFC 2033 Section 4.2).
        #[test]
        fn lhlo_well_formed(domain in arb_domain()) {
            let Ok(dol) = DomainOrLiteral::new(&domain) else { return Ok(()); };
            let mut buf = BytesMut::new();
            if matches!(encode_lhlo(&mut buf, &dol), Ok(())) {
                let bytes = &buf[..];
                prop_assert!(
                    bytes.starts_with(b"LHLO "),
                    "LHLO must start with 'LHLO '"
                );
                prop_assert!(
                    bytes.ends_with(b"\r\n"),
                    "LHLO must end with CRLF"
                );
            }
        }
    }
}