autumn-web 0.6.0

An opinionated, convention-over-configuration web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
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
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
//! Transactional email support.
//!
//! The public surface is intentionally small: build a [`Mail`] value, send it
//! through the cloneable [`Mailer`] extractor, and swap transports through the
//! [`MailTransport`] trait when SMTP is not the right coffin lining.

// autumn-panic-gate: request-path module — production code path must be panic-free.
// See CONTRIBUTING.md "Request-path panic gate". Justify exceptions with
// #[allow(clippy::<lint>, reason = "…")] at the narrowest scope.
#![cfg_attr(
    not(test),
    deny(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        clippy::unreachable,
        clippy::todo,
        clippy::unimplemented,
        clippy::indexing_slicing,
    )
)]

use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use axum::extract::FromRequestParts;
use axum::response::{Html, IntoResponse, Response};
use lettre::message::header::{ContentTransferEncoding, ContentType};
use lettre::message::{
    Attachment as LettreAttachment, Body as LettreBody, Mailbox, MultiPart, SinglePart,
};
use lettre::transport::smtp::authentication::Credentials;
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{AppState, AutumnError, AutumnResult};

/// Mail transport selected by `[mail].transport`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Transport {
    /// Write full email contents to the tracing log at INFO.
    Log,
    /// Write RFC 822 `.eml` files under `target/mail` or a configured dir.
    File,
    /// Send through SMTP using Lettre.
    Smtp,
    /// Drop all email sends successfully.
    #[default]
    Disabled,
}

impl Transport {
    pub(crate) fn from_env_value(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "log" => Some(Self::Log),
            "file" => Some(Self::File),
            "smtp" => Some(Self::Smtp),
            "disabled" => Some(Self::Disabled),
            _ => None,
        }
    }
}

/// SMTP TLS mode.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TlsMode {
    /// Plain connection; useful only for local test SMTP sinks.
    Disabled,
    /// Upgrade with STARTTLS.
    #[default]
    StartTls,
    /// Connect with wrapper TLS.
    Tls,
}

impl TlsMode {
    pub(crate) fn from_env_value(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "disabled" => Some(Self::Disabled),
            "starttls" | "start_tls" => Some(Self::StartTls),
            "tls" => Some(Self::Tls),
            _ => None,
        }
    }
}

/// SMTP configuration nested under `[mail.smtp]`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct SmtpConfig {
    /// SMTP host name.
    #[serde(default)]
    pub host: Option<String>,
    /// SMTP port. Defaults to 587 for STARTTLS, 465 for TLS, and 25 for disabled TLS.
    #[serde(default)]
    pub port: Option<u16>,
    /// Optional SMTP username.
    #[serde(default)]
    pub username: Option<String>,
    /// Environment variable containing the SMTP password.
    #[serde(default)]
    pub password_env: Option<String>,
    /// TLS behavior.
    #[serde(default)]
    pub tls: TlsMode,
}

impl Default for SmtpConfig {
    fn default() -> Self {
        Self {
            host: None,
            port: None,
            username: None,
            password_env: None,
            tls: TlsMode::StartTls,
        }
    }
}

/// `[mail]` config section.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[allow(clippy::struct_excessive_bools)] // independent transport/prod/unsubscribe toggles
pub struct MailConfig {
    /// Active transport.
    #[serde(default)]
    pub transport: Transport,
    /// Default From header.
    #[serde(default)]
    pub from: Option<String>,
    /// Default Reply-To header.
    #[serde(default)]
    pub reply_to: Option<String>,
    /// Permit log transport in `prod`.
    #[serde(default)]
    pub allow_log_in_production: bool,
    /// Acknowledge that `deliver_later` may use the in-process Tokio fallback in
    /// `prod`. Without a registered durable [`MailDeliveryQueue`], this is the
    /// only way to start the app in `prod` with an active mail transport.
    #[serde(default)]
    pub allow_in_process_deliver_later_in_production: bool,
    /// Directory for file transport.
    #[serde(default = "default_file_dir")]
    pub file_dir: PathBuf,
    /// Force-enable the dev mail preview UI.
    ///
    /// The UI is auto-enabled in `dev` when `mail.transport = "file"`.
    /// Setting this flag outside `dev` is rejected at startup.
    #[serde(default)]
    pub preview: bool,
    /// Base URL for RFC 8058 one-click `List-Unsubscribe` links, e.g.
    /// `https://app.example.com`. Required (alongside or instead of
    /// [`unsubscribe_mailto`](Self::unsubscribe_mailto)) for any `#[mailer]`
    /// that declares `list_unsubscribe`.
    #[serde(default)]
    pub unsubscribe_base_url: Option<String>,
    /// `mailto:` fallback address for the `List-Unsubscribe` header, e.g.
    /// `unsubscribe@example.com`.
    #[serde(default)]
    pub unsubscribe_mailto: Option<String>,
    /// Validity window for signed unsubscribe tokens, in days.
    #[serde(default = "default_unsubscribe_ttl_days")]
    pub unsubscribe_token_ttl_days: i64,
    /// Opt in to mounting the framework's default one-click unsubscribe endpoint
    /// (`GET`/`POST /_autumn/unsubscribe`). Off by default so JSON-only apps
    /// never get an HTML endpoint they didn't ask for; also settable via
    /// [`AppBuilder::mount_unsubscribe_endpoint`](crate::app::AppBuilder::mount_unsubscribe_endpoint).
    #[serde(default)]
    pub mount_unsubscribe_endpoint: bool,
    /// Default for CSS inlining of HTML mail bodies (issue #1254).
    ///
    /// When `true`, every HTML body sent through a [`Mailer`] built from this
    /// config has its `<style>` rules inlined onto matching elements as
    /// `style="…"` attributes at send time, so it renders styled in clients
    /// that strip `<head>`/`<style>` (Gmail, Outlook). Off by default —
    /// existing apps are unaffected until they opt in. A per-message
    /// [`MailBuilder::inline_css`] call overrides this default in either
    /// direction (explicit builder value wins).
    #[serde(default)]
    pub inline_css: bool,
    /// SMTP settings.
    #[serde(default)]
    pub smtp: SmtpConfig,
}

/// Whether `url` is an absolute `https://` URL with a non-empty host and no
/// query/fragment, e.g. `https://app.example.com` or `…/base`. Rejects bare
/// `https://`, `https:///path`, and bases carrying `?`/`#` (the unsubscribe
/// path/token is appended afterwards, so a query/fragment base would not route).
fn is_valid_https_base_url(url: &str) -> bool {
    // Reject characters that are unsafe inside an RFC 2369 angle-bracket URI or
    // would survive into the raw header: `Url::parse` percent-encodes a space or
    // `<`/`>` in the path, but the *original* string is what gets rendered as
    // `<…?token=…>`, so a raw `<`/`>`/whitespace/control char would close or
    // corrupt the `List-Unsubscribe` value.
    if url
        .chars()
        .any(|c| c.is_control() || c.is_whitespace() || matches!(c, '<' | '>'))
    {
        return false;
    }
    // Require the raw input to be literally `https://<authority>…`. `url::Url`
    // normalizes a missing/short authority (`https:`, `https:app.example.com`,
    // `https:/app.example.com`, `https:///path`) into a valid HTTPS URL with a
    // host, but the *original* malformed string is what gets rendered into the
    // header — so reject anything that isn't `https://` followed by a non-`/`
    // authority character.
    match url.strip_prefix("https://") {
        Some(rest) if !rest.is_empty() && !rest.starts_with('/') => {}
        _ => return false,
    }
    let Ok(parsed) = ::url::Url::parse(url) else {
        return false;
    };
    // Require an absolute https:// URL with a real host and a valid authority.
    // Parsing (rather than splitting on `/`) rejects malformed authorities like
    // `https://app.example.com:abc` (bad port) or `https://@/base` (empty host).
    // No credentials in the link, and no query/fragment — either would break the
    // appended `?token=…`.
    parsed.scheme() == "https"
        && parsed.host_str().is_some_and(|h| !h.is_empty())
        && parsed.username().is_empty()
        && parsed.password().is_none()
        && parsed.query().is_none()
        && parsed.fragment().is_none()
}

/// Whether `value` is a usable unsubscribe mailbox — a bare `local@domain` or a
/// `mailto:local@domain` URI, with non-empty parts and no whitespace.
fn is_valid_mailto_address(value: &str) -> bool {
    // Reject control characters and RFC 2369 delimiters anywhere in the value
    // (including inside a `?subject=…` query): the value is rendered verbatim
    // inside `<mailto:…>`, so a control char (CRLF injection, e.g. an extra
    // `Bcc:`) or a `<`/`>`/`,` (which would close the entry and inject an extra
    // `List-Unsubscribe` target) must not pass.
    if value
        .chars()
        .any(|c| c.is_control() || matches!(c, '<' | '>' | ','))
    {
        return false;
    }
    let address = value
        .trim()
        .strip_prefix("mailto:")
        .unwrap_or_else(|| value.trim());
    // Drop any `?subject=…` parameters before validating the address itself.
    let address = address.split('?').next().unwrap_or("");
    match address.split_once('@') {
        Some((local, domain)) => {
            !local.is_empty()
                && !domain.is_empty()
                && domain.contains('.')
                && !address.contains(char::is_whitespace)
                // Reject any other URI scheme (e.g. `https://unsub@example.com`):
                // `:` / `/` here mean the value is not a bare mailbox, and it
                // would otherwise render as a bogus `<mailto:https://…>` header.
                && !address.contains([':', '/'])
        }
        None => false,
    }
}

const fn default_unsubscribe_ttl_days() -> i64 {
    crate::mail::unsubscribe::DEFAULT_TOKEN_TTL_DAYS
}

impl Default for MailConfig {
    fn default() -> Self {
        Self {
            transport: Transport::Disabled,
            from: None,
            reply_to: None,
            allow_log_in_production: false,
            allow_in_process_deliver_later_in_production: false,
            file_dir: default_file_dir(),
            preview: false,
            unsubscribe_base_url: None,
            unsubscribe_mailto: None,
            unsubscribe_token_ttl_days: default_unsubscribe_ttl_days(),
            mount_unsubscribe_endpoint: false,
            inline_css: false,
            smtp: SmtpConfig::default(),
        }
    }
}

impl MailConfig {
    /// Validate semantic mail configuration.
    ///
    /// # Errors
    ///
    /// Returns [`crate::config::ConfigError::Validation`] for unsafe profile
    /// combinations or missing SMTP settings.
    pub fn validate(&self, profile: Option<&str>) -> Result<(), crate::config::ConfigError> {
        if matches!(profile, Some("prod" | "production"))
            && self.transport == Transport::Log
            && !self.allow_log_in_production
        {
            return Err(crate::config::ConfigError::Validation(
                "mail.transport = \"log\" is disabled in prod; set mail.allow_log_in_production = true to acknowledge this explicitly".to_owned(),
            ));
        }

        if self.transport == Transport::Smtp
            && self.smtp.host.as_deref().map_or("", str::trim).is_empty()
        {
            return Err(crate::config::ConfigError::Validation(
                "mail.smtp.host is required when mail.transport = \"smtp\"".to_owned(),
            ));
        }

        if self.preview && !matches!(profile, Some("dev" | "development")) {
            return Err(crate::config::ConfigError::Validation(
                "mail.preview = true is only allowed in dev; refusing to mount /_autumn/mail outside the dev profile".to_owned(),
            ));
        }

        if self.unsubscribe_token_ttl_days <= 0 {
            return Err(crate::config::ConfigError::Validation(
                "mail.unsubscribe_token_ttl_days must be a positive number of days; a non-positive value would make every unsubscribe token immediately expired".to_owned(),
            ));
        }

        if matches!(profile, Some("prod" | "production"))
            && let Some(base) = self.unsubscribe_base_url.as_deref().map(str::trim)
            && !base.is_empty()
            && !is_valid_https_base_url(base)
        {
            return Err(crate::config::ConfigError::Validation(
                "mail.unsubscribe_base_url must be an absolute https:// URL with a host in prod; mailbox providers require HTTPS for RFC 8058 one-click unsubscribe".to_owned(),
            ));
        }

        if matches!(profile, Some("prod" | "production"))
            && let Some(mailto) = self.unsubscribe_mailto.as_deref().map(str::trim)
            && !mailto.is_empty()
            && !is_valid_mailto_address(mailto)
        {
            return Err(crate::config::ConfigError::Validation(
                "mail.unsubscribe_mailto must be a bare mailbox address (or mailto: URI) like unsubscribe@example.com".to_owned(),
            ));
        }

        Ok(())
    }

    pub(crate) fn preview_routes_enabled(&self, profile: Option<&str>) -> bool {
        matches!(profile, Some("dev" | "development"))
            && (self.preview || self.transport == Transport::File)
    }

    /// Whether a base URL is configured. A `mailto`-only configuration emits a
    /// `List-Unsubscribe: <mailto:…>` header but needs no HTTP endpoint.
    pub(crate) fn unsubscribe_base_url_set(&self) -> bool {
        self.unsubscribe_base_url
            .as_deref()
            .is_some_and(|s| !s.trim().is_empty())
    }

    /// Whether the framework's default one-click unsubscribe endpoint should be
    /// mounted: the app opted in **and** a base URL is configured. Opt-in keeps
    /// JSON-only apps free of an HTML endpoint they never requested.
    pub(crate) fn should_mount_unsubscribe_endpoint(&self) -> bool {
        self.mount_unsubscribe_endpoint && self.unsubscribe_base_url_set()
    }
}

fn default_file_dir() -> PathBuf {
    PathBuf::from("target/mail")
}

/// Renderable mail body input.
pub trait IntoMailBody {
    /// Convert into owned body text.
    fn into_mail_body(self) -> String;
}

impl IntoMailBody for String {
    fn into_mail_body(self) -> String {
        self
    }
}

impl IntoMailBody for &str {
    fn into_mail_body(self) -> String {
        self.to_owned()
    }
}

impl IntoMailBody for maud::Markup {
    fn into_mail_body(self) -> String {
        self.into_string()
    }
}

/// Placeholder token in shared mailer layouts marking where the per-mailer body
/// fragment is inserted.
///
/// Layouts that do not contain this marker are ignored and the raw body is
/// delivered instead (prevents silent content loss).
pub const MAIL_LAYOUT_CONTENT_MARKER: &str = "{{ content }}";

/// Compose a `layout` string and a `body` fragment by replacing
/// [`MAIL_LAYOUT_CONTENT_MARKER`] with `body`.
///
/// If the layout does not contain the marker, `body` is returned unchanged so
/// content is never silently dropped.
#[must_use]
pub fn compose_layout(layout: &str, body: &str) -> String {
    if layout.contains(MAIL_LAYOUT_CONTENT_MARKER) {
        layout.replace(MAIL_LAYOUT_CONTENT_MARKER, body)
    } else {
        body.to_owned()
    }
}

/// Whether `html` contains a `<style` tag (case-insensitive), i.e. there is any
/// embedded stylesheet worth inlining. Allocation-free ASCII scan — the fast
/// path for the common case of plain-text or already-inlined bodies.
fn html_contains_style_block(html: &str) -> bool {
    html.as_bytes()
        .windows(6)
        .any(|window| window.eq_ignore_ascii_case(b"<style"))
}

/// Whether `html` looks like a full HTML *document* — it carries a `<!doctype`,
/// `<html`, or `<body` marker — rather than a bare fragment. Autumn permits raw
/// fragment bodies when no layout wraps them, so [`inline_css_html`] uses this to
/// decide whether to strip the synthetic document wrappers `css-inline` adds. A
/// user-authored `<body>` is therefore recognized as a document and its
/// structure is left untouched. Allocation-free case-insensitive ASCII scan.
fn html_is_full_document(html: &str) -> bool {
    let bytes = html.as_bytes();
    bytes.windows(5).any(|w| w.eq_ignore_ascii_case(b"<html"))
        || bytes.windows(5).any(|w| w.eq_ignore_ascii_case(b"<body"))
        || bytes
            .windows(9)
            .any(|w| w.eq_ignore_ascii_case(b"<!doctype"))
}

/// Strip the synthetic `<html>`/`<head>`/`<body>` wrappers that `css-inline`'s
/// document mode adds around fragment input, reconstructing the fragment.
///
/// [`inline_css_html`] always inlines in document mode because `css-inline`'s
/// fragment mode drops retained `@media`/at-rules (it re-homes them to `<head>`,
/// which a fragment lacks). Document mode instead wraps a fragment body in
/// synthetic structural tags. This is only ever called on output we produced by
/// document-inlining a body we already determined was a *fragment*, so those
/// wrappers are always `css-inline`'s own, never user-authored.
///
/// `css-inline` (via `html5ever`) serializes a document as a canonical,
/// attribute-free `<html><head>…</head><body>…</body></html>`, so exact-literal
/// matching is safe. The result is the `<head>` contents (the retained `<style>`
/// block carrying un-inlinable `@media`/pseudo rules, per AC5) followed by the
/// `<body>` contents — preserving the original fragment ordering of `<style>`
/// before body content. If the expected shape is absent, the input is returned
/// unchanged rather than risking corruption.
fn unwrap_synthetic_document(doc: &str) -> String {
    // html5ever emits these exact byte sequences, lowercased and without
    // attributes or whitespace, for the wrappers it synthesizes.
    let inner = doc
        .strip_prefix("<html>")
        .and_then(|rest| rest.strip_suffix("</html>"))
        .unwrap_or(doc);
    let (head, after_head) = match inner.strip_prefix("<head>") {
        Some(rest) => match rest.split_once("</head>") {
            Some(split) => split,
            // Malformed/unexpected shape: don't risk corrupting the body.
            None => return doc.to_owned(),
        },
        None => ("", inner),
    };
    let body = after_head
        .strip_prefix("<body>")
        .map_or(after_head, |rest| {
            rest.strip_suffix("</body>").unwrap_or(rest)
        });
    format!("{head}{body}")
}

/// Inline the `<style>` rules of an HTML mail body onto matching elements as
/// `style="…"` attributes, so the message renders styled in clients that strip
/// `<head>`/`<style>` (Gmail, Outlook). See issue #1254.
///
/// Behavior:
/// - Bodies with no `<style>` block are returned unchanged (fast path), so
///   plain-text and already-fully-inlined bodies pass through byte-for-byte.
/// - `<style>` blocks are retained, but rules that were successfully inlined are
///   stripped from them — so what remains is exactly the un-inlinable
///   `@media`/pseudo-class rules, which still reach clients that honor them.
///   Because the inlinable rules are removed from the retained block, running
///   this again is a no-op: inlining is idempotent.
/// - Remote/`<link>` stylesheets are never fetched (the `css-inline` network
///   feature is not compiled in) — only embedded `<style>` CSS is inlined. The
///   `<link rel="stylesheet">` tags themselves are preserved in the body so the
///   linked CSS still reaches clients rather than being silently dropped.
/// - A raw *fragment* body (no `<html>`/`<body>`/doctype) stays a fragment.
///   `css-inline`'s document mode wraps fragment output in synthetic
///   `<html>`/`<head>`/`<body>` tags; those wrappers are stripped back off (see
///   [`unwrap_synthetic_document`]) so opting into inlining never promotes a
///   fragment MIME body into a full document. Full-document bodies keep their
///   structure unchanged.
///
/// # Errors
///
/// Returns [`MailError::CssInline`] if the body cannot be parsed/inlined, rather
/// than returning a silently corrupted body.
fn inline_css_html(html: &str) -> Result<String, MailError> {
    // Fast path: nothing to inline. Keeps text-like, fragment, and
    // already-inlined bodies byte-identical and makes re-inlining idempotent.
    if !html_contains_style_block(html) {
        return Ok(html.to_owned());
    }
    let inliner = css_inline::CSSInliner::options()
        // Retain `<style>` so un-inlinable rules survive…
        .keep_style_tags(true)
        // …including `@media`/other at-rules (dropped by default), so responsive
        // tweaks still work in clients that honor them.
        .keep_at_rules(true)
        // …but drop the rules we did inline, leaving only the un-inlinable ones
        // in the retained block (also what makes a second pass a no-op).
        .remove_inlined_selectors(true)
        // Never reach out to the network for `<link>`ed stylesheets.
        .load_remote_stylesheets(false)
        // …but since we do NOT fetch them, keep the `<link rel="stylesheet">`
        // tags in the body (dropped by default) so the linked CSS still reaches
        // clients rather than being silently discarded from the delivered body.
        .keep_link_tags(true)
        // Also emit the presentational HTML `width`/`height` attributes (from the
        // inlined CSS dimensions) on `table`/`td`/`th`/`img` — both default off.
        // Outlook-family clients ignore CSS `width`/`height`, so without these
        // attributes those elements lose their intended sizing there.
        .apply_width_attributes(true)
        .apply_height_attributes(true)
        .build();
    // Inline in document mode. Its fragment mode would avoid the `<html>`/`<body>`
    // wrapping but drops retained `@media`/at-rules (it re-homes them to `<head>`,
    // which a fragment lacks) — breaking AC5. So document-inline unconditionally,
    // then, for a fragment body, strip the synthetic wrappers back off so the
    // MIME body stays a fragment. Full documents keep their structure as-is.
    let is_fragment = !html_is_full_document(html);
    let rendered = inliner
        .inline(html)
        // Defensive / effectively unreachable: with remote-stylesheet loading
        // disabled above and no file loader configured, `css-inline` only errors
        // on IO/network — both compiled out here. It is fully lenient toward
        // malformed CSS/HTML (garbage `<style>` bodies inline to an unchanged
        // fragment, never an error). We still surface the typed error rather than
        // `expect`ing, to keep the API stable if those loaders are ever enabled.
        .map_err(|error| MailError::CssInline(error.to_string()))?;
    Ok(if is_fragment {
        unwrap_synthetic_document(&rendered)
    } else {
        rendered
    })
}

/// A file attached to a [`Mail`] message.
///
/// Built via [`MailBuilder::attach`]. Carries raw, undecoded bytes so it
/// round-trips byte-identical through every transport and through a durable
/// [`MailDeliveryQueue`].
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MailAttachment {
    /// Attachment filename, as presented to the recipient's mail client.
    pub filename: String,
    /// Declared MIME content type (e.g. `"application/pdf"`).
    pub content_type: String,
    /// Raw attachment bytes.
    pub bytes: Vec<u8>,
}

impl std::fmt::Debug for MailAttachment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MailAttachment")
            .field("filename", &self.filename)
            .field("content_type", &self.content_type)
            .field("bytes", &format_args!("<{} bytes>", self.bytes.len()))
            .finish()
    }
}

/// A transactional email.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Mail {
    /// Optional From header. Falls back to [`Mailer`]'s default.
    pub from: Option<String>,
    /// Optional Reply-To header. Falls back to [`Mailer`]'s default.
    pub reply_to: Option<String>,
    /// To recipients.
    pub to: Vec<String>,
    /// Subject header.
    pub subject: String,
    /// HTML body.
    pub html: Option<String>,
    /// Plain-text body.
    pub text: Option<String>,
    /// Logical list / suppression scope for RFC 8058 one-click
    /// `List-Unsubscribe` (e.g. `"weekly_digest"`). Set by the
    /// `#[mailer(list_unsubscribe = "...")]` macro. `None` for transactional
    /// mail that must never carry unsubscribe headers (password resets, MFA
    /// codes, security alerts). See [`crate::mail::unsubscribe`].
    pub list_unsubscribe: Option<String>,
    /// Additional raw headers emitted on the wire by every transport. Used to
    /// carry the computed `List-Unsubscribe` / `List-Unsubscribe-Post` headers,
    /// but available for any custom header.
    pub extra_headers: Vec<(String, String)>,
    /// Files attached to this message, in declared order.
    #[serde(default)]
    pub attachments: Vec<MailAttachment>,
    /// When `true`, [`Mailer::send`] delivers this message even to addresses on
    /// the bounce/complaint [`suppression`] list. Set via
    /// [`MailBuilder::ignore_suppression`] for genuinely critical mail
    /// (password resets, MFA codes, security alerts) that must reach the
    /// recipient regardless of prior delivery failures. `false` by default.
    #[serde(default)]
    pub ignore_suppression: bool,
    /// Per-message override for CSS inlining (issue #1254).
    ///
    /// `Some(true)`/`Some(false)` force inlining on/off for this message,
    /// overriding the [`Mailer`]'s configured default; `None` (the default)
    /// defers to [`MailConfig::inline_css`]. Set via
    /// [`MailBuilder::inline_css`]. On the deferred/durable path a `None` is
    /// frozen to the originating mailer's default before the message is
    /// persisted to a [`MailDeliveryQueue`], so the enqueued job is
    /// self-describing and deferred mail inlines consistently with an immediate
    /// send even when a different worker consumes the queue.
    #[serde(default)]
    pub inline_css: Option<bool>,
}

/// Stable root path for the dev mail preview UI.
pub const MAIL_PREVIEW_PATH: &str = "/_autumn/mail";

const MAIL_PREVIEW_MESSAGE_PATH: &str = "/_autumn/mail/messages/{message_id}";
const MAIL_PREVIEW_TEMPLATE_PATH: &str = "/_autumn/mail/previews/{mailer}/{method}";

/// A developer-authored, zero-argument mail template preview.
#[derive(Clone)]
pub struct MailPreview {
    mailer: &'static str,
    method: &'static str,
    render: fn() -> Mail,
}

impl std::fmt::Debug for MailPreview {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MailPreview")
            .field("mailer", &self.mailer)
            .field("method", &self.method)
            .finish_non_exhaustive()
    }
}

impl MailPreview {
    /// Register a mail preview for the dev mail preview UI.
    #[must_use]
    pub const fn new(mailer: &'static str, method: &'static str, render: fn() -> Mail) -> Self {
        Self {
            mailer,
            method,
            render,
        }
    }

    /// Mailer type label used in preview URLs.
    #[must_use]
    pub const fn mailer(&self) -> &'static str {
        self.mailer
    }

    /// Preview method label used in preview URLs.
    #[must_use]
    pub const fn method(&self) -> &'static str {
        self.method
    }

    /// Render the preview without invoking any configured transport.
    ///
    /// # Errors
    ///
    /// Returns [`MailPreviewError::PreviewPanicked`] if the preview function
    /// panics while constructing sample data.
    pub fn render(&self) -> Result<Mail, MailPreviewError> {
        std::panic::catch_unwind(|| (self.render)()).map_err(|_| {
            MailPreviewError::PreviewPanicked {
                mailer: self.mailer,
                method: self.method,
            }
        })
    }
}

/// Collection of registered mail previews stored on [`AppState`].
#[derive(Debug, Clone, Default)]
pub struct MailPreviewRegistry {
    previews: Arc<Vec<MailPreview>>,
}

impl MailPreviewRegistry {
    /// Create a registry from preview registrations.
    #[must_use]
    pub fn new(previews: Vec<MailPreview>) -> Self {
        Self {
            previews: Arc::new(previews),
        }
    }

    /// Registered previews.
    #[must_use]
    pub fn previews(&self) -> &[MailPreview] {
        &self.previews
    }

    fn find(&self, mailer: &str, method: &str) -> Option<MailPreview> {
        self.previews
            .iter()
            .find(|preview| preview.mailer == mailer && preview.method == method)
            .cloned()
    }
}

/// Dev mail preview UI errors.
#[derive(Debug, Error)]
pub enum MailPreviewError {
    /// File transport preview IO failed.
    #[error("mail preview file IO failed: {0}")]
    Io(#[from] std::io::Error),
    /// Requested captured message was not found.
    #[error("captured mail message not found: {0}")]
    NotFound(String),
    /// Requested message id is not a single `.eml` filename.
    #[error("invalid captured mail message id: {0}")]
    InvalidMessageId(String),
    /// Developer-authored preview panicked while rendering sample data.
    #[error("mail preview {mailer}::{method} panicked while rendering")]
    PreviewPanicked {
        /// Mailer label.
        mailer: &'static str,
        /// Method label.
        method: &'static str,
    },
}

impl Mail {
    /// Start building a mail message.
    #[must_use]
    pub fn builder() -> MailBuilder {
        MailBuilder::default()
    }

    fn with_defaults(mut self, defaults: &MailerDefaults) -> Self {
        if self.from.is_none() {
            self.from.clone_from(&defaults.from);
        }
        if self.reply_to.is_none() {
            self.reply_to.clone_from(&defaults.reply_to);
        }
        self
    }
}

/// Builder for [`Mail`].
#[derive(Debug, Clone, Default)]
pub struct MailBuilder {
    from: Option<String>,
    reply_to: Option<String>,
    to: Vec<String>,
    subject: Option<String>,
    html: Option<String>,
    text: Option<String>,
    html_layout: Option<String>,
    text_layout: Option<String>,
    list_unsubscribe: Option<String>,
    extra_headers: Vec<(String, String)>,
    attachments: Vec<MailAttachment>,
    ignore_suppression: bool,
    inline_css: Option<bool>,
}

impl MailBuilder {
    /// Set a message-specific From header.
    #[must_use]
    pub fn from(mut self, from: impl Into<String>) -> Self {
        self.from = Some(from.into());
        self
    }

    /// Set a message-specific Reply-To header.
    #[must_use]
    pub fn reply_to(mut self, reply_to: impl Into<String>) -> Self {
        self.reply_to = Some(reply_to.into());
        self
    }

    /// Add a To recipient.
    #[must_use]
    pub fn to(mut self, to: impl Into<String>) -> Self {
        self.to.push(to.into());
        self
    }

    /// Set the subject.
    #[must_use]
    pub fn subject(mut self, subject: impl Into<String>) -> Self {
        self.subject = Some(subject.into());
        self
    }

    /// Set the HTML body.
    #[must_use]
    pub fn html(mut self, html: impl IntoMailBody) -> Self {
        self.html = Some(html.into_mail_body());
        self
    }

    /// Set the plain-text body.
    #[must_use]
    pub fn text(mut self, text: impl IntoMailBody) -> Self {
        self.text = Some(text.into_mail_body());
        self
    }

    /// Tag this message with a logical list / suppression scope, opting it into
    /// RFC 8058 one-click `List-Unsubscribe` handling at send time.
    ///
    /// Authors normally set this declaratively via
    /// `#[mailer(list_unsubscribe = "...")]`; this builder method exists for
    /// hand-rolled mail and previews.
    #[must_use]
    pub fn list_unsubscribe(mut self, scope: impl Into<String>) -> Self {
        self.list_unsubscribe = Some(scope.into());
        self
    }

    /// Bypass the bounce/complaint [`suppression`] list for this message.
    ///
    /// [`Mailer::send`] normally skips recipients that have hard-bounced or
    /// filed a spam complaint. Call this for genuinely critical mail —
    /// password resets, MFA codes, security alerts — that must be delivered
    /// even to a suppressed address. Use sparingly: repeatedly sending to a
    /// hard-bounced address is exactly what damages sender reputation.
    #[must_use]
    pub const fn ignore_suppression(mut self) -> Self {
        self.ignore_suppression = true;
        self
    }

    /// Force CSS inlining on or off for this message, overriding the
    /// [`Mailer`]'s configured [`MailConfig::inline_css`] default.
    ///
    /// When enabled, the HTML body's `<style>` rules are inlined onto matching
    /// elements as `style="…"` attributes at send time so the message renders
    /// styled in clients that strip `<head>`/`<style>` (Gmail, Outlook).
    /// Un-inlinable `@media`/pseudo-class rules are preserved in a retained
    /// `<style>` block. Text bodies and HTML with no `<style>` block are left
    /// untouched.
    ///
    /// Precedence: an explicit call here always wins over the config default —
    /// `inline_css(false)` opts a single message out even when the environment
    /// defaults inlining on, and `inline_css(true)` opts a single message in
    /// when the default is off.
    #[must_use]
    pub const fn inline_css(mut self, enabled: bool) -> Self {
        self.inline_css = Some(enabled);
        self
    }

    /// Add a raw header emitted by every transport.
    #[must_use]
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra_headers.push((name.into(), value.into()));
        self
    }

    /// Attach a file. Calling this repeatedly appends attachments in the
    /// order they were declared; the SMTP and file transports both encode
    /// them as `multipart/mixed` parts with a `base64`
    /// `Content-Transfer-Encoding`.
    ///
    /// ```rust,ignore
    /// let mail = Mail::builder()
    ///     .to("ada@example.com")
    ///     .subject("Your invoice")
    ///     .text("Your invoice is attached.")
    ///     .attach("invoice.pdf", "application/pdf", pdf_bytes)
    ///     .build()?;
    /// ```
    #[must_use]
    pub fn attach(
        mut self,
        filename: impl Into<String>,
        content_type: impl Into<String>,
        bytes: impl Into<Vec<u8>>,
    ) -> Self {
        self.attachments.push(MailAttachment {
            filename: filename.into(),
            content_type: content_type.into(),
            bytes: bytes.into(),
        });
        self
    }

    /// Wrap the HTML and text bodies in a shared layout.
    ///
    /// The layout strings must contain [`MAIL_LAYOUT_CONTENT_MARKER`]
    /// (`{{ content }}`) where the per-mailer body fragment should be inserted.
    /// If a layout does not contain the marker the raw body is delivered
    /// unchanged (content is never silently dropped).
    ///
    /// Call this method with the shared `_layout.html` and `_layout.txt`
    /// templates. Omitting the call delivers the raw body — use that as the
    /// per-mailer opt-out for fully-custom or one-line plaintext messages.
    #[must_use]
    pub fn layout(
        mut self,
        html_layout: impl IntoMailBody,
        text_layout: impl IntoMailBody,
    ) -> Self {
        self.html_layout = Some(html_layout.into_mail_body());
        self.text_layout = Some(text_layout.into_mail_body());
        self
    }

    /// Build the mail.
    ///
    /// # Errors
    ///
    /// Returns [`MailError::InvalidMessage`] when required fields are missing.
    pub fn build(self) -> Result<Mail, MailError> {
        if self.to.is_empty() {
            return Err(MailError::InvalidMessage(
                "mail must have at least one recipient".to_owned(),
            ));
        }
        let subject = self
            .subject
            .filter(|s| !s.trim().is_empty())
            .ok_or_else(|| MailError::InvalidMessage("mail subject is required".to_owned()))?;
        if self.html.is_none() && self.text.is_none() {
            return Err(MailError::InvalidMessage(
                "mail must include html or text body".to_owned(),
            ));
        }
        for attachment in &self.attachments {
            if attachment.filename.trim().is_empty()
                || attachment.filename.chars().any(char::is_control)
            {
                return Err(MailError::InvalidMessage(format!(
                    "attachment filename {:?} must be non-empty and free of control characters",
                    attachment.filename
                )));
            }
            if let Err(error) = ContentType::parse(&attachment.content_type) {
                return Err(MailError::InvalidMessage(format!(
                    "attachment {:?} has invalid content type {:?}: {error}",
                    attachment.filename, attachment.content_type
                )));
            }
        }
        // A layout is only applied when the corresponding body is present.
        // If only one of html/text is set, the other layout half is intentionally
        // skipped rather than erroring — a text-only mailer may legitimately pass
        // an html_layout that has no effect, and vice-versa.
        let html = match (self.html, self.html_layout) {
            (Some(body), Some(layout)) => Some(compose_layout(&layout, &body)),
            (html, _) => html, // layout without a body: silently unused (by design)
        };
        let text = match (self.text, self.text_layout) {
            (Some(body), Some(layout)) => Some(compose_layout(&layout, &body)),
            (text, _) => text, // layout without a body: silently unused (by design)
        };
        Ok(Mail {
            from: self.from,
            reply_to: self.reply_to,
            to: self.to,
            subject,
            html,
            text,
            list_unsubscribe: self.list_unsubscribe,
            extra_headers: self.extra_headers,
            attachments: self.attachments,
            ignore_suppression: self.ignore_suppression,
            inline_css: self.inline_css,
        })
    }
}

/// Mailer errors.
#[derive(Debug, Error)]
pub enum MailError {
    /// Message could not be built or validated.
    #[error("invalid mail message: {0}")]
    InvalidMessage(String),
    /// Deferred delivery could not be scheduled.
    #[error("mail runtime unavailable: {0}")]
    RuntimeUnavailable(String),
    /// Address parsing failed.
    #[error("invalid mail address {address:?}: {source}")]
    InvalidAddress {
        /// Address that failed to parse.
        address: String,
        /// Lettre parse error.
        source: lettre::address::AddressError,
    },
    /// Lettre message construction failed.
    #[error("failed to build mail message: {0}")]
    Build(#[from] lettre::error::Error),
    /// SMTP transport failed.
    #[error("smtp send failed: {0}")]
    Smtp(#[from] lettre::transport::smtp::Error),
    /// File transport failed.
    #[error("file mail transport failed: {0}")]
    Io(#[from] std::io::Error),
    /// Every recipient of the message is on the bounce/complaint
    /// [`suppression`] list, so nothing was delivered. Distinct from success:
    /// callers can distinguish "sent" from "intentionally dropped". Bypass with
    /// [`MailBuilder::ignore_suppression`] for critical mail.
    #[error("all recipients are on the mail suppression list; nothing was sent")]
    AllRecipientsSuppressed,
    /// CSS inlining of the HTML body failed (issue #1254). `send` fails loudly
    /// with this typed error instead of delivering a corrupted body — the
    /// message is not sent, so callers can decide how to recover. Defensive:
    /// with remote and file loaders disabled, `css-inline` is fully lenient and
    /// this path is effectively unreachable, but the variant keeps the API
    /// stable if those loaders are ever enabled.
    #[error("failed to inline CSS into HTML mail body: {0}")]
    CssInline(String),
}

/// Escape hatch for custom transports.
pub trait MailTransport: Send + Sync {
    /// Send a mail message.
    fn send<'a>(
        &'a self,
        mail: Mail,
    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>>;

    /// Returns `true` if this transport is intentionally a no-op (e.g.
    /// [`Transport::Disabled`] for review apps and tests).
    ///
    /// When `true`, [`Mailer::deliver_later`] short-circuits before the queue
    /// or in-process fallback so deferred mail honors the same "drop
    /// everything" contract as immediate sends. Custom transports that mean
    /// "drop all mail" can override this to opt into the same behavior; the
    /// default of `false` preserves the existing contract for transports that
    /// merely capture mail (file, log, etc.) or send it (SMTP, custom APIs).
    fn is_disabled(&self) -> bool {
        false
    }
}

/// Durable backend for [`Mailer::deliver_later`].
///
/// Implementors persist the mail (DB row, Redis stream, Harvest job, etc.) and
/// return as soon as the handoff is durable. The framework's in-process Tokio
/// fallback is intentionally not durable; production deployments should
/// register a real implementation via [`MailDeliveryQueueHandle`] before
/// `install_mailer` runs, or set
/// [`MailConfig::allow_in_process_deliver_later_in_production`] to opt into the
/// fallback explicitly.
pub trait MailDeliveryQueue: Send + Sync {
    /// Enqueue a mail for durable later delivery.
    fn enqueue<'a>(
        &'a self,
        mail: Mail,
    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>>;
}

/// Cloneable handle to a [`MailDeliveryQueue`].
///
/// Designed for storage on [`AppState`] extensions. Plugins
/// (Harvest, custom Redis, etc.) install this before `install_mailer` runs and
/// the mailer picks it up.
#[derive(Clone)]
pub struct MailDeliveryQueueHandle(Arc<dyn MailDeliveryQueue>);

impl MailDeliveryQueueHandle {
    /// Wrap a queue implementation in a cloneable handle.
    #[must_use]
    pub fn new(queue: impl MailDeliveryQueue + 'static) -> Self {
        Self(Arc::new(queue))
    }

    /// Wrap an already-shared queue implementation.
    #[must_use]
    pub fn from_arc(queue: Arc<dyn MailDeliveryQueue>) -> Self {
        Self(queue)
    }

    /// Borrow the inner queue.
    #[must_use]
    pub fn inner(&self) -> &Arc<dyn MailDeliveryQueue> {
        &self.0
    }
}

impl std::fmt::Debug for MailDeliveryQueueHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MailDeliveryQueueHandle").finish()
    }
}

// ── RFC 8058 List-Unsubscribe ────────────────────────────────────────────────

/// Stable root path for the framework's default one-click unsubscribe endpoint.
pub const UNSUBSCRIBE_PATH: &str = "/_autumn/unsubscribe";

/// Compile-time registration of a `#[mailer(list_unsubscribe = "...")]`.
///
/// Emitted by the `#[mailer]` macro. Lets production startup and `autumn doctor`
/// enumerate which logical lists exist so they can fail closed when the app has
/// no unsubscribe destination configured.
#[derive(Debug)]
pub struct MailerListUnsubscribeDescriptor {
    /// Mailer type name (e.g. `WeeklyDigestMailer`).
    pub mailer: &'static str,
    /// Logical list / suppression scope (e.g. `weekly_digest`).
    pub scope: &'static str,
}

inventory::collect!(MailerListUnsubscribeDescriptor);

/// Every `list_unsubscribe` declaration registered across the binary.
#[must_use]
pub fn registered_list_unsubscribe_scopes() -> Vec<&'static MailerListUnsubscribeDescriptor> {
    inventory::iter::<MailerListUnsubscribeDescriptor>
        .into_iter()
        .collect()
}

/// Returns `true` when any `#[mailer]` in this binary opted into
/// `list_unsubscribe`.
#[must_use]
pub fn has_list_unsubscribe_mailers() -> bool {
    inventory::iter::<MailerListUnsubscribeDescriptor>
        .into_iter()
        .next()
        .is_some()
}

/// Whether production startup must fail closed: a `#[mailer]` declares
/// `list_unsubscribe` but the app configured no unsubscribe destination.
#[must_use]
#[allow(clippy::fn_params_excessive_bools)]
pub(crate) const fn unsubscribe_config_fail_closed(
    enforce: bool,
    in_production: bool,
    has_list_mailers: bool,
    unsubscribe_configured: bool,
) -> bool {
    enforce && in_production && has_list_mailers && !unsubscribe_configured
}

/// Encrypted, short-lived, stateless unsubscribe tokens.
///
/// A token is `base64url(version ‖ nonce ‖ AES-256-GCM(payload))`, where the
/// inner payload is `base64url(subscriber).base64url(list_id).expiry`. The cipher
/// key is derived from the app signing key (`ResolvedSigningKeys`) via HMAC-SHA256
/// with a domain-separation label. AES-256-GCM provides both confidentiality and
/// authenticity: unlike a plain signed token the recipient address is **not**
/// recoverable from the URL (so it can't leak from proxy/browser/link-scanner
/// logs), and the GCM tag makes the token tamper-proof. Verification tries the
/// current key, then any rotation-grace `previous` keys. Stateless — no
/// server-side token storage.
pub mod unsubscribe {
    use aes_gcm::aead::{Aead, KeyInit};
    use aes_gcm::{Aes256Gcm, Nonce};
    use base64::Engine as _;
    use hmac::{Hmac, Mac};
    use sha2::Sha256;

    use crate::security::config::ResolvedSigningKeys;

    /// Default validity window for unsubscribe tokens, in days.
    pub const DEFAULT_TOKEN_TTL_DAYS: i64 = 30;

    const ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE_NO_PAD;
    /// Token format version (first byte of the encrypted blob).
    const TOKEN_VERSION: u8 = 1;
    /// AES-GCM nonce length in bytes.
    const NONCE_LEN: usize = 12;
    /// Domain-separation label for deriving the token cipher key from a signing
    /// key, so it is independent of other uses of the signing secret.
    const KEY_CONTEXT: &[u8] = b"autumn:unsubscribe-token:v1";

    /// A verified unsubscribe request decoded from a signed token.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct Unsubscribed {
        /// Opaque subscriber identifier (email address by default).
        pub subscriber: String,
        /// Logical list / suppression scope.
        pub list_id: String,
    }

    /// Reasons an unsubscribe token fails to verify.
    #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
    pub enum TokenError {
        /// Structure or encoding is invalid.
        #[error("unsubscribe token is malformed")]
        Malformed,
        /// Signature did not match any current or previous signing key.
        #[error("unsubscribe token signature is invalid")]
        BadSignature,
        /// Token is past its expiry.
        #[error("unsubscribe token has expired")]
        Expired,
    }

    /// Derive a 32-byte AES-256 key from a signing key via HMAC-SHA256 with a
    /// domain-separation label.
    #[allow(
        clippy::expect_used,
        reason = "infallible: HMAC accepts any key length"
    )]
    fn derive_key(signing_key: &[u8]) -> [u8; 32] {
        let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(signing_key)
            .expect("HMAC accepts any key length");
        mac.update(KEY_CONTEXT);
        let bytes = mac.finalize().into_bytes();
        let mut key = [0u8; 32];
        key.copy_from_slice(&bytes);
        key
    }

    /// The inner authenticated plaintext: `b64(subscriber).b64(list_id).expiry`.
    fn plaintext(subscriber: &str, list_id: &str, expiry_unix: i64) -> String {
        format!(
            "{}.{}.{expiry_unix}",
            ENGINE.encode(subscriber.as_bytes()),
            ENGINE.encode(list_id.as_bytes()),
        )
    }

    /// Mint an encrypted unsubscribe token valid until `expiry_unix`.
    ///
    /// The subscriber/list/expiry (seconds since epoch) are encrypted and
    /// authenticated with AES-256-GCM, so they are not recoverable from the URL.
    ///
    /// # Panics
    ///
    /// Panics if the OS RNG is unavailable.
    #[must_use]
    #[allow(
        clippy::expect_used,
        reason = "infallible crypto: AES-256-GCM over a 32-byte derived key; an OS RNG failure is an unrecoverable environment fault surfaced as a documented panic"
    )]
    pub fn sign_token(
        keys: &ResolvedSigningKeys,
        subscriber: &str,
        list_id: &str,
        expiry_unix: i64,
    ) -> String {
        let key = derive_key(&keys.current);
        let cipher = Aes256Gcm::new_from_slice(&key).expect("derived key is always 32 bytes");
        let mut nonce_bytes = [0u8; NONCE_LEN];
        getrandom::getrandom(&mut nonce_bytes).expect("OS RNG failed");
        let ciphertext = cipher
            .encrypt(
                Nonce::from_slice(&nonce_bytes),
                plaintext(subscriber, list_id, expiry_unix).as_bytes(),
            )
            .expect("AES-GCM encryption cannot fail for valid inputs");
        let mut blob = Vec::with_capacity(1 + NONCE_LEN + ciphertext.len());
        blob.push(TOKEN_VERSION);
        blob.extend_from_slice(&nonce_bytes);
        blob.extend_from_slice(&ciphertext);
        ENGINE.encode(blob)
    }

    /// Verify a token and decode its subscriber/list, rejecting bad signatures
    /// and expired tokens.
    ///
    /// # Errors
    ///
    /// Returns [`TokenError`] when the token is malformed, its signature is
    /// invalid, or it has expired relative to `now_unix`.
    #[allow(
        clippy::indexing_slicing,
        reason = "blob.len() is checked to be >= 1 + NONCE_LEN above, so these indices are in bounds"
    )]
    pub fn verify_token(
        keys: &ResolvedSigningKeys,
        token: &str,
        now_unix: i64,
    ) -> Result<Unsubscribed, TokenError> {
        let blob = ENGINE.decode(token).map_err(|_| TokenError::Malformed)?;
        if blob.len() < 1 + NONCE_LEN {
            return Err(TokenError::Malformed);
        }
        if blob[0] != TOKEN_VERSION {
            return Err(TokenError::Malformed);
        }
        let nonce = Nonce::from_slice(&blob[1..=NONCE_LEN]);
        let ciphertext = &blob[1 + NONCE_LEN..];
        // Try the current key first, then any rotation-grace `previous` keys. A
        // wrong key (or any tampering) fails AES-GCM authentication.
        let payload = std::iter::once(&keys.current)
            .chain(keys.previous.iter())
            .find_map(|signing_key| {
                let key = derive_key(signing_key);
                // The derived key is always 32 bytes, so construction never fails;
                // `.ok()?` keeps this panic-free regardless.
                let cipher = Aes256Gcm::new_from_slice(&key).ok()?;
                cipher.decrypt(nonce, ciphertext).ok()
            })
            .ok_or(TokenError::BadSignature)?;
        let payload = String::from_utf8(payload).map_err(|_| TokenError::Malformed)?;
        let mut parts = payload.split('.');
        let subscriber_b64 = parts.next().ok_or(TokenError::Malformed)?;
        let list_b64 = parts.next().ok_or(TokenError::Malformed)?;
        let expiry_s = parts.next().ok_or(TokenError::Malformed)?;
        if parts.next().is_some() {
            return Err(TokenError::Malformed);
        }
        let expiry: i64 = expiry_s.parse().map_err(|_| TokenError::Malformed)?;
        if now_unix > expiry {
            return Err(TokenError::Expired);
        }
        let subscriber = decode_field(subscriber_b64)?;
        let list_id = decode_field(list_b64)?;
        Ok(Unsubscribed {
            subscriber,
            list_id,
        })
    }

    fn decode_field(encoded: &str) -> Result<String, TokenError> {
        let bytes = ENGINE.decode(encoded).map_err(|_| TokenError::Malformed)?;
        String::from_utf8(bytes).map_err(|_| TokenError::Malformed)
    }

    /// Build the one-click unsubscribe URL for `token` rooted at `base_url`.
    #[must_use]
    pub fn unsubscribe_url(base_url: &str, token: &str) -> String {
        format!(
            "{}{}?token={token}",
            base_url.trim_end_matches('/'),
            super::UNSUBSCRIBE_PATH,
        )
    }
}

/// Persistent record of recipients who unsubscribed from a logical list.
///
/// Implementors store one row per `(subscriber, list_id)` and answer
/// suppression queries at send time. Mirrors [`MailDeliveryQueue`]: register a
/// [`SuppressionStoreHandle`] on [`AppState`] (or let the framework auto-wire a
/// `db`-feature `DbSuppressionStore` backend) before `install_mailer` runs.
pub trait SuppressionStore: Send + Sync {
    /// Returns `true` when `subscriber` has unsubscribed from `list_id`.
    fn is_suppressed<'a>(
        &'a self,
        subscriber: &'a str,
        list_id: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<bool, MailError>> + Send + 'a>>;

    /// Record that `subscriber` unsubscribed from `list_id` (idempotent).
    fn suppress<'a>(
        &'a self,
        subscriber: &'a str,
        list_id: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>>;
}

/// Cloneable handle to a [`SuppressionStore`] for storage on [`AppState`].
#[derive(Clone)]
pub struct SuppressionStoreHandle(Arc<dyn SuppressionStore>);

impl SuppressionStoreHandle {
    /// Wrap a store implementation.
    #[must_use]
    pub fn new(store: impl SuppressionStore + 'static) -> Self {
        Self(Arc::new(store))
    }

    /// Wrap an already-shared store implementation.
    #[must_use]
    pub fn from_arc(store: Arc<dyn SuppressionStore>) -> Self {
        Self(store)
    }

    /// Borrow the inner store.
    #[must_use]
    pub fn inner(&self) -> &Arc<dyn SuppressionStore> {
        &self.0
    }
}

impl std::fmt::Debug for SuppressionStoreHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SuppressionStoreHandle").finish()
    }
}

/// In-memory [`SuppressionStore`] for tests, review apps, and single-process dev.
///
/// State is process-local and lost on restart; use `DbSuppressionStore` in
/// production.
#[derive(Debug, Default, Clone)]
pub struct InMemorySuppressionStore {
    suppressed: Arc<std::sync::Mutex<std::collections::HashSet<(String, String)>>>,
}

impl InMemorySuppressionStore {
    /// Create an empty in-memory store.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

impl SuppressionStore for InMemorySuppressionStore {
    fn is_suppressed<'a>(
        &'a self,
        subscriber: &'a str,
        list_id: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<bool, MailError>> + Send + 'a>> {
        Box::pin(async move {
            let key = (subscriber.to_owned(), list_id.to_owned());
            let suppressed = self
                .suppressed
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .contains(&key);
            Ok(suppressed)
        })
    }

    fn suppress<'a>(
        &'a self,
        subscriber: &'a str,
        list_id: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
        Box::pin(async move {
            let key = (subscriber.to_owned(), list_id.to_owned());
            self.suppressed
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .insert(key);
            Ok(())
        })
    }
}

/// Runtime wiring for List-Unsubscribe.
///
/// Holds where to point unsubscribe links, how to sign tokens, and where
/// suppression lives. Shared (via `Arc`) between the [`Mailer`] that signs
/// links and the endpoint that verifies them so tokens always validate within a
/// process.
pub struct UnsubscribeRuntime {
    /// Base URL for unsubscribe links (e.g. `https://app.example.com`).
    pub base_url: Option<String>,
    /// `mailto:` fallback address for the `List-Unsubscribe` header.
    pub mailto: Option<String>,
    /// Signing keys used for token HMACs.
    pub signing_keys: Arc<crate::security::config::ResolvedSigningKeys>,
    /// Token validity window, in days.
    pub ttl_days: i64,
    /// Suppression backend (absent in pure-header configurations).
    pub suppression: Option<Arc<dyn SuppressionStore>>,
}

impl std::fmt::Debug for UnsubscribeRuntime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UnsubscribeRuntime")
            .field("base_url", &self.base_url)
            .field("mailto", &self.mailto)
            .field("ttl_days", &self.ttl_days)
            .field("has_suppression", &self.suppression.is_some())
            .finish_non_exhaustive()
    }
}

impl UnsubscribeRuntime {
    /// Build the `List-Unsubscribe` header value for `subscriber` on `list_id`:
    /// `<https://…?token=…>, <mailto:…>` per RFC 8058 §2. Returns `None` when
    /// neither a base URL nor a mailto is configured.
    #[must_use]
    pub fn list_unsubscribe_header(&self, subscriber: &str, list_id: &str) -> Option<String> {
        let mut entries: Vec<String> = Vec::new();
        if let Some(base) = self.base_url.as_deref().filter(|s| !s.trim().is_empty()) {
            let expiry = current_unix_time().saturating_add(self.ttl_days.saturating_mul(86_400));
            let token = unsubscribe::sign_token(&self.signing_keys, subscriber, list_id, expiry);
            entries.push(format!("<{}>", unsubscribe::unsubscribe_url(base, &token)));
        }
        if let Some(mailto) = self.mailto.as_deref().filter(|s| !s.trim().is_empty()) {
            // Accept both a bare address and a full `mailto:` URI without
            // double-prefixing the scheme. Render only the bare mailbox (drop any
            // configured `?query`) before appending the canonical subject, so a
            // value like `mailto:u@x?subject=a\r\nBcc: v@x` can't inject extra
            // headers into the raw `List-Unsubscribe` value.
            let trimmed = mailto.trim();
            let address = trimmed.strip_prefix("mailto:").unwrap_or(trimmed);
            let address = address.split('?').next().unwrap_or(address);
            entries.push(format!("<mailto:{address}?subject=unsubscribe>"));
        }
        if entries.is_empty() {
            None
        } else {
            Some(entries.join(", "))
        }
    }

    /// Whether RFC 8058 one-click is available — i.e. an HTTPS unsubscribe URL is
    /// configured. `List-Unsubscribe-Post` is only valid alongside such a URL; a
    /// `mailto`-only configuration is a plain RFC 2369 unsubscribe, not one-click.
    #[must_use]
    pub fn supports_one_click(&self) -> bool {
        self.base_url
            .as_deref()
            .is_some_and(|s| !s.trim().is_empty())
    }
}

fn current_unix_time() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
}

#[derive(Debug, Clone, Default)]
struct MailerDefaults {
    from: Option<String>,
    reply_to: Option<String>,
}

/// Cloneable email sender. Extract it in handlers as `mailer: Mailer`.
#[derive(Clone)]
pub struct Mailer {
    defaults: Arc<MailerDefaults>,
    transport: Arc<dyn MailTransport>,
    delivery_queue: Option<Arc<dyn MailDeliveryQueue>>,
    unsubscribe: Option<Arc<UnsubscribeRuntime>>,
    /// Bounce/complaint suppression list consulted before transport. See
    /// [`suppression`]. `None` disables the check (suppression is opt-in on a
    /// hand-built [`Mailer`]; the framework wires a default in-memory store).
    suppression: Option<Arc<dyn suppression::SuppressionStore>>,
    /// Default for CSS inlining of HTML bodies when a message does not set its
    /// own [`Mail::inline_css`] override. Sourced from [`MailConfig::inline_css`].
    inline_css_default: bool,
}

impl Mailer {
    /// Build a mailer manually.
    #[must_use]
    pub fn builder() -> MailerBuilder {
        MailerBuilder::default()
    }

    /// Build a mailer from resolved config.
    ///
    /// # Errors
    ///
    /// Returns an error when SMTP or address configuration is invalid.
    pub fn from_config(config: &MailConfig) -> Result<Self, MailError> {
        Self::from_config_inner(config, None)
    }

    pub(crate) fn from_config_inner(
        config: &MailConfig,
        resilience: Option<Arc<crate::config::ResilienceConfig>>,
    ) -> Result<Self, MailError> {
        let mut builder = Self::builder()
            .transport(config.transport)
            .inline_css(config.inline_css)
            .resilience_config(resilience);
        if let Some(from) = &config.from {
            builder = builder.from(from.clone());
        }
        if let Some(reply_to) = &config.reply_to {
            builder = builder.reply_to(reply_to.clone());
        }
        if config.transport == Transport::File {
            builder = builder.file_dir(config.file_dir.clone());
        }
        if config.transport == Transport::Smtp {
            builder = builder.smtp(config.smtp.clone());
        }
        builder.build()
    }

    /// Build a mailer from any custom transport.
    #[must_use]
    pub fn with_transport(transport: impl MailTransport + 'static) -> Self {
        Self {
            defaults: Arc::new(MailerDefaults::default()),
            transport: Arc::new(transport),
            delivery_queue: None,
            unsubscribe: None,
            suppression: None,
            inline_css_default: false,
        }
    }

    /// Attach a durable [`MailDeliveryQueue`] used by [`Self::deliver_later`].
    #[must_use]
    pub fn with_delivery_queue(mut self, queue: impl MailDeliveryQueue + 'static) -> Self {
        self.delivery_queue = Some(Arc::new(queue));
        self
    }

    /// Attach the List-Unsubscribe runtime used to sign links, emit RFC 8058
    /// headers, and skip suppressed recipients.
    #[must_use]
    pub fn with_unsubscribe(mut self, runtime: Arc<UnsubscribeRuntime>) -> Self {
        self.unsubscribe = Some(runtime);
        self
    }

    /// Attach the bounce/complaint [`suppression`] list consulted before
    /// transport. Recipients on the list are skipped (and the skip is logged +
    /// counted) unless the message opts out via
    /// [`MailBuilder::ignore_suppression`].
    #[must_use]
    pub fn with_suppression(mut self, store: suppression::SuppressionStoreHandle) -> Self {
        self.suppression = Some(store.into_inner());
        self
    }

    /// Returns whether a durable [`MailDeliveryQueue`] is attached.
    #[must_use]
    pub fn has_durable_delivery_queue(&self) -> bool {
        self.delivery_queue.is_some()
    }

    /// Returns `true` when the active transport is intentionally a no-op
    /// (i.e. `transport = "disabled"` in `autumn.toml`).
    ///
    /// Handlers that require mail (e.g. forgot-password) can guard against
    /// silently dropped messages by checking this before attempting to send.
    #[must_use]
    pub fn is_disabled(&self) -> bool {
        self.transport.is_disabled()
    }

    /// Send mail immediately.
    ///
    /// Before transport, recipients on the bounce/complaint [`suppression`] list
    /// (hard bounce or complaint) are skipped — each skip emits a structured
    /// `outcome = "skipped_suppressed"` log line and increments
    /// [`suppression::suppressed_skips`]. When **every** recipient is suppressed,
    /// returns [`MailError::AllRecipientsSuppressed`] rather than reporting a
    /// phantom success. A message built with
    /// [`Mail::ignore_suppression`](MailBuilder::ignore_suppression) bypasses
    /// this check entirely (critical mail).
    ///
    /// When the message carries a [`list_unsubscribe`](Mail::list_unsubscribe)
    /// scope and a [`UnsubscribeRuntime`] is attached, recipients with a
    /// matching suppression row are skipped (with a structured log event) and
    /// every delivered message gains RFC 8058 `List-Unsubscribe` /
    /// `List-Unsubscribe-Post` headers scoped to the recipient. Such messages
    /// are delivered one recipient at a time so each unsubscribe link is
    /// personalized.
    ///
    /// # Errors
    ///
    /// Returns [`MailError::AllRecipientsSuppressed`] when every recipient is
    /// suppressed, an error from the selected transport, or from the suppression
    /// store when a suppression check fails.
    pub async fn send(&self, mail: Mail) -> Result<(), MailError> {
        let mut mail = mail.with_defaults(&self.defaults);

        // Inline `<style>` CSS into element `style="…"` attributes before
        // transport, so every transport (SMTP, file, log, preview) delivers the
        // inlined body and it renders styled in clients that strip
        // `<head>`/`<style>`. Doing it here — ahead of the list-mail branch that
        // clones per recipient — inlines exactly once regardless of path.
        self.apply_css_inlining(&mut mail)?;

        // Consult the bounce/complaint suppression list *before* transport.
        // Suppressed recipients are dropped from `to` (skipped, not an error)
        // unless the message opts out via `Mail::ignore_suppression`. When every
        // recipient is suppressed we return `AllRecipientsSuppressed` rather than
        // reporting a phantom success.
        if !mail.ignore_suppression
            && let Some(store) = self.suppression.as_ref()
            && !mail.to.is_empty()
        {
            let mut kept: Vec<String> = Vec::with_capacity(mail.to.len());
            for recipient in &mail.to {
                // The store canonicalizes internally, so pass the raw recipient
                // and only canonicalize on the (rare) suppressed path for the
                // log line — no allocation for delivered recipients.
                if store.is_suppressed(recipient).await? {
                    suppression::note_skip(&canonical_subscriber(recipient));
                } else {
                    kept.push(recipient.clone());
                }
            }
            if kept.is_empty() {
                return Err(MailError::AllRecipientsSuppressed);
            }
            mail.to = kept;
        }

        if let Some(list_id) = mail.list_unsubscribe.clone() {
            if let Some(runtime) = self.unsubscribe.clone() {
                return self.send_list_mail(mail, list_id, &runtime).await;
            }
            // Opted into a list (e.g. via MailBuilder::list_unsubscribe) but no
            // unsubscribe runtime is wired — send without headers/suppression,
            // but make the compliance gap loud rather than silent.
            tracing::warn!(
                target: "mail",
                list_id = %list_id,
                "sending list mail without an unsubscribe runtime: no List-Unsubscribe headers or suppression applied (set mail.unsubscribe_base_url / mail.unsubscribe_mailto)"
            );
        }
        self.transport.send(mail).await
    }

    /// Resolve the CSS-inlining decision for a message and, when enabled, inline
    /// its HTML body in place (issue #1254).
    ///
    /// Precedence: a per-message [`Mail::inline_css`] override wins; otherwise
    /// the [`Mailer`]'s configured [`MailConfig::inline_css`] default applies.
    /// On inliner failure `send` fails loudly: a typed [`MailError::CssInline`]
    /// is returned and the message is not delivered, rather than shipping a
    /// corrupted body. Text bodies are never touched.
    fn apply_css_inlining(&self, mail: &mut Mail) -> Result<(), MailError> {
        let enabled = mail.inline_css.unwrap_or(self.inline_css_default);
        if !enabled {
            return Ok(());
        }
        let Some(html) = mail.html.as_deref() else {
            return Ok(());
        };
        match inline_css_html(html) {
            Ok(inlined) => {
                mail.html = Some(inlined);
                Ok(())
            }
            Err(error) => {
                // Leave `mail.html` as the original body (not corrupted) and make
                // the failure loud rather than silently shipping broken HTML.
                tracing::warn!(
                    target: "mail",
                    error = %error,
                    "CSS inlining failed; HTML body left un-inlined"
                );
                Err(error)
            }
        }
    }

    /// Freeze this mailer's CSS-inlining default onto a message before it is
    /// handed to a durable [`MailDeliveryQueue`] for deferred delivery (issue
    /// #1254).
    ///
    /// A worker that later dequeues the persisted job resolves
    /// [`Mail::inline_css`] against ITS OWN mailer's default via
    /// [`apply_css_inlining`](Self::apply_css_inlining), which may differ from
    /// (or be off by default relative to) the originating mailer. Recording the
    /// originating decision here makes the persisted job self-describing, so
    /// deferred mail inlines consistently with an immediate send. Only `None`
    /// is resolved — explicit `Some(true)`/`Some(false)` per-message overrides
    /// are preserved. The body itself is left un-inlined so the single inline
    /// pass still happens once at the consumer's `send()`, keeping delivery
    /// idempotent and avoiding a bloated persisted body.
    const fn freeze_inline_css_default(&self, mail: &mut Mail) {
        if mail.inline_css.is_none() {
            mail.inline_css = Some(self.inline_css_default);
        }
    }

    /// Deliver a list mail recipient-by-recipient, applying suppression and
    /// per-recipient RFC 8058 headers.
    async fn send_list_mail(
        &self,
        mail: Mail,
        list_id: String,
        runtime: &UnsubscribeRuntime,
    ) -> Result<(), MailError> {
        // Resolve every recipient — address validity AND suppression decision —
        // before delivering anything. The delivery loop below sends one message
        // per recipient; if validation or a suppression-store lookup failed
        // mid-loop it could deliver to earlier recipients and then return an
        // error, so a caller retrying the send would duplicate those earlier
        // deliveries. Non-list mail builds and validates the full message before
        // any send — match that atomicity here.
        //
        // Each entry is `(recipient_display, canonical_subscriber)`. The canonical
        // bare address is used for the suppression / token key so a formatted
        // `Ada <ada@example.com>` recipient matches an opt-out recorded as
        // `ada@example.com`; the display string is preserved for actual delivery.
        let mut deliveries: Vec<(String, String)> = Vec::with_capacity(mail.to.len());
        for recipient in &mail.to {
            parse_mailbox(recipient)?;
            let subscriber = canonical_subscriber(recipient);
            if let Some(store) = runtime.suppression.as_ref()
                && store.is_suppressed(&subscriber, &list_id).await?
            {
                tracing::info!(
                    target: "mail",
                    list_id = %list_id,
                    outcome = "skipped_suppressed",
                    "skipping suppressed list-unsubscribe recipient"
                );
                continue;
            }
            deliveries.push((recipient.clone(), subscriber));
        }

        for (recipient, subscriber) in deliveries {
            let mut per_recipient = mail.clone();
            per_recipient.to = vec![recipient];
            if let Some(value) = runtime.list_unsubscribe_header(&subscriber, &list_id) {
                // A migration to `#[mailer(list_unsubscribe)]` replaces, not
                // duplicates, any header the template set by hand: drop an existing
                // List-Unsubscribe / List-Unsubscribe-Post first so the generated
                // per-recipient one-click header is authoritative (otherwise a
                // stale manual header would suppress RFC 8058 compliance).
                per_recipient.extra_headers.retain(|(name, _)| {
                    !name.eq_ignore_ascii_case("List-Unsubscribe")
                        && !name.eq_ignore_ascii_case("List-Unsubscribe-Post")
                });
                per_recipient
                    .extra_headers
                    .push(("List-Unsubscribe".to_owned(), value));
                // `List-Unsubscribe-Post` is only valid with an HTTPS one-click
                // URL; a mailto-only header is plain RFC 2369.
                if runtime.supports_one_click() {
                    per_recipient.extra_headers.push((
                        "List-Unsubscribe-Post".to_owned(),
                        "List-Unsubscribe=One-Click".to_owned(),
                    ));
                }
            }
            self.transport.send(per_recipient).await?;
        }
        Ok(())
    }

    /// Queue mail for later delivery.
    ///
    /// When called **inside a [`Db::tx`](autumn_web::db::Db::tx) block**, the
    /// delivery is automatically deferred until the transaction commits. On
    /// rollback the mail is silently dropped — no orphaned sends.
    ///
    /// This deferral is process-local. It prevents mail for rolled-back writes,
    /// but it does not make the post-commit mail handoff crash-safe unless the
    /// configured [`MailDeliveryQueue`] records a durable outbox/queue entry.
    ///
    /// When called outside any active transaction the behaviour is unchanged:
    /// the mail is dispatched in a background Tokio task immediately.
    ///
    /// Use [`deliver_later_eager`](Self::deliver_later_eager) when you need the
    /// mail to fire regardless of whether the surrounding transaction commits
    /// (e.g. security alerts that must go out on any code path).
    pub fn deliver_later(&self, mail: Mail) {
        if let Err(error) = self.try_deliver_later(mail) {
            tracing::error!(error = %error, "background mail delivery was not scheduled");
        }
    }

    /// Queue mail for later delivery, **bypassing any active transaction**.
    ///
    /// Unlike [`deliver_later`](Self::deliver_later), this method always
    /// spawns the delivery immediately — it does not check for an active
    /// `db.tx` block. Use this when the mail must be sent even if the
    /// surrounding transaction rolls back (e.g. "someone tried to log in"
    /// security alerts, rate-limit notices).
    pub fn deliver_later_eager(&self, mail: Mail) {
        if let Err(error) = self.try_deliver_later_eager(mail) {
            tracing::error!(error = %error, "background mail delivery was not scheduled");
        }
    }

    /// Queue mail for later delivery, deferring when inside a `db.tx`.
    ///
    /// # Errors
    ///
    /// Returns an error when no active Tokio runtime is available to host the
    /// background task.
    ///
    /// # Panics
    ///
    /// Panics if the internal after-commit registry mutex is poisoned.
    pub fn try_deliver_later(&self, mail: Mail) -> Result<(), MailError> {
        if self.transport.is_disabled() {
            return Ok(());
        }
        let mut mail = mail.with_defaults(&self.defaults);
        // Resolve the CSS-inlining default onto the message once, at the top of
        // the deferred path, so BOTH the durable-queue branch (persisted for a
        // possibly-different worker to consume) and the in-process fallback
        // branch carry the originating mailer's decision. Only `None` is frozen;
        // explicit per-message overrides are preserved (issue #1254).
        self.freeze_inline_css_default(&mut mail);

        // When inside a db.tx, push the spawn as an after-commit callback so
        // the mail only fires if the transaction commits successfully.
        #[cfg(feature = "db")]
        {
            let mailer = self.clone();
            let deferred = mail.clone();
            let mut f_opt: Option<(Self, Mail)> = Some((mailer, deferred));
            // Capture the caller's span now; the after-commit callback runs in a
            // fresh task with no request span, so spawn_mail_delivery would see an
            // empty span and lose trace correlation without this.
            let deliver_span = tracing::Span::current();

            crate::db::AFTER_COMMIT_REGISTRY
                .try_with(|registry| {
                    #[allow(
                        clippy::expect_used,
                        reason = "unreachable: try_with closure body runs at most once"
                    )]
                    let (m, m_mail) = f_opt.take().expect("once");
                    let span = deliver_span.clone();
                    let boxed: crate::db::CommitCallback = Box::new(move || {
                        Box::pin(tracing::Instrument::instrument(
                            async move {
                                if let Some(queue) = m.delivery_queue.clone() {
                                    queue.enqueue(m_mail).await.map_err(|e| {
                                        crate::AutumnError::internal_server_error_msg(e.to_string())
                                    })
                                } else {
                                    m.spawn_mail_delivery(m_mail).map_err(|e| {
                                        crate::AutumnError::internal_server_error_msg(e.to_string())
                                    })
                                }
                            },
                            span,
                        ))
                    });
                    registry
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .push(boxed);
                })
                .ok();

            if f_opt.is_none() {
                // Successfully registered for after-commit; skip the eager spawn.
                return Ok(());
            }
        }

        // Outside a transaction (or `db` feature not enabled) — spawn immediately.
        self.spawn_mail_delivery(mail)
    }

    /// Queue mail for later delivery, always spawning immediately.
    ///
    /// # Errors
    ///
    /// Returns an error when no active Tokio runtime is available.
    pub fn try_deliver_later_eager(&self, mail: Mail) -> Result<(), MailError> {
        if self.transport.is_disabled() {
            return Ok(());
        }
        let mut mail = mail.with_defaults(&self.defaults);
        self.freeze_inline_css_default(&mut mail);
        self.spawn_mail_delivery(mail)
    }

    fn spawn_mail_delivery(&self, mail: Mail) -> Result<(), MailError> {
        // Honor the disabled-transport contract: if the operator turned mail off
        // for this profile, deliver_later must drop the message just like
        // immediate `send` does — even when a queue is attached.
        let handle = tokio::runtime::Handle::try_current().map_err(|_| {
            MailError::RuntimeUnavailable(
                "deliver_later requires an active Tokio runtime".to_owned(),
            )
        })?;
        let parent_span = tracing::Span::current();
        if let Some(queue) = self.delivery_queue.clone() {
            handle.spawn(tracing::Instrument::instrument(
                async move {
                    if let Err(error) = queue.enqueue(mail).await {
                        tracing::error!(error = %error, "durable mail enqueue failed");
                    }
                },
                parent_span,
            ));
        } else {
            let mailer = self.clone();
            handle.spawn(tracing::Instrument::instrument(
                async move {
                    if let Err(error) = mailer.send(mail).await {
                        tracing::error!(error = %error, "background mail delivery failed");
                    }
                },
                parent_span,
            ));
        }
        Ok(())
    }
}

impl FromRequestParts<AppState> for Mailer {
    type Rejection = AutumnError;

    async fn from_request_parts(
        _parts: &mut http::request::Parts,
        state: &AppState,
    ) -> Result<Self, Self::Rejection> {
        state
            .extension::<Self>()
            .as_deref()
            .cloned()
            .ok_or_else(|| AutumnError::service_unavailable_msg("Mailer is not configured"))
    }
}

/// Builder for [`Mailer`].
#[derive(Clone)]
pub struct MailerBuilder {
    transport: Transport,
    from: Option<String>,
    reply_to: Option<String>,
    file_dir: PathBuf,
    smtp: Option<SmtpConfig>,
    delivery_queue: Option<Arc<dyn MailDeliveryQueue>>,
    resilience_config: Option<Arc<crate::config::ResilienceConfig>>,
    inline_css: bool,
}

impl Default for MailerBuilder {
    fn default() -> Self {
        Self {
            transport: Transport::Log,
            from: None,
            reply_to: None,
            file_dir: default_file_dir(),
            smtp: None,
            delivery_queue: None,
            resilience_config: None,
            inline_css: false,
        }
    }
}

impl MailerBuilder {
    /// Select the transport.
    #[must_use]
    pub const fn transport(mut self, transport: Transport) -> Self {
        self.transport = transport;
        self
    }

    /// Set default From header.
    #[must_use]
    pub fn from(mut self, from: impl Into<String>) -> Self {
        self.from = Some(from.into());
        self
    }

    /// Set default Reply-To header.
    #[must_use]
    pub fn reply_to(mut self, reply_to: impl Into<String>) -> Self {
        self.reply_to = Some(reply_to.into());
        self
    }

    /// Set file output directory.
    #[must_use]
    pub fn file_dir(mut self, dir: impl AsRef<Path>) -> Self {
        self.file_dir = dir.as_ref().to_path_buf();
        self
    }

    /// Set SMTP config.
    #[must_use]
    pub fn smtp(mut self, smtp: SmtpConfig) -> Self {
        self.smtp = Some(smtp);
        self
    }

    /// Attach a durable [`MailDeliveryQueue`] used by
    /// [`Mailer::deliver_later`].
    #[must_use]
    pub fn delivery_queue(mut self, queue: impl MailDeliveryQueue + 'static) -> Self {
        self.delivery_queue = Some(Arc::new(queue));
        self
    }

    /// Attach an already-shared durable [`MailDeliveryQueue`].
    #[must_use]
    pub fn delivery_queue_arc(mut self, queue: Arc<dyn MailDeliveryQueue>) -> Self {
        self.delivery_queue = Some(queue);
        self
    }

    #[must_use]
    pub fn resilience_config(mut self, rc: Option<Arc<crate::config::ResilienceConfig>>) -> Self {
        self.resilience_config = rc;
        self
    }

    /// Set the default for CSS inlining of HTML bodies (issue #1254). Applied to
    /// every message that does not carry its own [`MailBuilder::inline_css`]
    /// override. Mirrors [`MailConfig::inline_css`].
    #[must_use]
    pub const fn inline_css(mut self, enabled: bool) -> Self {
        self.inline_css = enabled;
        self
    }

    /// Build the mailer.
    ///
    /// # Errors
    ///
    /// Returns an error when the SMTP transport or default addresses cannot be configured.
    pub fn build(self) -> Result<Mailer, MailError> {
        if let Some(from) = &self.from {
            parse_mailbox(from)?;
        }
        if let Some(reply_to) = &self.reply_to {
            parse_mailbox(reply_to)?;
        }

        let transport: Arc<dyn MailTransport> = match self.transport {
            Transport::Log => Arc::new(LogTransport),
            Transport::File => Arc::new(FileTransport { dir: self.file_dir }),
            Transport::Disabled => Arc::new(DisabledTransport),
            Transport::Smtp => Arc::new(SmtpTransport::new(
                self.smtp.unwrap_or_default(),
                self.resilience_config.clone(),
            )?),
        };

        Ok(Mailer {
            defaults: Arc::new(MailerDefaults {
                from: self.from,
                reply_to: self.reply_to,
            }),
            transport,
            delivery_queue: self.delivery_queue,
            unsubscribe: None,
            suppression: None,
            inline_css_default: self.inline_css,
        })
    }
}

struct DisabledTransport;

impl MailTransport for DisabledTransport {
    fn send<'a>(
        &'a self,
        _mail: Mail,
    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
        Box::pin(async { Ok(()) })
    }

    fn is_disabled(&self) -> bool {
        true
    }
}

struct LogTransport;

impl MailTransport for LogTransport {
    fn send<'a>(
        &'a self,
        mail: Mail,
    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
        Box::pin(async move {
            tracing::info!(
                from = ?mail.from,
                reply_to = ?mail.reply_to,
                to = ?mail.to,
                subject = %mail.subject,
                text = ?mail.text,
                html = ?mail.html,
                attachments = mail.attachments.len(),
                "mail captured by log transport"
            );
            Ok(())
        })
    }
}

struct FileTransport {
    dir: PathBuf,
}

static FILE_TRANSPORT_SEQUENCE: AtomicU64 = AtomicU64::new(0);

impl MailTransport for FileTransport {
    fn send<'a>(
        &'a self,
        mail: Mail,
    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
        Box::pin(async move {
            tokio::fs::create_dir_all(&self.dir).await?;
            let filename = file_transport_filename(&mail);
            let path = self.dir.join(filename);
            let mut file = tokio::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(path)
                .await?;
            let eml = render_eml(&mail);
            tokio::io::AsyncWriteExt::write_all(&mut file, eml.as_bytes()).await?;
            tokio::io::AsyncWriteExt::flush(&mut file).await?;
            file.sync_all().await?;
            Ok(())
        })
    }
}

struct SmtpTransport {
    inner: AsyncSmtpTransport<Tokio1Executor>,
    resilience_config: Option<Arc<crate::config::ResilienceConfig>>,
}

impl SmtpTransport {
    fn new(
        config: SmtpConfig,
        resilience_config: Option<Arc<crate::config::ResilienceConfig>>,
    ) -> Result<Self, MailError> {
        let host = config
            .host
            .filter(|host| !host.trim().is_empty())
            .ok_or_else(|| MailError::InvalidMessage("mail.smtp.host is required".to_owned()))?;
        let mut builder = match config.tls {
            TlsMode::Disabled => AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&host),
            TlsMode::StartTls => AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&host)?,
            TlsMode::Tls => AsyncSmtpTransport::<Tokio1Executor>::relay(&host)?,
        };
        if let Some(port) = config.port {
            builder = builder.port(port);
        }
        if let Some(username) = config.username {
            let password_env = config.password_env.ok_or_else(|| {
                MailError::InvalidMessage(
                    "mail.smtp.password_env is required when mail.smtp.username is set".to_owned(),
                )
            })?;
            let password = std::env::var(&password_env)
                .map_err(|error| smtp_password_env_error(&password_env, &error))?;
            builder = builder.credentials(Credentials::new(username, password));
        }
        Ok(Self {
            inner: builder.build(),
            resilience_config,
        })
    }
}

/// Builds the startup error for a failed SMTP password lookup without ever
/// embedding the environment variable's *value*: [`std::env::VarError`]'s
/// `NotUnicode` variant carries the raw contents of the variable — the SMTP
/// password itself — in both its `Display` and `Debug` output, so the error
/// kind is mapped to a static description instead of being formatted. The
/// variable *name* is ordinary configuration and is kept for diagnostics.
fn smtp_password_env_error(password_env: &str, error: &std::env::VarError) -> MailError {
    let reason = match error {
        std::env::VarError::NotPresent => "environment variable is not set",
        std::env::VarError::NotUnicode(_) => "environment variable contains non-unicode data",
    };
    MailError::InvalidMessage(format!(
        "mail.smtp.password_env={password_env:?} could not be resolved: {reason}"
    ))
}

impl MailTransport for SmtpTransport {
    fn send<'a>(
        &'a self,
        mail: Mail,
    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
        Box::pin(async move {
            let breaker = self.resilience_config.as_ref().map_or_else(
                || {
                    crate::circuit_breaker::global_registry().get_or_create(
                        "smtp_mailer",
                        crate::circuit_breaker::CircuitBreakerPolicy::default(),
                    )
                },
                |rc| {
                    let policy = crate::circuit_breaker::CircuitBreakerPolicy::from_config(
                        rc,
                        "smtp_mailer",
                    );
                    crate::circuit_breaker::global_registry()
                        .get_or_create_with_config("smtp_mailer", policy)
                },
            );

            if breaker.before_call().is_err() {
                return Err(MailError::RuntimeUnavailable(
                    "smtp mailer circuit breaker is open".to_owned(),
                ));
            }
            let guard = crate::circuit_breaker::CircuitBreakerGuard::new(breaker.clone());

            let message = lettre_message(&mail)?;
            let res = self.inner.send(message).await;
            if res.is_ok() {
                guard.success();
            } else {
                guard.failure();
            }

            res.map(|_| ()).map_err(Into::into)
        })
    }
}

fn sanitize_filename(value: &str) -> String {
    value
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '_') {
                ch
            } else {
                '_'
            }
        })
        .collect()
}

/// RFC 2231 `attr-char`: alphanumerics plus these ASCII punctuation marks may
/// appear unescaped in an extended parameter value; everything else
/// (including all non-ASCII and control bytes) is percent-encoded.
const RFC2231_ATTR_CHAR: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
    .remove(b'!')
    .remove(b'#')
    .remove(b'$')
    .remove(b'&')
    .remove(b'+')
    .remove(b'-')
    .remove(b'.')
    .remove(b'^')
    .remove(b'_')
    .remove(b'`')
    .remove(b'|')
    .remove(b'~');

/// Strips CR/LF and other ASCII/Unicode control characters from a header
/// value written by the hand-rolled `.eml` renderer, so untrusted `Mail`
/// field content (which may arrive via `Deserialize` from a durable queue,
/// bypassing [`MailBuilder::build`]'s validation) can never inject an extra
/// header line.
fn strip_header_controls(value: &str) -> String {
    value.chars().filter(|ch| !ch.is_control()).collect()
}

fn quote_header_value(value: &str) -> String {
    let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
    format!("\"{escaped}\"")
}

/// Builds the `Content-Disposition: attachment; …` parameter section for the
/// hand-rolled `.eml` renderer. Always ASCII and CR/LF-free by construction:
/// control characters are stripped, and non-ASCII filenames are RFC 2231
/// percent-encoded (`filename*=UTF-8''…`) alongside an ASCII fallback
/// `filename="…"` for readers that don't understand extended parameters.
fn content_disposition_params(filename: &str) -> String {
    let mut clean = strip_header_controls(filename);
    if clean.trim().is_empty() {
        "attachment".clone_into(&mut clean);
    }
    if clean.is_ascii() {
        format!("filename={}", quote_header_value(&clean))
    } else {
        let fallback: String = clean
            .chars()
            .map(|ch| if ch.is_ascii() { ch } else { '_' })
            .collect();
        let encoded = percent_encoding::utf8_percent_encode(&clean, RFC2231_ATTR_CHAR);
        format!(
            "filename={}; filename*=UTF-8''{encoded}",
            quote_header_value(&fallback)
        )
    }
}

/// Base64-encodes `bytes` and hard-wraps at 76 columns per RFC 2045.
fn base64_wrap76(bytes: &[u8]) -> String {
    use base64::Engine as _;
    let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
    if encoded.len() <= 76 {
        return encoded;
    }
    let newlines = (encoded.len() - 1) / 76;
    let mut wrapped = String::with_capacity(encoded.len() + newlines);
    for chunk in encoded.as_bytes().chunks(76) {
        if !wrapped.is_empty() {
            wrapped.push('\n');
        }
        #[allow(
            clippy::expect_used,
            reason = "infallible: base64 output is always ASCII"
        )]
        let chunk_str = std::str::from_utf8(chunk).expect("base64 output is always ASCII");
        wrapped.push_str(chunk_str);
    }
    wrapped
}

fn file_transport_filename(mail: &Mail) -> String {
    let sequence = FILE_TRANSPORT_SEQUENCE.fetch_add(1, Ordering::Relaxed);
    format!(
        "{}-{}-{:016x}-{}.eml",
        chrono::Utc::now().format("%Y%m%d%H%M%S%6f"),
        std::process::id(),
        sequence,
        sanitize_filename(mail.to.first().map_or("unknown", String::as_str))
    )
}

fn render_eml(mail: &Mail) -> String {
    let mut out = String::new();
    if let Some(from) = &mail.from {
        out.push_str("From: ");
        out.push_str(&strip_header_controls(from));
        out.push('\n');
    }
    for to in &mail.to {
        out.push_str("To: ");
        out.push_str(&strip_header_controls(to));
        out.push('\n');
    }
    if let Some(reply_to) = &mail.reply_to {
        out.push_str("Reply-To: ");
        out.push_str(&strip_header_controls(reply_to));
        out.push('\n');
    }
    out.push_str("Date: ");
    out.push_str(&chrono::Utc::now().to_rfc2822());
    out.push('\n');
    out.push_str("Message-Id: <");
    out.push_str(&uuid::Uuid::new_v4().to_string());
    out.push_str("@autumn.local>\n");
    out.push_str("Subject: ");
    out.push_str(&strip_header_controls(&mail.subject));
    out.push('\n');
    for (name, value) in &mail.extra_headers {
        out.push_str(&strip_header_controls(name));
        out.push_str(": ");
        out.push_str(&strip_header_controls(value));
        out.push('\n');
    }
    out.push_str("MIME-Version: 1.0\n");
    if mail.attachments.is_empty() {
        render_eml_bodies(mail, &mut out);
    } else {
        // Random per-message boundary: text/html bodies are caller-controlled
        // and may legitimately contain a line matching a fixed boundary
        // (e.g. `--autumn-mixed`), which would truncate or split the
        // rendered MIME structure. A boundary the caller cannot predict in
        // advance can't collide with body content.
        use std::fmt::Write as _;
        let boundary = format!("autumn-mixed-{}", uuid::Uuid::new_v4().simple());
        let _ = write!(
            out,
            "Content-Type: multipart/mixed; boundary=\"{boundary}\"\n\n"
        );
        let _ = writeln!(out, "--{boundary}");
        render_eml_bodies(mail, &mut out);
        for attachment in &mail.attachments {
            let _ = writeln!(out, "--{boundary}");
            out.push_str("Content-Type: ");
            let content_type = strip_header_controls(&attachment.content_type);
            if ContentType::parse(&content_type).is_ok() {
                out.push_str(&content_type);
            } else {
                out.push_str("application/octet-stream");
            }
            out.push('\n');
            out.push_str("Content-Disposition: attachment; ");
            out.push_str(&content_disposition_params(&attachment.filename));
            out.push('\n');
            out.push_str("Content-Transfer-Encoding: base64\n\n");
            out.push_str(&base64_wrap76(&attachment.bytes));
            out.push('\n');
        }
        let _ = writeln!(out, "--{boundary}--");
    }
    out
}

/// Renders the html/text body part(s) of an `.eml` message — everything
/// after the `MIME-Version` header, before any `multipart/mixed` attachment
/// wrapper. Pulled out of [`render_eml`] so the attachment-less code path is
/// provably byte-identical to what it was before attachments existed.
fn render_eml_bodies(mail: &Mail, out: &mut String) {
    if mail.html.is_some() && mail.text.is_some() {
        out.push_str("Content-Type: multipart/alternative; boundary=\"autumn-mail\"\n\n");
        if let Some(text) = &mail.text {
            out.push_str("--autumn-mail\nContent-Type: text/plain; charset=utf-8\n\n");
            out.push_str(text);
            out.push('\n');
        }
        if let Some(html) = &mail.html {
            out.push_str("--autumn-mail\nContent-Type: text/html; charset=utf-8\n\n");
            out.push_str(html);
            out.push('\n');
        }
        out.push_str("--autumn-mail--\n");
    } else if let Some(html) = &mail.html {
        out.push_str("Content-Type: text/html; charset=utf-8\n\n");
        out.push_str(html);
        out.push('\n');
    } else if let Some(text) = &mail.text {
        out.push_str("Content-Type: text/plain; charset=utf-8\n\n");
        out.push_str(text);
        out.push('\n');
    }
}

#[derive(Debug, Clone)]
struct ParsedMail {
    headers: Vec<(String, String)>,
    to: Vec<String>,
    subject: String,
    date: Option<String>,
    html: Option<String>,
    text: Option<String>,
    attachments: Vec<ParsedAttachment>,
    raw: String,
}

impl ParsedMail {
    fn header_value(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(header, _)| header.eq_ignore_ascii_case(name))
            .map(|(_, value)| value.as_str())
    }
}

/// An attachment as surfaced by the dev mail preview: just enough to list it
/// (filename, declared content type) without decoding its body.
#[derive(Debug, Clone)]
struct ParsedAttachment {
    filename: String,
    content_type: String,
}

#[derive(Debug, Clone)]
struct CapturedMailSummary {
    id: String,
    to: Vec<String>,
    subject: String,
    timestamp: String,
    modified: SystemTime,
}

pub(crate) fn mail_preview_router<S>(file_dir: PathBuf) -> axum::Router<S>
where
    S: Clone + Send + Sync + 'static,
    AppState: axum::extract::FromRef<S>,
{
    let file_dir = Arc::new(file_dir);
    axum::Router::new()
        .route(
            MAIL_PREVIEW_PATH,
            axum::routing::get({
                let file_dir = Arc::clone(&file_dir);
                move |axum::extract::State(state): axum::extract::State<AppState>| {
                    let file_dir = Arc::clone(&file_dir);
                    async move { list_mail_preview(file_dir, state).await }
                }
            }),
        )
        .route(
            MAIL_PREVIEW_MESSAGE_PATH,
            axum::routing::get({
                let file_dir = Arc::clone(&file_dir);
                move |axum::extract::Path(message_id): axum::extract::Path<String>| {
                    let file_dir = Arc::clone(&file_dir);
                    async move { show_captured_mail(file_dir, message_id).await }
                }
            }),
        )
        .route(
            MAIL_PREVIEW_TEMPLATE_PATH,
            axum::routing::get(
                |axum::extract::Path((mailer, method)): axum::extract::Path<(String, String)>,
                 axum::extract::State(state): axum::extract::State<AppState>| async move {
                    show_template_preview(&state, &mailer, &method)
                },
            ),
        )
}

async fn list_mail_preview(file_dir: Arc<PathBuf>, state: AppState) -> Response {
    match captured_messages(&file_dir).await {
        Ok(messages) => {
            let previews = state
                .extension::<MailPreviewRegistry>()
                .map(|registry| registry.previews().to_vec())
                .unwrap_or_default();
            html_response(render_mail_index(&messages, &previews, &file_dir))
        }
        Err(error) => preview_error_response(&error),
    }
}

async fn show_captured_mail(file_dir: Arc<PathBuf>, message_id: String) -> Response {
    match read_captured_message(&file_dir, &message_id).await {
        Ok(parsed) => html_response(render_mail_detail(&parsed, "Captured message")),
        Err(error) => preview_error_response(&error),
    }
}

fn show_template_preview(state: &AppState, mailer: &str, method: &str) -> Response {
    let preview = state
        .extension::<MailPreviewRegistry>()
        .and_then(|registry| registry.find(mailer, method));
    let Some(preview) = preview else {
        return preview_error_response(&MailPreviewError::NotFound(format!("{mailer}/{method}")));
    };

    match preview.render() {
        Ok(mail) => {
            let mut mail = apply_preview_unsubscribe_headers(state, mailer, mail);
            // Match Mailer::send: inline <style> CSS so the preview reflects what
            // strict clients (Gmail/Outlook) actually receive. Reuses the send-time
            // decision (per-message override vs. the mailer's inline_css_default).
            if let Some(m) = state.extension::<Mailer>() {
                // Dev preview: degrade gracefully on inliner error (leaves html un-inlined)
                // rather than failing the preview; the inliner is effectively infallible here.
                let _ = m.apply_css_inlining(&mut mail);
            }
            let raw = render_eml(&mail);
            let parsed = parse_eml(&raw);
            html_response(render_mail_detail(&parsed, "Template preview"))
        }
        Err(error) => preview_error_response(&error),
    }
}

/// Inject sample RFC 8058 headers into a preview so authors can confirm wiring
/// without sending. Uses the configured [`UnsubscribeRuntime`] when present,
/// otherwise a sample base URL with an ephemeral key purely for display.
fn apply_preview_unsubscribe_headers(state: &AppState, mailer_label: &str, mut mail: Mail) -> Mail {
    let scope = mail.list_unsubscribe.clone().or_else(|| {
        registered_list_unsubscribe_scopes()
            .into_iter()
            .find(|descriptor| descriptor.mailer == mailer_label)
            .map(|descriptor| descriptor.scope.to_owned())
    });
    let Some(scope) = scope else {
        return mail;
    };
    mail.list_unsubscribe = Some(scope.clone());
    let recipient = mail.to.first().map_or_else(
        || "subscriber@example.com".to_owned(),
        |to| canonical_subscriber(to),
    );
    // Use the configured runtime when present, otherwise a sample with an
    // ephemeral key purely for display. Compute the header inside each branch so
    // the sample need not outlive this expression.
    let (header, one_click) = state.extension::<UnsubscribeRuntime>().map_or_else(
        || {
            let sample = UnsubscribeRuntime {
                base_url: Some("https://example.com".to_owned()),
                mailto: None,
                signing_keys: Arc::new(crate::security::config::resolve_signing_keys(
                    &crate::security::config::SigningSecretConfig::default(),
                )),
                ttl_days: unsubscribe::DEFAULT_TOKEN_TTL_DAYS,
                suppression: None,
            };
            (
                sample.list_unsubscribe_header(&recipient, &scope),
                sample.supports_one_click(),
            )
        },
        |runtime| {
            (
                runtime.list_unsubscribe_header(&recipient, &scope),
                runtime.supports_one_click(),
            )
        },
    );
    if let Some(value) = header {
        // Mirror send: the generated header replaces, not duplicates, any header
        // the preview author set by hand, so the preview reflects what is sent.
        mail.extra_headers.retain(|(name, _)| {
            !name.eq_ignore_ascii_case("List-Unsubscribe")
                && !name.eq_ignore_ascii_case("List-Unsubscribe-Post")
        });
        mail.extra_headers
            .push(("List-Unsubscribe".to_owned(), value));
        if one_click {
            mail.extra_headers.push((
                "List-Unsubscribe-Post".to_owned(),
                "List-Unsubscribe=One-Click".to_owned(),
            ));
        }
    }
    mail
}

async fn captured_messages(dir: &Path) -> Result<Vec<CapturedMailSummary>, MailPreviewError> {
    let mut entries = match tokio::fs::read_dir(dir).await {
        Ok(entries) => entries,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => return Err(error.into()),
    };

    let mut messages = Vec::new();
    while let Some(entry) = entries.next_entry().await? {
        let path = entry.path();
        if !path
            .extension()
            .and_then(|ext| ext.to_str())
            .is_some_and(|ext| ext.eq_ignore_ascii_case("eml"))
        {
            continue;
        }
        let Some(id) = path.file_name().and_then(|name| name.to_str()) else {
            continue;
        };
        let metadata = entry.metadata().await?;
        let modified = metadata.modified().unwrap_or(UNIX_EPOCH);
        let raw = tokio::fs::read_to_string(&path).await?;
        let parsed = parse_eml(&raw);
        messages.push(CapturedMailSummary {
            id: id.to_owned(),
            to: parsed.to,
            subject: parsed.subject,
            timestamp: parsed.date.unwrap_or_else(|| format_system_time(modified)),
            modified,
        });
    }

    messages.sort_by(|left, right| {
        right
            .modified
            .cmp(&left.modified)
            .then_with(|| right.id.cmp(&left.id))
    });
    Ok(messages)
}

async fn read_captured_message(
    dir: &Path,
    message_id: &str,
) -> Result<ParsedMail, MailPreviewError> {
    if !valid_message_id(message_id) {
        return Err(MailPreviewError::InvalidMessageId(message_id.to_owned()));
    }
    let path = dir.join(message_id);
    let raw = match tokio::fs::read_to_string(&path).await {
        Ok(raw) => raw,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Err(MailPreviewError::NotFound(message_id.to_owned()));
        }
        Err(error) => return Err(error.into()),
    };
    Ok(parse_eml(&raw))
}

fn valid_message_id(message_id: &str) -> bool {
    !message_id.is_empty()
        && Path::new(message_id)
            .extension()
            .and_then(|ext| ext.to_str())
            .is_some_and(|ext| ext.eq_ignore_ascii_case("eml"))
        && !message_id.contains('/')
        && !message_id.contains('\\')
        && !message_id.contains("..")
}

fn parse_eml(raw: &str) -> ParsedMail {
    let normalized = raw.replace("\r\n", "\n");
    let (headers, body) = split_headers_body(&normalized);
    let content_type = header_value(&headers, "Content-Type").unwrap_or_default();
    let (html, text, attachments) = parse_mail_body(&content_type, body);
    let to = header_values(&headers, "To");
    let subject = header_value(&headers, "Subject").unwrap_or_else(|| "(no subject)".to_owned());
    let date = header_value(&headers, "Date");

    ParsedMail {
        headers,
        to,
        subject,
        date,
        html,
        text,
        attachments,
        raw: raw.to_owned(),
    }
}

fn split_headers_body(raw: &str) -> (Vec<(String, String)>, &str) {
    let Some((header_block, body)) = raw.split_once("\n\n") else {
        return (parse_header_block(raw), "");
    };
    (parse_header_block(header_block), body)
}

fn parse_header_block(header_block: &str) -> Vec<(String, String)> {
    let mut headers = Vec::new();
    let mut current: Option<(String, String)> = None;

    for line in header_block.lines() {
        if line.starts_with(' ') || line.starts_with('\t') {
            if let Some((_, value)) = current.as_mut() {
                value.push(' ');
                value.push_str(line.trim());
            }
            continue;
        }
        if let Some(header) = current.take() {
            headers.push(header);
        }
        if let Some((name, value)) = line.split_once(':') {
            current = Some((name.trim().to_owned(), value.trim().to_owned()));
        }
    }
    if let Some(header) = current {
        headers.push(header);
    }
    headers
}

fn header_value(headers: &[(String, String)], name: &str) -> Option<String> {
    headers
        .iter()
        .find(|(header, _)| header.eq_ignore_ascii_case(name))
        .map(|(_, value)| value.clone())
}

fn header_values(headers: &[(String, String)], name: &str) -> Vec<String> {
    headers
        .iter()
        .filter(|(header, _)| header.eq_ignore_ascii_case(name))
        .map(|(_, value)| value.clone())
        .collect()
}

fn parse_mail_body(
    content_type: &str,
    body: &str,
) -> (Option<String>, Option<String>, Vec<ParsedAttachment>) {
    let lower = content_type.to_ascii_lowercase();
    if lower.contains("multipart/mixed")
        && let Some(boundary) = content_type_boundary(content_type)
    {
        return parse_multipart_mixed(body, &boundary);
    }

    if lower.contains("multipart/alternative")
        && let Some(boundary) = content_type_boundary(content_type)
    {
        let (html, text) = parse_multipart_alternative(body, &boundary);
        return (html, text, Vec::new());
    }

    if lower.contains("text/html") {
        (Some(trim_body(body)), None, Vec::new())
    } else {
        (None, Some(trim_body(body)), Vec::new())
    }
}

/// Parses a `multipart/mixed` body: the first non-attachment part is
/// recursed into for html/text (it is itself typically a nested
/// `multipart/alternative`), and every part with an `attachment`
/// `Content-Disposition` is collected into the returned attachment list.
fn parse_multipart_mixed(
    body: &str,
    boundary: &str,
) -> (Option<String>, Option<String>, Vec<ParsedAttachment>) {
    let marker = format!("--{boundary}");
    let mut html = None;
    let mut text = None;
    let mut attachments = Vec::new();

    for segment in body.split(&marker).skip(1) {
        let segment = segment.trim_start_matches(['\n', '\r']);
        if segment.starts_with("--") {
            break;
        }
        let (headers, part_body) = split_headers_body(segment);
        let disposition = header_value(&headers, "Content-Disposition").unwrap_or_default();
        let part_content_type = header_value(&headers, "Content-Type").unwrap_or_default();
        let disposition_type = split_mime_params(&disposition)
            .first()
            .copied()
            .unwrap_or("");
        if disposition_type.eq_ignore_ascii_case("attachment") {
            attachments.push(ParsedAttachment {
                filename: extract_attachment_filename(&disposition),
                content_type: content_type_without_params(&part_content_type),
            });
        } else {
            let (nested_html, nested_text, _) = parse_mail_body(&part_content_type, part_body);
            html = html.or(nested_html);
            text = text.or(nested_text);
        }
    }

    (html, text, attachments)
}

/// Splits a `Content-Disposition`/`Content-Type` parameter list on `;`,
/// respecting RFC 2045 quoted-string boundaries so a value like
/// `filename="a;b.txt"` is not mistaken for two parameters.
fn split_mime_params(value: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut start = 0;
    let mut in_quotes = false;
    let mut escaped = false;
    for (i, ch) in value.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        match ch {
            '\\' if in_quotes => escaped = true,
            '"' => in_quotes = !in_quotes,
            ';' if !in_quotes => {
                parts.push(value[start..i].trim());
                start = i + ch.len_utf8();
            }
            _ => {}
        }
    }
    parts.push(value[start..].trim());
    parts
}

/// Reverses RFC 2045 quoted-string escaping (`\\` → `\`, `\"` → `"`), the
/// inverse of [`quote_header_value`].
fn unescape_quoted_string(value: &str) -> String {
    let mut result = String::with_capacity(value.len());
    let mut chars = value.chars();
    while let Some(ch) = chars.next() {
        if ch == '\\'
            && let Some(next) = chars.next()
        {
            result.push(next);
        } else {
            result.push(ch);
        }
    }
    result
}

/// Extracts a filename from a `Content-Disposition: attachment; …` header
/// value, preferring the RFC 2231 extended `filename*=charset'lang'…`
/// parameter (percent-decoded, case-insensitive charset/param name, any
/// language tag) over the plain `filename="…"` fallback when both are
/// present.
fn extract_attachment_filename(disposition: &str) -> String {
    let params = split_mime_params(disposition);
    if let Some(value) = params.iter().skip(1).find_map(|part| {
        let (key, val) = part.split_once('=')?;
        key.trim().eq_ignore_ascii_case("filename*").then_some(val)
    }) {
        let encoded = value.splitn(3, '\'').nth(2).unwrap_or(value);
        return percent_encoding::percent_decode_str(encoded)
            .decode_utf8_lossy()
            .into_owned();
    }
    if let Some(value) = params.iter().skip(1).find_map(|part| {
        let (key, val) = part.split_once('=')?;
        key.trim()
            .eq_ignore_ascii_case("filename")
            .then_some(val.trim())
    }) {
        if let Some(inner) = value.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
            return unescape_quoted_string(inner);
        }
        return value.to_owned();
    }
    "attachment".to_owned()
}

fn content_type_without_params(content_type: &str) -> String {
    content_type
        .split(';')
        .next()
        .unwrap_or(content_type)
        .trim()
        .to_owned()
}

fn parse_multipart_alternative(body: &str, boundary: &str) -> (Option<String>, Option<String>) {
    let marker = format!("--{boundary}");
    let mut html = None;
    let mut text = None;

    for segment in body.split(&marker).skip(1) {
        let segment = segment.trim_start_matches(['\n', '\r']);
        if segment.starts_with("--") {
            break;
        }
        let (headers, part_body) = split_headers_body(segment);
        let content_type = header_value(&headers, "Content-Type").unwrap_or_default();
        if content_type.to_ascii_lowercase().contains("text/html") {
            html = Some(trim_body(part_body));
        } else if content_type.to_ascii_lowercase().contains("text/plain") {
            text = Some(trim_body(part_body));
        }
    }

    (html, text)
}

fn content_type_boundary(content_type: &str) -> Option<String> {
    content_type.split(';').find_map(|part| {
        let part = part.trim();
        let (name, value) = part.split_once('=')?;
        if !name.trim().eq_ignore_ascii_case("boundary") {
            return None;
        }
        Some(value.trim().trim_matches('"').to_owned())
    })
}

fn trim_body(body: &str) -> String {
    body.trim_matches(['\r', '\n']).to_owned()
}

fn format_system_time(time: SystemTime) -> String {
    let datetime: chrono::DateTime<chrono::Utc> = time.into();
    datetime.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

fn render_mail_index(
    messages: &[CapturedMailSummary],
    previews: &[MailPreview],
    file_dir: &Path,
) -> String {
    let mut body = String::new();
    body.push_str("<h1>Autumn Mail</h1>");
    body.push_str("<section><h2>Captured messages</h2>");
    if messages.is_empty() {
        body.push_str("<p class=\"empty\">No captured emails yet. Set <code>mail.transport = &quot;file&quot;</code>, send an email, then refresh this page. Autumn reads <code>");
        body.push_str(&escape_html(&file_dir.display().to_string()));
        body.push_str("</code>.</p>");
    } else {
        body.push_str(
            "<table><thead><tr><th>Timestamp</th><th>To</th><th>Subject</th></tr></thead><tbody>",
        );
        for message in messages {
            body.push_str("<tr><td>");
            body.push_str(&escape_html(&message.timestamp));
            body.push_str("</td><td>");
            body.push_str(&escape_html(&message.to.join(", ")));
            body.push_str("</td><td><a href=\"");
            body.push_str(MAIL_PREVIEW_PATH);
            body.push_str("/messages/");
            body.push_str(&escape_html(&message.id));
            body.push_str("\">");
            body.push_str(&escape_html(&message.subject));
            body.push_str("</a></td></tr>");
        }
        body.push_str("</tbody></table>");
    }
    body.push_str("</section><section><h2>Template previews</h2>");
    if previews.is_empty() {
        body.push_str("<p class=\"empty\">No mailer previews registered.</p>");
    } else {
        body.push_str("<table><thead><tr><th>Mailer</th><th>Preview</th></tr></thead><tbody>");
        for preview in previews {
            body.push_str("<tr><td>");
            body.push_str(&escape_html(preview.mailer()));
            body.push_str("</td><td><a href=\"");
            body.push_str(MAIL_PREVIEW_PATH);
            body.push_str("/previews/");
            body.push_str(&escape_html(preview.mailer()));
            body.push('/');
            body.push_str(&escape_html(preview.method()));
            body.push_str("\">");
            body.push_str(&escape_html(preview.method()));
            body.push_str("</a></td></tr>");
        }
        body.push_str("</tbody></table>");
    }
    body.push_str("</section>");
    render_mail_preview_layout("Autumn Mail", &body)
}

fn render_mail_detail(parsed: &ParsedMail, label: &str) -> String {
    let mut body = String::new();
    body.push_str("<p><a href=\"");
    body.push_str(MAIL_PREVIEW_PATH);
    body.push_str("\">Back to mail</a></p><h1>");
    body.push_str(&escape_html(&parsed.subject));
    body.push_str("</h1><p class=\"muted\">");
    body.push_str(&escape_html(label));
    body.push_str("</p>");

    if let Some(html) = &parsed.html {
        body.push_str("<iframe title=\"Rendered HTML email\" sandbox srcdoc=\"");
        body.push_str(&escape_html(html));
        body.push_str("\"></iframe>");
    } else {
        body.push_str("<p class=\"empty\">No HTML body was found for this email.</p>");
    }

    body.push_str("<details><summary>Plain text</summary><pre>");
    body.push_str(&escape_html(parsed.text.as_deref().unwrap_or("")));
    body.push_str("</pre></details>");

    if !parsed.attachments.is_empty() {
        body.push_str("<details open><summary>Attachments (");
        body.push_str(&parsed.attachments.len().to_string());
        body.push_str(")</summary><ul>");
        for attachment in &parsed.attachments {
            body.push_str("<li>");
            body.push_str(&escape_html(&attachment.filename));
            body.push_str(" <span class=\"muted\">(");
            body.push_str(&escape_html(&attachment.content_type));
            body.push_str(")</span></li>");
        }
        body.push_str("</ul></details>");
    }

    body.push_str("<details><summary>Headers</summary><dl>");
    for header in [
        "From",
        "To",
        "Reply-To",
        "Subject",
        "Date",
        "Message-Id",
        "List-Unsubscribe",
        "List-Unsubscribe-Post",
    ] {
        if let Some(value) = parsed.header_value(header) {
            body.push_str("<dt>");
            body.push_str(header);
            body.push_str("</dt><dd>");
            body.push_str(&escape_html(value));
            body.push_str("</dd>");
        }
    }
    body.push_str("</dl></details>");

    body.push_str("<details><summary>Raw .eml</summary><pre>");
    body.push_str(&escape_html(&parsed.raw));
    body.push_str("</pre></details>");

    render_mail_preview_layout(&parsed.subject, &body)
}

fn render_mail_preview_layout(title: &str, body: &str) -> String {
    format!(
        "<!doctype html><html><head><meta charset=\"utf-8\"><title>{}</title><style>{}</style></head><body>{}</body></html>",
        escape_html(title),
        MAIL_PREVIEW_CSS,
        body
    )
}

const MAIL_PREVIEW_CSS: &str = r#"
body{margin:0;padding:24px;font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#1f2933;background:#f6f8fa}
h1{margin:0 0 16px;font-size:28px}
h2{margin:28px 0 12px;font-size:18px}
table{width:100%;border-collapse:collapse;background:white;border:1px solid #d9e2ec}
th,td{padding:10px 12px;border-bottom:1px solid #e5eaf0;text-align:left;font-size:14px;vertical-align:top}
th{background:#edf2f7;color:#394b59;font-weight:650}
a{color:#0b63ce;text-decoration:none}
a:hover{text-decoration:underline}
.empty,.muted{color:#52616f}
code,pre{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}
pre{white-space:pre-wrap;background:#111827;color:#f8fafc;padding:12px;overflow:auto}
iframe{width:100%;min-height:420px;border:1px solid #cbd5e1;background:white}
details{margin-top:14px;background:white;border:1px solid #d9e2ec;padding:10px 12px}
summary{cursor:pointer;font-weight:650}
dt{font-weight:650;margin-top:8px}
dd{margin:2px 0 8px}
"#;

fn html_response(html: String) -> Response {
    Html(html).into_response()
}

fn preview_error_response(error: &MailPreviewError) -> Response {
    let status = match error {
        MailPreviewError::NotFound(_) | MailPreviewError::InvalidMessageId(_) => {
            http::StatusCode::NOT_FOUND
        }
        MailPreviewError::Io(_) | MailPreviewError::PreviewPanicked { .. } => {
            http::StatusCode::INTERNAL_SERVER_ERROR
        }
    };
    (
        status,
        Html(render_mail_preview_layout(
            "Mail preview error",
            &format!(
                "<h1>Mail preview error</h1><p>{}</p>",
                escape_html(&error.to_string())
            ),
        )),
    )
        .into_response()
}

fn escape_html(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&#39;"),
            _ => escaped.push(ch),
        }
    }
    escaped
}

fn parse_mailbox(address: &str) -> Result<Mailbox, MailError> {
    address.parse().map_err(|source| MailError::InvalidAddress {
        address: address.to_owned(),
        source,
    })
}

/// Canonical, case-insensitive bare address used as the suppression / token key.
///
/// Strips any display name (`Ada <ada@example.com>` → `ada@example.com`) and
/// lowercases, so an opt-out matches future sends regardless of formatting.
/// Falls back to the trimmed, lowercased input when the address cannot be parsed.
fn canonical_subscriber(recipient: &str) -> String {
    parse_mailbox(recipient).map_or_else(
        |_| recipient.trim().to_ascii_lowercase(),
        |mailbox| mailbox.email.to_string().to_ascii_lowercase(),
    )
}

/// The html/text body of a message, before any attachment wrapping is
/// decided. Kept as an enum so the attachment-less code path can hand a
/// `SinglePart` straight to `Message::builder().singlepart(...)` exactly as
/// it did before attachments existed — a `MultiPart::mixed()` wrapper is
/// only introduced when there is at least one attachment.
enum MailBodyPart {
    Single(SinglePart),
    Multi(MultiPart),
}

fn lettre_body_part(mail: &Mail) -> Result<MailBodyPart, MailError> {
    match (&mail.text, &mail.html) {
        (Some(text), Some(html)) => Ok(MailBodyPart::Multi(
            MultiPart::alternative()
                .singlepart(SinglePart::plain(text.clone()))
                .singlepart(SinglePart::html(html.clone())),
        )),
        (Some(text), None) => Ok(MailBodyPart::Single(SinglePart::plain(text.clone()))),
        (None, Some(html)) => Ok(MailBodyPart::Single(SinglePart::html(html.clone()))),
        (None, None) => Err(MailError::InvalidMessage(
            "mail must include html or text body".to_owned(),
        )),
    }
}

fn lettre_attachment_part(attachment: &MailAttachment) -> Result<SinglePart, MailError> {
    let content_type = ContentType::parse(&attachment.content_type).map_err(|error| {
        MailError::InvalidMessage(format!(
            "attachment {:?} has invalid content type {:?}: {error}",
            attachment.filename, attachment.content_type
        ))
    })?;
    // Force base64 regardless of content: lettre's automatic encoder picks
    // `7bit` for short ASCII byte buffers, but attachments must always carry
    // a `base64` Content-Transfer-Encoding per the framework's contract.
    #[allow(
        clippy::expect_used,
        reason = "infallible: base64 encoding is always valid for any byte buffer"
    )]
    let body =
        LettreBody::new_with_encoding(attachment.bytes.clone(), ContentTransferEncoding::Base64)
            .expect("base64 encoding is always valid for any byte buffer");
    Ok(LettreAttachment::new(attachment.filename.clone()).body(body, content_type))
}

fn lettre_message(mail: &Mail) -> Result<Message, MailError> {
    let from = mail
        .from
        .as_deref()
        .ok_or_else(|| MailError::InvalidMessage("mail from address is required".to_owned()))?;
    let mut builder = Message::builder().from(parse_mailbox(from)?);
    for to in &mail.to {
        builder = builder.to(parse_mailbox(to)?);
    }
    if let Some(reply_to) = &mail.reply_to {
        builder = builder.reply_to(parse_mailbox(reply_to)?);
    }
    builder = builder.subject(mail.subject.clone());

    for (name, value) in &mail.extra_headers {
        use lettre::message::header::{HeaderName, HeaderValue};
        match HeaderName::new_from_ascii(name.clone()) {
            Ok(header_name) => {
                builder = builder.raw_header(HeaderValue::new(header_name, value.clone()));
            }
            Err(error) => {
                tracing::warn!(
                    header_name = %name,
                    error = %error,
                    "skipping mail header with invalid name"
                );
            }
        }
    }

    let body_part = lettre_body_part(mail)?;

    if mail.attachments.is_empty() {
        return Ok(match body_part {
            MailBodyPart::Multi(multi) => builder.multipart(multi)?,
            MailBodyPart::Single(single) => builder.singlepart(single)?,
        });
    }

    let mut mixed = match body_part {
        MailBodyPart::Multi(multi) => MultiPart::mixed().multipart(multi),
        MailBodyPart::Single(single) => MultiPart::mixed().singlepart(single),
    };
    for attachment in &mail.attachments {
        mixed = mixed.singlepart(lettre_attachment_part(attachment)?);
    }
    Ok(builder.multipart(mixed)?)
}

struct InterceptedMailTransport {
    inner: Arc<dyn MailTransport>,
    interceptor: Arc<dyn crate::interceptor::MailInterceptor>,
}

impl MailTransport for InterceptedMailTransport {
    fn send<'a>(
        &'a self,
        mail: Mail,
    ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
        Box::pin(async move {
            let inner = Arc::clone(&self.inner);
            let mail_for_next = mail.clone();
            let next = Box::pin(async move { inner.send(mail_for_next).await });
            self.interceptor.intercept(&mail, next).await
        })
    }

    fn is_disabled(&self) -> bool {
        self.inner.is_disabled()
    }
}

/// Install the configured mailer into app state.
///
/// Picks up a runtime-installed [`MailDeliveryQueueHandle`] from
/// [`AppState`] extensions when present, so plugins (Harvest, Redis-backed,
/// etc.) can register durable delivery before this runs. In `prod` with a
/// non-`Disabled` transport, startup fails when neither a durable queue nor
/// [`MailConfig::allow_in_process_deliver_later_in_production`] is set, unless
/// `enforce_durable_guard` is `false` (used by short-lived contexts like
/// static-site builds where `deliver_later` semantics don't apply).
///
/// # Errors
///
/// Returns an Autumn error when the configured transport cannot be created or
/// when the production `deliver_later` guard is not satisfied.
#[allow(clippy::too_many_lines)]
pub(crate) fn install_mailer(
    state: &AppState,
    config: &MailConfig,
    enforce_durable_guard: bool,
) -> AutumnResult<()> {
    let resilience = state
        .extension::<crate::config::AutumnConfig>()
        .map(|c| Arc::new(c.resilience.clone()));
    let mut mailer =
        Mailer::from_config_inner(config, resilience).map_err(AutumnError::service_unavailable)?;

    if let Some(interceptor) = state.extension::<Arc<dyn crate::interceptor::MailInterceptor>>() {
        mailer.transport = Arc::new(InterceptedMailTransport {
            inner: Arc::clone(&mailer.transport),
            interceptor: (*interceptor).clone(),
        });
    }

    let in_production = matches!(state.profile(), "prod" | "production");
    let transport_sends_mail = config.transport != Transport::Disabled;

    // Honor the disabled transport contract: if the operator turned mail off
    // for this profile (tests, review apps, etc.), `deliver_later` must also
    // be a no-op — even when a durable queue was registered globally.
    if transport_sends_mail {
        let queue_handle = state.extension::<MailDeliveryQueueHandle>();
        if let Some(handle) = queue_handle.as_ref() {
            mailer.delivery_queue = Some(Arc::clone(handle.inner()));
        }
    }

    if enforce_durable_guard && in_production && transport_sends_mail {
        let has_durable_queue = mailer.delivery_queue.is_some();
        if !has_durable_queue && !config.allow_in_process_deliver_later_in_production {
            return Err(AutumnError::service_unavailable_msg(
                "mail.deliver_later has no durable backend in prod: register a MailDeliveryQueueHandle on AppState or set mail.allow_in_process_deliver_later_in_production = true to opt into the in-process Tokio fallback",
            ));
        }
        if !has_durable_queue {
            tracing::warn!(
                "mail.deliver_later is using the in-process Tokio fallback in prod; this is acknowledged via mail.allow_in_process_deliver_later_in_production but is not durable across restarts or replicas"
            );
        }
    }

    // ── List-Unsubscribe wiring ──────────────────────────────────────────────
    let base_url = config
        .unsubscribe_base_url
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty());
    let mailto = config
        .unsubscribe_mailto
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty());
    let unsubscribe_configured = base_url.is_some() || mailto.is_some();

    // Resolve the suppression backend: an explicitly registered handle wins;
    // otherwise auto-wire a Diesel-backed store when a DB pool is available.
    let suppression: Option<Arc<dyn SuppressionStore>> = {
        let explicit = state
            .extension::<SuppressionStoreHandle>()
            .map(|handle| Arc::clone(handle.inner()));
        #[cfg(feature = "db")]
        let resolved = explicit.or_else(|| {
            state
                .pool()
                .map(|pool| Arc::new(db_suppression::DbSuppressionStore::new(pool.clone())) as _)
        });
        #[cfg(not(feature = "db"))]
        let resolved = explicit;
        resolved
    };

    // Fail closed: any mailer that declares `list_unsubscribe` needs a place to
    // point the unsubscribe link/mailto, or Gmail/Yahoo will reject the mail.
    // Skipped when the transport is disabled — no list mail is emitted, so the
    // disabled-transport contract (review apps, tests) can boot without it.
    if transport_sends_mail
        && unsubscribe_config_fail_closed(
            enforce_durable_guard,
            in_production,
            has_list_unsubscribe_mailers(),
            unsubscribe_configured,
        )
    {
        return Err(AutumnError::service_unavailable_msg(
            "a #[mailer] declares list_unsubscribe but neither mail.unsubscribe_base_url nor mail.unsubscribe_mailto is configured: set at least one so RFC 8058 List-Unsubscribe headers can be emitted",
        ));
    }

    // Fail closed: when we will actually emit one-click links (active transport,
    // a list mailer, and a base URL), the endpoint must be able to record
    // opt-outs — otherwise a successful unsubscribe POST is a silent no-op.
    if enforce_durable_guard
        && in_production
        && transport_sends_mail
        && has_list_unsubscribe_mailers()
        && base_url.is_some()
        && suppression.is_none()
    {
        return Err(AutumnError::service_unavailable_msg(
            "mail.unsubscribe_base_url is set but no suppression backend is available: configure a database pool or register a SuppressionStore so one-click unsubscribes can be persisted",
        ));
    }

    // Warn (don't fail — a custom route is a valid choice) when one-click links
    // will be advertised but the built-in endpoint is not opted in. We can't see
    // app-registered routes here, so this is a heads-up, not a hard gate.
    if in_production
        && transport_sends_mail
        && has_list_unsubscribe_mailers()
        && base_url.is_some()
        && !config.mount_unsubscribe_endpoint
    {
        tracing::warn!(
            target: "mail",
            path = UNSUBSCRIBE_PATH,
            "list mail will advertise one-click unsubscribe URLs but the default endpoint is not mounted; call AppBuilder::mount_unsubscribe_endpoint() or serve the path yourself"
        );
    }

    if unsubscribe_configured || suppression.is_some() {
        let signing_keys = Arc::new(crate::security::config::resolve_signing_keys(
            &state
                .extension::<crate::config::AutumnConfig>()
                .map(|c| c.security.signing_secret.clone())
                .unwrap_or_default(),
        ));
        let ttl_days = config.unsubscribe_token_ttl_days;
        let make_runtime = || UnsubscribeRuntime {
            base_url: base_url.map(str::to_owned),
            mailto: mailto.map(str::to_owned),
            signing_keys: Arc::clone(&signing_keys),
            ttl_days,
            suppression: suppression.clone(),
        };
        // Always share the wiring with the endpoint handler (mounted whenever an
        // unsubscribe destination is configured, independent of transport) so a
        // live unsubscribe link never 404s. Only the *sender* skips when the
        // transport is intentionally a no-op.
        state.insert_extension(make_runtime());
        if transport_sends_mail {
            mailer.unsubscribe = Some(Arc::new(make_runtime()));
        }
    }

    // ── Bounce/complaint suppression wiring (issue #1247) ────────────────────
    // Zero-config: default to an in-memory store so the detect→suppress loop
    // works out of the box on a single instance. An explicitly registered
    // handle (e.g. a Postgres-backed `PgSuppressionStore` via
    // `AppBuilder::with_mail_suppression_store`) wins. Unlike List-Unsubscribe
    // suppression, no db-backed store is auto-wired: `send()` consults this on
    // *every* message, so silently pointing it at a table that may not exist
    // would break all outbound mail — durable backends are opt-in.
    //
    // The resolved handle is registered on `AppState` so inbound bounce/complaint
    // handlers can share the exact store the `Mailer` consults.
    if transport_sends_mail {
        let handle = state
            .extension::<suppression::SuppressionStoreHandle>()
            .map_or_else(
                || {
                    let handle = suppression::SuppressionStoreHandle::new(
                        suppression::InMemorySuppressionStore::new(),
                    );
                    state.insert_extension(handle.clone());
                    handle
                },
                |arc| (*arc).clone(),
            );
        mailer.suppression = Some(Arc::clone(handle.inner()));
    }

    state.insert_extension(mailer);
    Ok(())
}

/// Run the optional [`MailDeliveryQueue`] factory and install the configured
/// mailer.
///
/// Centralizes the wiring used by every [`AppBuilder`](crate::app::AppBuilder)
/// build path: optionally invoke `queue_factory` against the live `AppState`,
/// register the resulting [`MailDeliveryQueueHandle`], then call
/// [`install_mailer`]. The factory is skipped entirely when
/// `enforce_durable_guard` is `false` (static-site builds), since the queue
/// may capture infrastructure (Redis, Harvest, etc.) that isn't available in
/// the asset-build environment.
///
/// # Errors
///
/// Propagates errors from the queue factory and from [`install_mailer`].
pub(crate) fn install_mailer_with_factory<F>(
    state: &AppState,
    config: &MailConfig,
    queue_factory: Option<F>,
    enforce_durable_guard: bool,
) -> AutumnResult<()>
where
    F: FnOnce(&AppState) -> AutumnResult<Arc<dyn MailDeliveryQueue>>,
{
    // Honor the disabled transport contract: a profile that turned mail off
    // (tests, review apps, etc.) must not open queue infrastructure either,
    // since all sends — immediate and deferred — are supposed to be no-ops.
    let transport_sends_mail = config.transport != Transport::Disabled;
    if enforce_durable_guard
        && transport_sends_mail
        && let Some(factory) = queue_factory
    {
        let queue = factory(state)?;
        state.insert_extension(MailDeliveryQueueHandle::from_arc(queue));
    }
    install_mailer(state, config, enforce_durable_guard)
}

// ── Default one-click unsubscribe endpoint ───────────────────────────────────

#[derive(Deserialize)]
struct UnsubscribeParams {
    #[serde(default)]
    token: String,
}

/// Router for the framework's default unsubscribe endpoint.
///
/// Mounted automatically when `mail.unsubscribe_base_url` or
/// `mail.unsubscribe_mailto` is configured, unless the app registers its own
/// route at [`UNSUBSCRIBE_PATH`] (the documented override hook). Requires no
/// end-user auth; the global rate-limit layer applies.
pub(crate) fn unsubscribe_router() -> axum::Router<AppState> {
    axum::Router::new().route(
        UNSUBSCRIBE_PATH,
        axum::routing::get(unsubscribe_get_handler).post(unsubscribe_post_handler),
    )
}

/// RFC 8058 one-click POST: verify the token and record the suppression.
async fn unsubscribe_post_handler(
    axum::extract::State(state): axum::extract::State<AppState>,
    axum::extract::Query(params): axum::extract::Query<UnsubscribeParams>,
    body: String,
) -> Response {
    // RFC 8058 §3.1: the one-click POST carries `List-Unsubscribe=One-Click`.
    // Requiring it avoids recording opt-outs from arbitrary POSTs to the URL
    // (e.g. link scanners that don't send the body).
    if !is_one_click_body(&body) {
        return (
            axum::http::StatusCode::BAD_REQUEST,
            "expected List-Unsubscribe=One-Click body",
        )
            .into_response();
    }
    let Some(runtime) = state.extension::<UnsubscribeRuntime>() else {
        return (
            axum::http::StatusCode::NOT_FOUND,
            "unsubscribe is not configured",
        )
            .into_response();
    };
    match unsubscribe::verify_token(&runtime.signing_keys, &params.token, current_unix_time()) {
        Ok(decoded) => {
            let Some(store) = runtime.suppression.as_ref() else {
                // No backend to record the opt-out — never confirm an unsubscribe
                // we cannot actually honor.
                tracing::error!(
                    target: "mail",
                    "unsubscribe POST received but no suppression backend is configured"
                );
                return (
                    axum::http::StatusCode::SERVICE_UNAVAILABLE,
                    "unsubscribe storage is not configured",
                )
                    .into_response();
            };
            if let Err(error) = store.suppress(&decoded.subscriber, &decoded.list_id).await {
                tracing::error!(error = %error, "failed to record unsubscribe suppression");
                return (
                    axum::http::StatusCode::INTERNAL_SERVER_ERROR,
                    "could not process unsubscribe",
                )
                    .into_response();
            }
            tracing::info!(
                target: "mail",
                list_id = %decoded.list_id,
                outcome = "unsubscribed",
                "recorded one-click unsubscribe"
            );
            (
                axum::http::StatusCode::OK,
                Html(unsubscribe_confirmation_html(&decoded.list_id)),
            )
                .into_response()
        }
        Err(error) => (
            axum::http::StatusCode::BAD_REQUEST,
            Html(unsubscribe_error_html(&error.to_string())),
        )
            .into_response(),
    }
}

/// Whether a urlencoded body contains `List-Unsubscribe=One-Click` (RFC 8058).
fn is_one_click_body(body: &str) -> bool {
    body.split('&').any(|pair| {
        let mut kv = pair.splitn(2, '=');
        let key = kv.next().unwrap_or("");
        let value = kv.next().unwrap_or("");
        key.eq_ignore_ascii_case("List-Unsubscribe") && value.eq_ignore_ascii_case("One-Click")
    })
}

/// Click-through GET: render a minimal confirmation page with a one-click form.
async fn unsubscribe_get_handler(
    axum::extract::State(state): axum::extract::State<AppState>,
    axum::extract::Query(params): axum::extract::Query<UnsubscribeParams>,
) -> Response {
    let Some(runtime) = state.extension::<UnsubscribeRuntime>() else {
        return (
            axum::http::StatusCode::NOT_FOUND,
            "unsubscribe is not configured",
        )
            .into_response();
    };
    match unsubscribe::verify_token(&runtime.signing_keys, &params.token, current_unix_time()) {
        Ok(decoded) => Html(unsubscribe_form_html(&decoded.list_id, &params.token)).into_response(),
        Err(error) => (
            axum::http::StatusCode::BAD_REQUEST,
            Html(unsubscribe_error_html(&error.to_string())),
        )
            .into_response(),
    }
}

fn unsubscribe_form_html(list_id: &str, token: &str) -> String {
    // Relative action (`?token=…`) posts back to the current URL, preserving any
    // base-path prefix added by a reverse proxy.
    format!(
        "<!doctype html><html><head><meta charset=\"utf-8\"><title>Unsubscribe</title></head>\
         <body><h1>Unsubscribe</h1>\
         <p>Stop receiving <strong>{}</strong> emails?</p>\
         <form method=\"post\" action=\"?token={}\">\
         <input type=\"hidden\" name=\"List-Unsubscribe\" value=\"One-Click\">\
         <button type=\"submit\">Unsubscribe</button></form></body></html>",
        escape_html(list_id),
        escape_html(token),
    )
}

fn unsubscribe_confirmation_html(list_id: &str) -> String {
    format!(
        "<!doctype html><html><head><meta charset=\"utf-8\"><title>Unsubscribed</title></head>\
         <body><h1>You're unsubscribed</h1>\
         <p>You will no longer receive <strong>{}</strong> emails.</p></body></html>",
        escape_html(list_id),
    )
}

fn unsubscribe_error_html(detail: &str) -> String {
    format!(
        "<!doctype html><html><head><meta charset=\"utf-8\"><title>Unsubscribe</title></head>\
         <body><h1>Unsubscribe link is not valid</h1><p>{}</p></body></html>",
        escape_html(detail),
    )
}

/// Bounce/complaint mail suppression list (issue #1247).
///
/// Autumn already *detects* delivery failure: `inbound_mail` parses provider
/// bounce signals and spam complaints. This module closes the loop — it records
/// the addresses that hard-bounced or complained and has [`Mailer::send`] skip
/// them before transport, so a sending domain's reputation survives contact
/// with real recipients.
///
/// This is distinct from the recipient-initiated List-Unsubscribe suppression
/// in [`crate::mail::unsubscribe`] (issue #838): that keys on
/// `(subscriber, list_id)` and is driven by a user clicking "unsubscribe";
/// this keys on a bare address and is driven by a *provider-reported* failure.
///
/// # Backends
///
/// [`InMemorySuppressionStore`] is the zero-config default (process-local,
/// lost on restart — perfect for a single instance, tests, and review apps).
/// [`PgSuppressionStore`](suppression::PgSuppressionStore) (feature `db`) persists to a `mail_suppressions`
/// table for multi-instance deploys, mirroring the memory/durable split used
/// by sessions and jobs. That table is **not** auto-created — provision it
/// yourself (see [`PgSuppressionStore`](suppression::PgSuppressionStore)).
///
/// # Closing the loop
///
/// Wire the provided `record_inbound` handler into the inbound router's
/// `on_bounce` hook (or call [`SuppressionStore::suppress`] yourself) to turn a
/// parsed provider bounce into a suppression entry. autumn's `on_spam` signal
/// is an *inbound spam verdict*, not an outbound FBL complaint — see
/// `record_inbound` for why routing it here is a safe no-op rather than
/// suppressing the wrong address.
pub mod suppression {
    use std::future::Future;
    use std::pin::Pin;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU64, Ordering};

    use super::{MailError, canonical_subscriber};

    /// Why an address is on the suppression list.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum SuppressionReason {
        /// A permanent delivery failure (5xx SMTP / DSN hard bounce).
        HardBounce,
        /// A spam complaint / feedback-loop (FBL) report.
        Complaint,
        /// Added by an operator, not by a provider signal.
        Manual,
    }

    impl SuppressionReason {
        /// Stable lowercase token used in storage rows and log lines.
        #[must_use]
        pub const fn as_str(self) -> &'static str {
            match self {
                Self::HardBounce => "hard_bounce",
                Self::Complaint => "complaint",
                Self::Manual => "manual",
            }
        }
    }

    impl std::fmt::Display for SuppressionReason {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str(self.as_str())
        }
    }

    /// Persistent set of addresses that must not receive mail because they
    /// hard-bounced or filed a spam complaint.
    ///
    /// All three methods canonicalize the address (strip any display name and
    /// lowercase) so a suppression recorded as `Bounced@X.com` matches a later
    /// send to `Ada <bounced@x.com>`.
    pub trait SuppressionStore: Send + Sync {
        /// Returns `true` when `address` must not be delivered to.
        fn is_suppressed<'a>(
            &'a self,
            address: &'a str,
        ) -> Pin<Box<dyn Future<Output = Result<bool, MailError>> + Send + 'a>>;

        /// Record `address` on the suppression list (idempotent). A repeat call
        /// with a different `reason` updates the recorded reason.
        fn suppress<'a>(
            &'a self,
            address: &'a str,
            reason: SuppressionReason,
        ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>>;

        /// Remove `address` from the suppression list — the manual escape hatch
        /// (e.g. a recipient fixed their mailbox). No-op when absent.
        fn unsuppress<'a>(
            &'a self,
            address: &'a str,
        ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>>;
    }

    /// Cloneable handle to a [`SuppressionStore`] for storage on `AppState` and
    /// attachment to a [`Mailer`](crate::mail::Mailer).
    #[derive(Clone)]
    pub struct SuppressionStoreHandle(Arc<dyn SuppressionStore>);

    impl SuppressionStoreHandle {
        /// Wrap a store implementation.
        #[must_use]
        pub fn new(store: impl SuppressionStore + 'static) -> Self {
            Self(Arc::new(store))
        }

        /// Wrap an already-shared store implementation.
        #[must_use]
        pub fn from_arc(store: Arc<dyn SuppressionStore>) -> Self {
            Self(store)
        }

        /// Borrow the inner store.
        #[must_use]
        pub fn inner(&self) -> &Arc<dyn SuppressionStore> {
            &self.0
        }

        /// Consume the handle, yielding the shared store.
        #[must_use]
        pub fn into_inner(self) -> Arc<dyn SuppressionStore> {
            self.0
        }
    }

    impl std::fmt::Debug for SuppressionStoreHandle {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("SuppressionStoreHandle")
                .finish_non_exhaustive()
        }
    }

    /// In-memory [`SuppressionStore`] — the zero-config default.
    ///
    /// State is process-local and lost on restart; use [`PgSuppressionStore`]
    /// for multi-instance deploys that must share suppression across replicas.
    #[derive(Debug, Default, Clone)]
    pub struct InMemorySuppressionStore {
        entries: Arc<std::sync::Mutex<std::collections::HashMap<String, SuppressionReason>>>,
    }

    impl InMemorySuppressionStore {
        /// Create an empty in-memory store.
        #[must_use]
        pub fn new() -> Self {
            Self::default()
        }
    }

    impl SuppressionStore for InMemorySuppressionStore {
        fn is_suppressed<'a>(
            &'a self,
            address: &'a str,
        ) -> Pin<Box<dyn Future<Output = Result<bool, MailError>> + Send + 'a>> {
            Box::pin(async move {
                let key = canonical_subscriber(address);
                Ok(self
                    .entries
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .contains_key(&key))
            })
        }

        fn suppress<'a>(
            &'a self,
            address: &'a str,
            reason: SuppressionReason,
        ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
            Box::pin(async move {
                let key = canonical_subscriber(address);
                self.entries
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .insert(key, reason);
                Ok(())
            })
        }

        fn unsuppress<'a>(
            &'a self,
            address: &'a str,
        ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
            Box::pin(async move {
                let key = canonical_subscriber(address);
                self.entries
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .remove(&key);
                Ok(())
            })
        }
    }

    // ── Observability: a suppressed drop is never truly silent ───────────────
    static SUPPRESSED_SKIPS: AtomicU64 = AtomicU64::new(0);

    /// Recipients [`Mailer::send`](crate::mail::Mailer::send) has skipped as suppressed, process-wide.
    ///
    /// Counted since startup. Pair with the structured `outcome =
    /// "skipped_suppressed"` log line emitted per skip.
    #[must_use]
    pub fn suppressed_skips() -> u64 {
        SUPPRESSED_SKIPS.load(Ordering::Relaxed)
    }

    /// Record and log a skip. Internal to the `send` path.
    pub(crate) fn note_skip(canonical_address: &str) {
        SUPPRESSED_SKIPS.fetch_add(1, Ordering::Relaxed);
        tracing::info!(
            target: "mail",
            outcome = "skipped_suppressed",
            address = %canonical_address,
            "skipping suppressed recipient (hard bounce or complaint); \
             pass Mail::ignore_suppression() to override for critical mail"
        );
    }

    /// Provided inbound handler: turn a parsed provider bounce/complaint webhook
    /// into a suppression entry, closing the detect→suppress loop in one call.
    ///
    /// It only ever suppresses the *provider-reported failed/complaining
    /// address*, never `email.to` — on an inbound webhook `to` is the app's own
    /// inbound address, so suppressing it would let anyone who can POST to the
    /// endpoint knock arbitrary recipients off future sends.
    ///
    /// - A bounce (`email.is_bounce`) suppresses the provider-reported
    ///   [`bounced_address`](crate::inbound_mail::InboundEmail::bounced_address)
    ///   with [`SuppressionReason::HardBounce`]. A bounce flagged with no
    ///   address is logged and dropped (nothing suppressed).
    /// - A complaint suppresses
    ///   [`complained_address`](crate::inbound_mail::InboundEmail::complained_address)
    ///   with [`SuppressionReason::Complaint`] — populated only by parsers that
    ///   surface a genuine FBL complainant. autumn's built-in `on_spam` signal
    ///   is an *inbound spam verdict* (`X-Mailgun-Sflag`), not an outbound FBL
    ///   complaint, and carries no complainant address, so wiring `on_spam`
    ///   here is a safe no-op (logged) rather than suppressing the wrong party.
    ///
    /// Wire it into the inbound router (see the crate `suppression` module docs
    /// for the full shared-store example):
    ///
    /// ```rust,ignore
    /// InboundMailRouter::new()
    ///     .endpoint(InboundMailEndpointConfig::mailgun("/mail/inbound", key))
    ///     .on_bounce(|email| Box::pin(async move {
    ///         record_inbound(SUPPRESSION.get().unwrap().inner().as_ref(), &email).await?;
    ///         Ok(())
    ///     }));
    /// ```
    ///
    /// # Errors
    ///
    /// Propagates any [`MailError`] returned by the store while recording the
    /// suppression (e.g. a database backend being unavailable).
    #[cfg(feature = "inbound-mail")]
    pub async fn record_inbound(
        store: &dyn SuppressionStore,
        email: &crate::inbound_mail::InboundEmail,
    ) -> Result<(), MailError> {
        if email.is_bounce {
            // Only the provider-reported bounced address is the failed
            // recipient; `email.to` on a bounce webhook is the app's own
            // inbound address, so never suppress that.
            if let Some(addr) = email.bounced_address.as_deref() {
                store.suppress(addr, SuppressionReason::HardBounce).await?;
            } else {
                tracing::warn!(
                    target: "mail",
                    "inbound bounce webhook set is_bounce with no bounced_address; nothing suppressed"
                );
            }
            return Ok(());
        }
        // Complaint / FBL: suppress the genuine complainant only. Never fall
        // back to `email.to`. autumn's `on_spam` is an inbound spam verdict, not
        // an outbound complaint, so `complained_address` is `None` there and we
        // log rather than suppress the wrong address.
        if let Some(addr) = email.complained_address.as_deref() {
            store.suppress(addr, SuppressionReason::Complaint).await?;
        } else if email
            .spam_report
            .as_ref()
            .and_then(|r| r.verdict.as_deref())
            .is_some_and(|v| v.eq_ignore_ascii_case("yes"))
        {
            tracing::warn!(
                target: "mail",
                "inbound spam verdict carries no outbound complainant address; \
                 nothing suppressed (wire a real FBL/complaint source that \
                 populates InboundEmail::complained_address)"
            );
        }
        Ok(())
    }

    #[cfg(feature = "db")]
    pub use pg::PgSuppressionStore;

    #[cfg(feature = "db")]
    mod pg {
        use std::future::Future;
        use std::pin::Pin;

        use diesel::prelude::*;
        use diesel_async::AsyncPgConnection;
        use diesel_async::RunQueryDsl;
        use diesel_async::pooled_connection::deadpool::Pool;

        use super::super::canonical_subscriber;
        use super::{MailError, SuppressionReason, SuppressionStore};

        diesel::table! {
            mail_suppressions (address) {
                address -> Text,
                reason -> Text,
                suppressed_at -> Timestamptz,
            }
        }

        #[derive(Insertable)]
        #[diesel(table_name = mail_suppressions)]
        struct NewSuppression<'a> {
            address: &'a str,
            reason: &'a str,
        }

        /// Postgres-backed bounce/complaint [`SuppressionStore`].
        ///
        /// Suppression is shared across every instance that points at the same
        /// database.
        ///
        /// # Required table (no migration is shipped)
        ///
        /// This store does **not** create or migrate its table — provision it
        /// yourself (same convention as the List-Unsubscribe `mail_unsubscribes`
        /// store). Every `send` errors on the suppression lookup until it
        /// exists:
        ///
        /// ```sql
        /// CREATE TABLE mail_suppressions (
        ///     address       TEXT PRIMARY KEY,
        ///     reason        TEXT NOT NULL,
        ///     suppressed_at TIMESTAMPTZ NOT NULL DEFAULT now()
        /// );
        /// ```
        #[derive(Clone)]
        pub struct PgSuppressionStore {
            pool: Pool<AsyncPgConnection>,
        }

        impl PgSuppressionStore {
            /// Create a store backed by `pool`.
            #[must_use]
            pub const fn new(pool: Pool<AsyncPgConnection>) -> Self {
                Self { pool }
            }
        }

        impl SuppressionStore for PgSuppressionStore {
            fn is_suppressed<'a>(
                &'a self,
                address: &'a str,
            ) -> Pin<Box<dyn Future<Output = Result<bool, MailError>> + Send + 'a>> {
                Box::pin(async move {
                    let key = canonical_subscriber(address);
                    let mut conn = self.pool.get().await.map_err(|e| {
                        MailError::RuntimeUnavailable(format!("suppression pool: {e}"))
                    })?;
                    let count: i64 = mail_suppressions::table
                        .filter(mail_suppressions::address.eq(&key))
                        .count()
                        .get_result(&mut conn)
                        .await
                        .map_err(|e| {
                            MailError::RuntimeUnavailable(format!("suppression query: {e}"))
                        })?;
                    Ok(count > 0)
                })
            }

            fn suppress<'a>(
                &'a self,
                address: &'a str,
                reason: SuppressionReason,
            ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
                Box::pin(async move {
                    let key = canonical_subscriber(address);
                    let reason_str = reason.as_str();
                    let mut conn = self.pool.get().await.map_err(|e| {
                        MailError::RuntimeUnavailable(format!("suppression pool: {e}"))
                    })?;
                    diesel::insert_into(mail_suppressions::table)
                        .values(NewSuppression {
                            address: &key,
                            reason: reason_str,
                        })
                        .on_conflict(mail_suppressions::address)
                        .do_update()
                        // Refresh both the reason and the timestamp so a
                        // re-suppression (e.g. an old hard bounce now also a
                        // complaint) reflects the latest event, not stale data.
                        .set((
                            mail_suppressions::reason.eq(reason_str),
                            mail_suppressions::suppressed_at.eq(diesel::dsl::now),
                        ))
                        .execute(&mut conn)
                        .await
                        .map_err(|e| {
                            MailError::RuntimeUnavailable(format!("suppression insert: {e}"))
                        })?;
                    Ok(())
                })
            }

            fn unsuppress<'a>(
                &'a self,
                address: &'a str,
            ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
                Box::pin(async move {
                    let key = canonical_subscriber(address);
                    let mut conn = self.pool.get().await.map_err(|e| {
                        MailError::RuntimeUnavailable(format!("suppression pool: {e}"))
                    })?;
                    diesel::delete(
                        mail_suppressions::table.filter(mail_suppressions::address.eq(&key)),
                    )
                    .execute(&mut conn)
                    .await
                    .map_err(|e| {
                        MailError::RuntimeUnavailable(format!("suppression delete: {e}"))
                    })?;
                    Ok(())
                })
            }
        }
    }
}

/// Diesel-backed [`SuppressionStore`].
#[cfg(feature = "db")]
pub mod db_suppression {
    use std::future::Future;
    use std::pin::Pin;

    use diesel::prelude::*;
    use diesel_async::AsyncPgConnection;
    use diesel_async::RunQueryDsl;
    use diesel_async::pooled_connection::deadpool::Pool;

    use super::{MailError, SuppressionStore};

    diesel::table! {
        mail_unsubscribes (id) {
            id -> Int8,
            subscriber -> Text,
            list_id -> Text,
            unsubscribed_at -> Timestamptz,
        }
    }

    #[derive(Insertable)]
    #[diesel(table_name = mail_unsubscribes)]
    struct NewUnsubscribe<'a> {
        subscriber: &'a str,
        list_id: &'a str,
    }

    /// Postgres-backed suppression list keyed by `(subscriber, list_id)`.
    ///
    /// Backed by the `mail_unsubscribes` table provisioned by the migration that
    /// `autumn generate mailer --list-unsubscribe` writes into the app.
    #[derive(Clone)]
    pub struct DbSuppressionStore {
        pool: Pool<AsyncPgConnection>,
    }

    impl DbSuppressionStore {
        /// Create a store backed by `pool`.
        #[must_use]
        pub const fn new(pool: Pool<AsyncPgConnection>) -> Self {
            Self { pool }
        }
    }

    impl SuppressionStore for DbSuppressionStore {
        fn is_suppressed<'a>(
            &'a self,
            subscriber: &'a str,
            list_id: &'a str,
        ) -> Pin<Box<dyn Future<Output = Result<bool, MailError>> + Send + 'a>> {
            Box::pin(async move {
                let mut conn =
                    self.pool.get().await.map_err(|e| {
                        MailError::RuntimeUnavailable(format!("suppression pool: {e}"))
                    })?;
                let count: i64 = mail_unsubscribes::table
                    .filter(mail_unsubscribes::subscriber.eq(subscriber))
                    .filter(mail_unsubscribes::list_id.eq(list_id))
                    .count()
                    .get_result(&mut conn)
                    .await
                    .map_err(|e| {
                        MailError::RuntimeUnavailable(format!("suppression query: {e}"))
                    })?;
                Ok(count > 0)
            })
        }

        fn suppress<'a>(
            &'a self,
            subscriber: &'a str,
            list_id: &'a str,
        ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
            Box::pin(async move {
                let mut conn =
                    self.pool.get().await.map_err(|e| {
                        MailError::RuntimeUnavailable(format!("suppression pool: {e}"))
                    })?;
                diesel::insert_into(mail_unsubscribes::table)
                    .values(NewUnsubscribe {
                        subscriber,
                        list_id,
                    })
                    .on_conflict((mail_unsubscribes::subscriber, mail_unsubscribes::list_id))
                    .do_nothing()
                    .execute(&mut conn)
                    .await
                    .map_err(|e| {
                        MailError::RuntimeUnavailable(format!("suppression insert: {e}"))
                    })?;
                Ok(())
            })
        }
    }
}

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

    // ── CSS inlining (issue #1254) ────────────────────────────────────────

    #[test]
    fn html_contains_style_block_is_case_insensitive() {
        assert!(html_contains_style_block("<STYLE>.a{}</STYLE>"));
        assert!(html_contains_style_block("<p>x</p><style>.a{}</style>"));
        assert!(!html_contains_style_block("<p style=\"color:red\">x</p>"));
        assert!(!html_contains_style_block("just plain text, no tags"));
    }

    #[test]
    fn inline_css_applies_class_style_to_anchor() {
        // AC1: a `<style>` block + a class-styled `<a>` yields an equivalent
        // inline `style="…"` on the anchor.
        let html = r#"<style>.btn{color:#fff;background:#06c}</style><a class="btn">Go</a>"#;
        let out = inline_css_html(html).expect("inlining succeeds");
        // Inspect the `<a …>` opening tag specifically so every assertion is
        // discriminating: `#fff`/`#06c` also appear in the retained `<style>`
        // block, so a no-op would pass a bare `out.contains(...)`.
        let anchor = out
            .split("<a")
            .nth(1)
            .expect("an <a> tag is present in the output");
        let anchor_open = &anchor[..anchor.find('>').expect("anchor tag closes")];
        assert!(
            anchor_open.contains("style="),
            "anchor must gain an inline style attribute; got tag: {anchor_open}"
        );
        assert!(
            anchor_open.contains("#fff"),
            "anchor's inline style must carry the color rule; got tag: {anchor_open}"
        );
        assert!(
            anchor_open.contains("#06c") || anchor_open.contains("background"),
            "anchor's inline style must carry the background rule; got tag: {anchor_open}"
        );
    }

    #[test]
    fn inline_css_applies_class_style_to_table() {
        // AC7: a class-styled `<table>` gains the expected inline style.
        let html = r#"<style>.wrap{width:600px;background:#eee}</style><table class="wrap"><tr><td>x</td></tr></table>"#;
        let out = inline_css_html(html).expect("inlining succeeds");
        let table = out
            .split("<table")
            .nth(1)
            .expect("a <table> tag is present in the output");
        let table_open = &table[..table.find('>').expect("table tag closes")];
        assert!(
            table_open.contains("style=") && table_open.contains("600px"),
            "table must carry an inline style with the width rule; got tag: {table_open}"
        );
    }

    #[test]
    #[allow(
        clippy::literal_string_with_formatting_args,
        reason = "CSS rule braces are literal HTML, not format placeholders"
    )]
    fn inline_css_emits_outlook_width_height_attributes() {
        // Outlook-family clients ignore CSS `width`/`height`, so the inliner must
        // also emit the presentational HTML `width`/`height` attributes on the
        // supported elements (`table`/`td`/`th`/`img`) — not only the CSS `style=`.
        let html = r#"<style>table{width:600px}img{height:40px}</style><table><tr><td><img src="/x.png"></td></tr></table>"#;
        let out = inline_css_html(html).expect("inlining succeeds");

        let table_open = {
            let table = out
                .split("<table")
                .nth(1)
                .expect("a <table> tag is present in the output");
            &table[..table.find('>').expect("table tag closes")]
        };
        // Discriminating: the CSS style must be present AND the HTML attribute too.
        assert!(
            table_open.contains("style=") && table_open.contains("600px"),
            "table must still carry the inline CSS width; got tag: {table_open}"
        );
        assert!(
            table_open.contains(r#"width="600""#),
            "table must gain the presentational HTML width attribute Outlook needs; got tag: {table_open}"
        );

        let img_open = {
            let img = out
                .split("<img")
                .nth(1)
                .expect("an <img> tag is present in the output");
            &img[..img.find('>').expect("img tag closes")]
        };
        assert!(
            img_open.contains("style=") && img_open.contains("40px"),
            "img must still carry the inline CSS height; got tag: {img_open}"
        );
        assert!(
            img_open.contains(r#"height="40""#),
            "img must gain the presentational HTML height attribute Outlook needs; got tag: {img_open}"
        );
    }

    #[test]
    fn inline_css_passthrough_without_style_block_is_byte_identical() {
        // AC3: bodies already fully inlined (no `<style>`) pass through unchanged.
        let html = r#"<p style="color:red">Hello</p><a href="/x">link</a>"#;
        let out = inline_css_html(html).expect("no-op inlining succeeds");
        assert_eq!(out, html, "no-<style> body must be returned unchanged");
    }

    #[test]
    #[allow(
        clippy::literal_string_with_formatting_args,
        reason = "CSS rule braces are literal HTML, not format placeholders"
    )]
    fn inline_css_retains_link_stylesheet_tags() {
        // We never fetch `<link>` stylesheets, so the `<link rel="stylesheet">`
        // tag must survive inlining rather than being silently dropped from the
        // delivered body — otherwise a message combining an embedded `<style>`
        // with a linked stylesheet would lose the linked CSS. The embedded rule
        // is still inlined onto the element.
        let html = r#"<style>.x{color:red}</style><link rel="stylesheet" href="https://example.com/app.css"><p class="x">Hi</p>"#;
        let out = inline_css_html(html).expect("inlining succeeds");
        assert!(
            out.contains("<link") && out.contains(r#"rel="stylesheet""#),
            "the <link rel=\"stylesheet\"> tag must be preserved; got: {out}"
        );
        assert!(
            out.contains("app.css"),
            "the linked stylesheet href must be preserved; got: {out}"
        );
        let para = out
            .split("<p")
            .nth(1)
            .expect("a <p> tag is present in the output");
        let para_open = &para[..para.find('>').expect("paragraph tag closes")];
        assert!(
            para_open.contains("style=") && para_open.contains("red"),
            "the embedded rule must still be inlined onto the paragraph; got tag: {para_open}"
        );
    }

    #[test]
    #[allow(
        clippy::literal_string_with_formatting_args,
        reason = "CSS rule braces are literal HTML, not format placeholders"
    )]
    fn inline_css_is_idempotent() {
        // AC3: inlining twice equals inlining once.
        let html = r#"<style>.btn{color:#fff}p{margin:0}</style><a class="btn">Go</a><p>hi</p>"#;
        let once = inline_css_html(html).expect("first pass");
        let twice = inline_css_html(&once).expect("second pass");
        assert_eq!(once, twice, "inlining must be idempotent");
    }

    #[test]
    #[allow(
        clippy::literal_string_with_formatting_args,
        reason = "CSS rule braces are literal HTML, not format placeholders"
    )]
    fn inline_css_retains_uninlinable_media_queries() {
        // AC5: `@media` rules that cannot be inlined survive in a retained
        // `<style>` block rather than being dropped.
        let html = r#"<style>.btn{color:#fff}@media (max-width:600px){.btn{color:#000}}</style><a class="btn">Go</a>"#;
        let out = inline_css_html(html).expect("inlining succeeds");
        assert!(
            out.contains("@media") && out.contains("max-width"),
            "the @media rule must be preserved in a retained <style> block; got: {out}"
        );
        // And the inlinable rule was still applied to the element.
        assert!(
            out.contains("<a") && out.contains("style="),
            "the inlinable rule must still be inlined onto the anchor; got: {out}"
        );
    }

    #[test]
    #[allow(
        clippy::literal_string_with_formatting_args,
        reason = "CSS rule braces are literal HTML, not format placeholders"
    )]
    fn inline_css_fragment_body_stays_a_fragment() {
        // A no-layout FRAGMENT body must stay a fragment after inlining:
        // opting into CSS inlining must not promote it into a full document by
        // introducing synthetic `<html>`/`<head>`/`<body>` wrappers. The class
        // rule is still inlined onto the element. See issue #1254 / PR #1681.
        let html = r#"<style>.x{color:red}</style><p class="x">Hi</p>"#;
        let out = inline_css_html(html).expect("inlining succeeds");
        assert!(
            !out.to_ascii_lowercase().contains("<html")
                && !out.to_ascii_lowercase().contains("<body")
                && !out.to_ascii_lowercase().contains("<head"),
            "fragment body must not gain document wrappers; got: {out}"
        );
        let para = out
            .split("<p")
            .nth(1)
            .expect("a <p> tag is present in the output");
        let para_open = &para[..para.find('>').expect("paragraph tag closes")];
        assert!(
            para_open.contains("style=") && para_open.contains("red"),
            "the class rule must be inlined onto the paragraph; got tag: {para_open}"
        );
    }

    #[test]
    #[allow(
        clippy::literal_string_with_formatting_args,
        reason = "CSS rule braces are literal HTML, not format placeholders"
    )]
    fn inline_css_fragment_body_retains_media_query_without_wrapping() {
        // AC5 + fragment: a FRAGMENT body with an un-inlinable `@media` rule
        // must stay a fragment (no synthetic wrappers) yet still carry the
        // retained `@media` block. Document-mode inlining hoists that retained
        // `<style>` into the synthetic `<head>`; the unwrap must fold it back
        // into the fragment rather than dropping it. See PR #1681.
        let html = r#"<style>.btn{color:#fff}@media (max-width:600px){.btn{color:#000}}</style><a class="btn">Go</a>"#;
        let out = inline_css_html(html).expect("inlining succeeds");
        assert!(
            !out.to_ascii_lowercase().contains("<html")
                && !out.to_ascii_lowercase().contains("<body")
                && !out.to_ascii_lowercase().contains("<head"),
            "fragment body must not gain document wrappers; got: {out}"
        );
        assert!(
            out.contains("@media") && out.contains("max-width"),
            "the retained @media block must survive the unwrap; got: {out}"
        );
        let anchor = out
            .split("<a")
            .nth(1)
            .expect("an <a> tag is present in the output");
        let anchor_open = &anchor[..anchor.find('>').expect("anchor tag closes")];
        assert!(
            anchor_open.contains("style=") && anchor_open.contains("#fff"),
            "the inlinable rule must still be inlined onto the anchor; got tag: {anchor_open}"
        );
    }

    #[test]
    #[allow(
        clippy::literal_string_with_formatting_args,
        reason = "CSS rule braces are literal HTML, not format placeholders"
    )]
    fn inline_css_full_document_body_stays_a_document() {
        // A FULL-DOCUMENT body keeps document-mode handling: its authored
        // `<html>`/`<body>` structure survives and the class rule is inlined.
        let html = r#"<html><head><style>.x{color:red}</style></head><body><p class="x">Hi</p></body></html>"#;
        let out = inline_css_html(html).expect("inlining succeeds");
        assert!(
            out.to_ascii_lowercase().contains("<html")
                && out.to_ascii_lowercase().contains("<body"),
            "full-document body must retain its structure; got: {out}"
        );
        let para = out
            .split("<p")
            .nth(1)
            .expect("a <p> tag is present in the output");
        let para_open = &para[..para.find('>').expect("paragraph tag closes")];
        assert!(
            para_open.contains("style=") && para_open.contains("red"),
            "the class rule must be inlined onto the paragraph; got tag: {para_open}"
        );
    }

    #[test]
    fn inline_css_stripped_style_renders_same_computed_styling() {
        // AC7: a `<style>`-stripped copy of the inlined output renders the same
        // computed styling — i.e. the visual styling lives in the inline
        // `style="…"` attribute, independent of any `<head>`/`<style>` the
        // client might drop.
        let html = r#"<style>.btn{color:#fff;padding:8px}</style><a class="btn">Go</a>"#;
        let inlined = inline_css_html(html).expect("inlining succeeds");

        // Strip every <style>…</style> block (what Gmail/Outlook effectively do).
        let mut stripped = String::new();
        let mut rest = inlined.as_str();
        while let Some(start) = rest.to_ascii_lowercase().find("<style") {
            stripped.push_str(&rest[..start]);
            let after = &rest[start..];
            let end = after
                .to_ascii_lowercase()
                .find("</style>")
                .map_or(after.len(), |e| e + "</style>".len());
            rest = &after[end..];
        }
        stripped.push_str(rest);

        // The anchor's inline style survives the strip, so styling is unchanged.
        let anchor = stripped
            .split("<a")
            .nth(1)
            .expect("anchor present after stripping <style>");
        let anchor_open = &anchor[..anchor.find('>').expect("anchor closes")];
        assert!(
            anchor_open.contains("style=") && anchor_open.contains("#fff"),
            "computed styling must be carried inline so a style-stripped copy looks identical; got: {anchor_open}"
        );
    }

    // ── Preview honours send-time CSS inlining (issue #1254) ──────────────

    /// Render `show_template_preview` for a single registered preview and return
    /// the full response body as a string. A [`Mailer`] is installed on the
    /// state so the handler can reuse the send-time inlining decision — mirrors
    /// the app build, where the mailer is always present before the preview
    /// registry.
    async fn preview_body_for(preview: MailPreview) -> String {
        let state = crate::AppState::for_test();
        state.insert_extension(MailPreviewRegistry::new(vec![preview]));
        let mailer = Mailer::builder()
            .build()
            .expect("log-transport mailer builds");
        state.insert_extension(mailer);

        let response = show_template_preview(&state, "test", "styled");
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("preview body collects");
        String::from_utf8(bytes.to_vec()).expect("preview body is utf-8")
    }

    /// Escaped opening `<a …>` tag of the email body as it appears in the
    /// preview page (the email HTML is HTML-escaped into an `<iframe srcdoc>`).
    /// Isolating the anchor keeps assertions discriminating: the colour rule
    /// also lives in the retained/original `<style>` block.
    fn escaped_anchor_open_tag(body: &str) -> String {
        let after = body
            .split("&lt;a")
            .nth(1)
            .expect("an <a> tag is present in the escaped preview body");
        let open = &after[..after.find("&gt;").expect("anchor tag closes")];
        open.to_owned()
    }

    #[tokio::test]
    #[allow(
        clippy::literal_string_with_formatting_args,
        reason = "CSS rule braces are literal HTML, not format placeholders"
    )]
    async fn preview_inlines_style_block_when_inlining_enabled() {
        // A preview whose Mail opts into inlining must reflect what strict
        // clients receive: the `.btn` class rule inlined onto the anchor.
        let preview = MailPreview::new("test", "styled", || {
            Mail::builder()
                .to("user@example.com")
                .subject("Styled")
                .html(r#"<style>.btn{color:#ff0000}</style><a class="btn">Go</a>"#)
                .inline_css(true)
                .build()
                .expect("preview mail builds")
        });

        let body = preview_body_for(preview).await;
        let anchor = escaped_anchor_open_tag(&body);
        assert!(
            anchor.contains("style="),
            "preview must inline the <style> block onto the anchor; got tag: {anchor}"
        );
        assert!(
            anchor.contains("#ff0000"),
            "the .btn colour rule must be carried inline; got tag: {anchor}"
        );
    }

    #[tokio::test]
    #[allow(
        clippy::literal_string_with_formatting_args,
        reason = "CSS rule braces are literal HTML, not format placeholders"
    )]
    async fn preview_leaves_style_block_raw_when_inlining_disabled() {
        // The discriminating counterpart: with inlining off the anchor keeps no
        // inline style and the raw `<style>` block survives untouched.
        let preview = MailPreview::new("test", "styled", || {
            Mail::builder()
                .to("user@example.com")
                .subject("Styled")
                .html(r#"<style>.btn{color:#ff0000}</style><a class="btn">Go</a>"#)
                .inline_css(false)
                .build()
                .expect("preview mail builds")
        });

        let body = preview_body_for(preview).await;
        let anchor = escaped_anchor_open_tag(&body);
        assert!(
            !anchor.contains("style="),
            "inlining is off, so the anchor must not gain an inline style; got tag: {anchor}"
        );
        assert!(
            body.contains("&lt;style&gt;"),
            "the raw <style> block must survive when inlining is off"
        );
    }

    #[test]
    fn mail_builder_inline_css_sets_per_message_override() {
        let on = Mail::builder()
            .to("a@example.com")
            .subject("s")
            .html("<p>x</p>")
            .inline_css(true)
            .build()
            .expect("valid mail");
        assert_eq!(on.inline_css, Some(true));

        let off = Mail::builder()
            .to("a@example.com")
            .subject("s")
            .html("<p>x</p>")
            .inline_css(false)
            .build()
            .expect("valid mail");
        assert_eq!(off.inline_css, Some(false));

        let unset = Mail::builder()
            .to("a@example.com")
            .subject("s")
            .html("<p>x</p>")
            .build()
            .expect("valid mail");
        assert_eq!(
            unset.inline_css, None,
            "unset builder must defer to the mailer/config default"
        );
    }

    #[test]
    fn mail_config_inline_css_defaults_off() {
        assert!(
            !MailConfig::default().inline_css,
            "inlining must default off so existing apps are unaffected"
        );
    }

    // ── Attachments (issue #1256): pinning tests ──────────────────────────
    //
    // These prove attachment support introduces zero byte-for-byte regression
    // to attachment-less mail. `pinned_render_eml_no_attachments` is a frozen
    // copy of `render_eml`'s pre-attachment body captured before any
    // attachment code was added. Do not "fix" drift here — a diff against
    // this function IS the regression signal (AC: "pure additive, no
    // regression to existing email output").

    fn pinned_render_eml_no_attachments(mail: &Mail) -> String {
        let mut out = String::new();
        if let Some(from) = &mail.from {
            out.push_str("From: ");
            out.push_str(from);
            out.push('\n');
        }
        for to in &mail.to {
            out.push_str("To: ");
            out.push_str(to);
            out.push('\n');
        }
        if let Some(reply_to) = &mail.reply_to {
            out.push_str("Reply-To: ");
            out.push_str(reply_to);
            out.push('\n');
        }
        out.push_str("Date: ");
        out.push_str("PINNED-DATE");
        out.push('\n');
        out.push_str("Message-Id: <");
        out.push_str("PINNED-ID");
        out.push_str("@autumn.local>\n");
        out.push_str("Subject: ");
        out.push_str(&mail.subject);
        out.push('\n');
        for (name, value) in &mail.extra_headers {
            out.push_str(name);
            out.push_str(": ");
            out.push_str(value);
            out.push('\n');
        }
        out.push_str("MIME-Version: 1.0\n");
        if mail.html.is_some() && mail.text.is_some() {
            out.push_str("Content-Type: multipart/alternative; boundary=\"autumn-mail\"\n\n");
            if let Some(text) = &mail.text {
                out.push_str("--autumn-mail\nContent-Type: text/plain; charset=utf-8\n\n");
                out.push_str(text);
                out.push('\n');
            }
            if let Some(html) = &mail.html {
                out.push_str("--autumn-mail\nContent-Type: text/html; charset=utf-8\n\n");
                out.push_str(html);
                out.push('\n');
            }
            out.push_str("--autumn-mail--\n");
        } else if let Some(html) = &mail.html {
            out.push_str("Content-Type: text/html; charset=utf-8\n\n");
            out.push_str(html);
            out.push('\n');
        } else if let Some(text) = &mail.text {
            out.push_str("Content-Type: text/plain; charset=utf-8\n\n");
            out.push_str(text);
            out.push('\n');
        }
        out
    }

    fn mask_nondeterministic(eml: &str) -> String {
        eml.lines()
            .map(|line| {
                if line.starts_with("Date: ") {
                    "Date: PINNED-DATE"
                } else if line.starts_with("Message-Id: ") {
                    "Message-Id: <PINNED-ID@autumn.local>"
                } else {
                    line
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn render_eml_without_attachments_matches_pinned_shape() {
        let mails = [
            Mail::builder()
                .from("from@example.com")
                .to("user@example.com")
                .subject("Hi")
                .text("hello text")
                .html("<p>hello html</p>")
                .build()
                .expect("mail should build"),
            Mail::builder()
                .from("from@example.com")
                .to("user@example.com")
                .subject("Hi")
                .text("hello text only")
                .build()
                .expect("mail should build"),
            Mail::builder()
                .from("from@example.com")
                .to("user@example.com")
                .subject("Hi")
                .html("<p>hello html only</p>")
                .build()
                .expect("mail should build"),
        ];
        for mail in mails {
            let actual = mask_nondeterministic(&render_eml(&mail));
            let pinned = mask_nondeterministic(&pinned_render_eml_no_attachments(&mail));
            assert_eq!(
                actual, pinned,
                "render_eml must be byte-identical for attachment-less mail"
            );
            assert!(!actual.contains("multipart/mixed"));
        }
    }

    #[test]
    fn lettre_message_without_attachments_has_no_mixed_part() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .html("<p>hello</p>")
            .build()
            .expect("mail should build");
        let message = lettre_message(&mail).expect("lettre message should build");
        let formatted = String::from_utf8_lossy(&message.formatted()).into_owned();
        assert!(formatted.contains("multipart/alternative"));
        assert!(!formatted.contains("multipart/mixed"));
    }

    // ── Attachments (issue #1256): model & builder ────────────────────────

    #[test]
    fn mail_builder_attach_preserves_order_and_count() {
        let mail = Mail::builder()
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .attach("a.txt", "text/plain", b"aaa".to_vec())
            .attach("b.txt", "text/plain", b"bbb".to_vec())
            .attach("c.txt", "text/plain", b"ccc".to_vec())
            .build()
            .expect("mail should build");
        assert_eq!(mail.attachments.len(), 3);
        assert_eq!(
            mail.attachments
                .iter()
                .map(|a| a.filename.as_str())
                .collect::<Vec<_>>(),
            vec!["a.txt", "b.txt", "c.txt"]
        );
        assert_eq!(mail.attachments[1].content_type, "text/plain");
        assert_eq!(mail.attachments[1].bytes, b"bbb".to_vec());
    }

    #[test]
    fn mail_serde_round_trips_attachments() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .attach("invoice.pdf", "application/pdf", vec![0_u8, 1, 2, 255])
            .build()
            .expect("mail should build");
        let json = serde_json::to_string(&mail).expect("mail should serialize");
        let round_tripped: Mail = serde_json::from_str(&json).expect("mail should deserialize");
        assert_eq!(round_tripped, mail);
    }

    #[test]
    fn mail_builder_rejects_control_chars_in_attachment_filename() {
        let err = Mail::builder()
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .attach(
                "evil\r\nX-Injected: 1.pdf",
                "application/pdf",
                b"x".to_vec(),
            )
            .build()
            .expect_err("CRLF in filename should be rejected");
        assert!(err.to_string().contains("filename"));

        let err = Mail::builder()
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .attach("\0evil.pdf", "application/pdf", b"x".to_vec())
            .build()
            .expect_err("NUL in filename should be rejected");
        assert!(err.to_string().contains("filename"));

        let err = Mail::builder()
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .attach("   ", "application/pdf", b"x".to_vec())
            .build()
            .expect_err("empty filename should be rejected");
        assert!(err.to_string().contains("filename"));
    }

    #[test]
    fn mail_builder_rejects_invalid_attachment_content_type() {
        let err = Mail::builder()
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .attach("a.pdf", "not a mime type", b"x".to_vec())
            .build()
            .expect_err("invalid content type should be rejected");
        assert!(err.to_string().contains("content type"));
    }

    #[test]
    fn mail_attachment_debug_hides_bytes() {
        let attachment = MailAttachment {
            filename: "secret.bin".to_owned(),
            content_type: "application/octet-stream".to_owned(),
            bytes: vec![1, 2, 3, 4, 5],
        };
        let debug = format!("{attachment:?}");
        assert!(debug.contains("secret.bin"));
        assert!(debug.contains('5'), "byte length should appear: {debug}");
        assert!(
            !debug.contains("[1, 2, 3, 4, 5]"),
            "raw byte values must not appear: {debug}"
        );
    }

    // ── Attachments (issue #1256): render_eml (file transport) ───────────

    fn blob_all_byte_values() -> Vec<u8> {
        (0_u8..=255).cycle().take(4096).collect()
    }

    fn sha256_hex(bytes: &[u8]) -> String {
        use sha2::Digest as _;
        let mut hasher = sha2::Sha256::new();
        hasher.update(bytes);
        format!("{:x}", hasher.finalize())
    }

    /// Extracts the random `multipart/mixed` boundary rendered by
    /// `render_eml` for an attachment message, so tests can assert against
    /// it without depending on a fixed boundary string.
    fn mixed_boundary(eml: &str) -> String {
        let line = eml
            .lines()
            .find(|line| line.starts_with("Content-Type: multipart/mixed;"))
            .expect("multipart/mixed Content-Type header present");
        content_type_boundary(line).expect("boundary parameter present")
    }

    #[test]
    fn render_eml_with_attachment_emits_multipart_mixed() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Invoice")
            .text("see attached")
            .attach("invoice.pdf", "application/pdf", b"%PDF-1.4".to_vec())
            .build()
            .expect("mail should build");
        let eml = render_eml(&mail);
        let boundary = mixed_boundary(&eml);
        assert!(eml.contains(&format!(
            "Content-Type: multipart/mixed; boundary=\"{boundary}\""
        )));
        assert!(eml.contains("Content-Disposition: attachment; filename=\"invoice.pdf\""));
        assert!(eml.contains("Content-Type: application/pdf"));
        assert!(eml.contains("Content-Transfer-Encoding: base64"));
        assert!(eml.contains(&format!("--{boundary}--")));
    }

    #[test]
    fn render_eml_boundary_is_unpredictable_and_body_cannot_forge_it() {
        // A fixed boundary (e.g. a literal `"autumn-mixed"`) lets a body
        // containing a `--autumn-mixed` line be mistaken for a real MIME
        // delimiter, truncating or splitting the message. The boundary must
        // vary per render and not be derivable from body content alone.
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Spoof attempt")
            .text("line one\n--autumn-mixed--\nX-Spoofed: header\nline two")
            .attach("invoice.pdf", "application/pdf", b"%PDF-1.4".to_vec())
            .build()
            .expect("mail should build");
        let eml = render_eml(&mail);
        let parsed = parse_eml(&eml);
        assert_eq!(
            parsed.text.as_deref(),
            Some("line one\n--autumn-mixed--\nX-Spoofed: header\nline two"),
            "body content resembling the old fixed boundary must not truncate the message"
        );
        assert_eq!(parsed.attachments.len(), 1);

        let other = render_eml(
            &Mail::builder()
                .from("from@example.com")
                .to("user@example.com")
                .subject("Second message")
                .text("hi")
                .attach("invoice.pdf", "application/pdf", b"%PDF-1.4".to_vec())
                .build()
                .expect("mail should build"),
        );
        assert_ne!(
            mixed_boundary(&eml),
            mixed_boundary(&other),
            "boundary must vary per message, not be a fixed/predictable string"
        );
    }

    #[test]
    fn render_eml_attachment_bytes_round_trip_sha256() {
        use base64::Engine as _;
        let blob = blob_all_byte_values();
        let expected_digest = sha256_hex(&blob);
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Blob")
            .text("see attached")
            .attach("blob.bin", "application/octet-stream", blob)
            .build()
            .expect("mail should build");
        let eml = render_eml(&mail);
        let boundary = mixed_boundary(&eml);

        let start = eml
            .find("Content-Transfer-Encoding: base64\n\n")
            .expect("base64 section present")
            + "Content-Transfer-Encoding: base64\n\n".len();
        let rest = &eml[start..];
        let end = rest
            .find(&format!("--{boundary}"))
            .expect("closing boundary present");
        let encoded: String = rest[..end].chars().filter(|c| !c.is_whitespace()).collect();

        let decoded = base64::engine::general_purpose::STANDARD
            .decode(encoded)
            .expect("attachment body should be valid base64");
        assert_eq!(sha256_hex(&decoded), expected_digest);
    }

    #[test]
    fn render_eml_preserves_attachment_order() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Multi")
            .text("see attached")
            .attach("a.txt", "text/plain", b"a".to_vec())
            .attach("b.txt", "text/plain", b"b".to_vec())
            .build()
            .expect("mail should build");
        let eml = render_eml(&mail);
        let a_pos = eml.find("filename=\"a.txt\"").expect("a.txt present");
        let b_pos = eml.find("filename=\"b.txt\"").expect("b.txt present");
        assert!(a_pos < b_pos, "attachments must render in declared order");
    }

    #[test]
    fn render_eml_with_attachment_nests_alternative_body() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Both bodies")
            .text("plain")
            .html("<p>html</p>")
            .attach("a.txt", "text/plain", b"a".to_vec())
            .build()
            .expect("mail should build");
        let eml = render_eml(&mail);
        assert!(eml.contains("Content-Type: multipart/alternative; boundary=\"autumn-mail\""));
        assert!(eml.contains("plain"));
        assert!(eml.contains("<p>html</p>"));
    }

    #[test]
    fn render_eml_blocks_filename_header_injection() {
        // Hand-built Mail bypasses `build()`'s validation entirely — a `Mail`
        // can also arrive via `Deserialize` from a durable queue, so the
        // render layer must be injection-proof independent of the builder.
        let mail = Mail {
            from: Some("from@example.com".to_owned()),
            reply_to: None,
            to: vec!["user@example.com".to_owned()],
            subject: "Hi".to_owned(),
            html: None,
            text: Some("hello".to_owned()),
            list_unsubscribe: None,
            extra_headers: Vec::new(),
            attachments: vec![MailAttachment {
                filename: "evil\r\nX-Injected: 1.pdf".to_owned(),
                content_type: "application/pdf".to_owned(),
                bytes: b"x".to_vec(),
            }],
            ignore_suppression: false,
            inline_css: None,
        };
        let eml = render_eml(&mail);
        assert!(
            !eml.lines().any(|line| line.starts_with("X-Injected")),
            "CRLF in filename must not inject a header: {eml}"
        );
        assert!(!eml.contains('\r'));
    }

    #[test]
    fn render_eml_blocks_header_injection_in_all_deserialized_fields() {
        // Same threat model as `render_eml_blocks_filename_header_injection`,
        // but for the pre-existing `subject`/`to`/`from`/`reply_to`/
        // `extra_headers` fields — these are just as reachable via an
        // untrusted `Deserialize`d `Mail` as the attachment filename is.
        let mail = Mail {
            from: Some("from@example.com\r\nX-From-Injected: 1".to_owned()),
            reply_to: Some("reply@example.com\r\nX-Reply-Injected: 1".to_owned()),
            to: vec!["user@example.com\r\nX-To-Injected: 1".to_owned()],
            subject: "Hi\r\nX-Subject-Injected: 1".to_owned(),
            html: None,
            text: Some("hello".to_owned()),
            list_unsubscribe: None,
            extra_headers: vec![(
                "X-Custom\r\nX-Header-Injected".to_owned(),
                "1\r\nX-Value-Injected: 1".to_owned(),
            )],
            attachments: Vec::new(),
            ignore_suppression: false,
            inline_css: None,
        };
        let eml = render_eml(&mail);
        assert!(
            !eml.lines().any(|line| line.starts_with("X-From-Injected")

                || line.starts_with("X-Reply-Injected")
                || line.starts_with("X-To-Injected")
                || line.starts_with("X-Subject-Injected")
                || line.starts_with("X-Header-Injected")
                || line.starts_with("X-Value-Injected")),
            "CRLF in any header-bound field must not inject a standalone header line: {eml}"
        );
        assert!(!eml.contains('\r'));
    }

    #[test]
    fn render_eml_falls_back_to_octet_stream_for_invalid_content_type() {
        // A `Mail` bypassing `build()` could carry a syntactically invalid
        // content type; the file transport must not write it verbatim, to
        // stay consistent with the SMTP transport (which rejects it).
        let mail = Mail {
            from: Some("from@example.com".to_owned()),
            reply_to: None,
            to: vec!["user@example.com".to_owned()],
            subject: "Hi".to_owned(),
            html: None,
            text: Some("hello".to_owned()),
            list_unsubscribe: None,
            extra_headers: Vec::new(),
            attachments: vec![MailAttachment {
                filename: "file.bin".to_owned(),
                content_type: "not a mime type".to_owned(),
                bytes: b"x".to_vec(),
            }],
            ignore_suppression: false,
            inline_css: None,
        };
        let eml = render_eml(&mail);
        assert!(eml.contains("Content-Type: application/octet-stream"));
        assert!(!eml.contains("not a mime type"));
    }

    #[test]
    fn render_eml_encodes_non_ascii_filename_rfc2231() {
        let mail = Mail {
            from: Some("from@example.com".to_owned()),
            reply_to: None,
            to: vec!["user@example.com".to_owned()],
            subject: "Hi".to_owned(),
            html: None,
            text: Some("hello".to_owned()),
            list_unsubscribe: None,
            extra_headers: Vec::new(),
            attachments: vec![MailAttachment {
                filename: "Résumé façade.pdf".to_owned(),
                content_type: "application/pdf".to_owned(),
                bytes: b"x".to_vec(),
            }],
            ignore_suppression: false,
            inline_css: None,
        };
        let eml = render_eml(&mail);
        assert!(eml.contains("filename*=UTF-8''"));
        let disposition_line = eml
            .lines()
            .find(|line| line.starts_with("Content-Disposition:"))
            .expect("Content-Disposition header present");
        assert!(disposition_line.is_ascii());
    }

    #[test]
    fn content_disposition_params_table() {
        assert_eq!(content_disposition_params("a.txt"), "filename=\"a.txt\"");
        assert_eq!(
            content_disposition_params("weird\"na\\me.txt"),
            "filename=\"weird\\\"na\\\\me.txt\""
        );
        assert_eq!(
            content_disposition_params("evil\r\nX: 1"),
            "filename=\"evilX: 1\""
        );
        assert_eq!(content_disposition_params(""), "filename=\"attachment\"");
        assert_eq!(content_disposition_params("   "), "filename=\"attachment\"");
        let non_ascii = content_disposition_params("café.txt");
        assert!(non_ascii.contains("filename*=UTF-8''caf%C3%A9.txt"));
        assert!(non_ascii.is_ascii());
    }

    #[test]
    fn render_eml_base64_lines_wrap_at_76() {
        let blob = blob_all_byte_values();
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Blob")
            .text("see attached")
            .attach("blob.bin", "application/octet-stream", blob)
            .build()
            .expect("mail should build");
        let eml = render_eml(&mail);
        let boundary = mixed_boundary(&eml);
        let start = eml
            .find("Content-Transfer-Encoding: base64\n\n")
            .expect("base64 section present")
            + "Content-Transfer-Encoding: base64\n\n".len();
        let rest = &eml[start..];
        let end = rest
            .find(&format!("--{boundary}"))
            .expect("closing boundary present");
        for line in rest[..end].lines() {
            assert!(
                line.len() <= 76,
                "base64 line too long: {} chars",
                line.len()
            );
        }
    }

    // ── Attachments (issue #1256): lettre_message (SMTP transport) ───────

    #[test]
    fn lettre_message_with_attachment_is_multipart_mixed() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Invoice")
            .text("see attached")
            .attach("invoice.pdf", "application/pdf", b"%PDF-1.4".to_vec())
            .build()
            .expect("mail should build");
        let message = lettre_message(&mail).expect("lettre message should build");
        let formatted = String::from_utf8_lossy(&message.formatted()).into_owned();
        assert!(formatted.contains("multipart/mixed"));
        assert!(formatted.contains("Content-Disposition: attachment"));
        assert!(formatted.contains("invoice.pdf"));
        assert!(formatted.contains("base64"));
    }

    fn extract_boundary(text: &str) -> String {
        let marker = "boundary=\"";
        let start = text.find(marker).expect("boundary present") + marker.len();
        let rest = &text[start..];
        let end = rest.find('"').expect("boundary closing quote");
        rest[..end].to_owned()
    }

    fn extract_attachment_base64(formatted_lf: &str, boundary: &str) -> String {
        let marker = format!("--{boundary}");
        for segment in formatted_lf.split(&marker).skip(1) {
            let segment = segment.trim_start_matches(['\n', '\r']);
            if segment.starts_with("--") {
                break;
            }
            let (headers, body) = split_headers_body(segment);
            if header_value(&headers, "Content-Disposition")
                .unwrap_or_default()
                .to_ascii_lowercase()
                .contains("attachment")
            {
                return body.chars().filter(|c| !c.is_whitespace()).collect();
            }
        }
        panic!("attachment part not found in: {formatted_lf}");
    }

    #[test]
    fn lettre_message_attachment_round_trips_sha256() {
        use base64::Engine as _;
        let blob = blob_all_byte_values();
        let expected_digest = sha256_hex(&blob);
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Blob")
            .text("see attached")
            .attach("blob.bin", "application/octet-stream", blob)
            .build()
            .expect("mail should build");
        let message = lettre_message(&mail).expect("lettre message should build");
        let formatted = String::from_utf8_lossy(&message.formatted()).into_owned();
        let normalized = formatted.replace("\r\n", "\n");
        let boundary = extract_boundary(&normalized);
        let encoded = extract_attachment_base64(&normalized, &boundary);

        let decoded = base64::engine::general_purpose::STANDARD
            .decode(encoded)
            .expect("attachment body should be valid base64");
        assert_eq!(sha256_hex(&decoded), expected_digest);
    }

    #[test]
    fn lettre_message_attachment_headers_ascii_and_injection_free() {
        for filename in ["evil\r\nX-Injected: 1.pdf", "Résumé façade.pdf"] {
            let mail = Mail {
                from: Some("from@example.com".to_owned()),
                reply_to: None,
                to: vec!["user@example.com".to_owned()],
                subject: "Hi".to_owned(),
                html: None,
                text: Some("hello".to_owned()),
                list_unsubscribe: None,
                extra_headers: Vec::new(),
                attachments: vec![MailAttachment {
                    filename: filename.to_owned(),
                    content_type: "application/pdf".to_owned(),
                    bytes: b"x".to_vec(),
                }],
                ignore_suppression: false,
                inline_css: None,
            };
            let message = lettre_message(&mail).expect("lettre message should build");
            let formatted = String::from_utf8_lossy(&message.formatted()).into_owned();
            let header_section = formatted
                .split("\r\n\r\n")
                .next()
                .expect("header section present");
            assert!(
                header_section.is_ascii(),
                "headers must stay ASCII for filename {filename:?}: {header_section}"
            );
            assert!(
                !formatted.lines().any(|line| line.starts_with("X-Injected")),
                "CRLF in filename must not inject a header for {filename:?}"
            );
        }
    }

    #[test]
    fn lettre_message_attachment_with_invalid_content_type_errors() {
        let mail = Mail {
            from: Some("from@example.com".to_owned()),
            reply_to: None,
            to: vec!["user@example.com".to_owned()],
            subject: "Hi".to_owned(),
            html: None,
            text: Some("hello".to_owned()),
            list_unsubscribe: None,
            extra_headers: Vec::new(),
            attachments: vec![MailAttachment {
                filename: "a.bin".to_owned(),
                content_type: "not a mime type".to_owned(),
                bytes: b"x".to_vec(),
            }],
            ignore_suppression: false,
            inline_css: None,
        };
        let err = lettre_message(&mail).expect_err("invalid content type should error");
        assert!(matches!(err, MailError::InvalidMessage(_)));
    }

    // ── Attachments (issue #1256): dev preview ────────────────────────────

    #[test]
    fn parse_eml_extracts_attachment_list() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Invoice")
            .text("plain")
            .html("<p>html</p>")
            .attach("invoice.pdf", "application/pdf", b"%PDF-1.4".to_vec())
            .attach("receipt.csv", "text/csv", b"a,b,c".to_vec())
            .build()
            .expect("mail should build");
        let eml = render_eml(&mail);
        let parsed = parse_eml(&eml);
        assert_eq!(parsed.attachments.len(), 2);
        assert_eq!(parsed.attachments[0].filename, "invoice.pdf");
        assert_eq!(parsed.attachments[0].content_type, "application/pdf");
        assert_eq!(parsed.attachments[1].filename, "receipt.csv");
        assert_eq!(parsed.html.as_deref(), Some("<p>html</p>"));
        assert_eq!(parsed.text.as_deref(), Some("plain"));
    }

    #[test]
    fn extract_attachment_filename_handles_semicolon_in_quoted_filename() {
        // Naive `disposition.split(';')` would truncate this at "invoice".
        assert_eq!(
            extract_attachment_filename(r#"attachment; filename="invoice;2026.pdf""#),
            "invoice;2026.pdf"
        );
    }

    #[test]
    fn extract_attachment_filename_unescapes_quoted_pairs() {
        assert_eq!(
            extract_attachment_filename(r#"attachment; filename="weird\"na\\me.txt""#),
            "weird\"na\\me.txt"
        );
    }

    #[test]
    fn extract_attachment_filename_is_case_insensitive_and_handles_language_tag() {
        assert_eq!(
            extract_attachment_filename("attachment; filename*=utf-8'en'r%C3%A9sum%C3%A9.pdf"),
            "résumé.pdf"
        );
    }

    #[test]
    fn extract_attachment_filename_round_trips_through_dev_preview() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Invoice")
            .text("plain")
            .attach(r#"a;b"c\d.txt"#, "text/plain", b"x".to_vec())
            .build()
            .expect("mail should build");
        let eml = render_eml(&mail);
        let parsed = parse_eml(&eml);
        assert_eq!(parsed.attachments.len(), 1);
        assert_eq!(parsed.attachments[0].filename, r#"a;b"c\d.txt"#);
    }

    #[test]
    fn parse_multipart_mixed_does_not_misclassify_inline_as_attachment() {
        let (_, _, attachments) = parse_multipart_mixed(
            "--b\nContent-Disposition: inline; filename=\"my-attachment-notes.pdf\"\nContent-Type: text/plain\n\nhi\n--b--\n",
            "b",
        );
        assert!(
            attachments.is_empty(),
            "an `inline` disposition must not be classified as an attachment: {attachments:?}"
        );
    }

    #[test]
    fn mail_deserializes_from_pre_attachments_json_shape() {
        // `Mail::attachments` must default on a missing key so a `Mail`
        // serialized by an older binary (before this field existed) still
        // deserializes from a durable delivery queue during a rolling
        // deploy.
        let json = r#"{"from":null,"reply_to":null,"to":["a@example.com"],"subject":"hi","html":null,"text":"hello","list_unsubscribe":null,"extra_headers":[]}"#;
        let mail: Mail =
            serde_json::from_str(json).expect("pre-attachments JSON should deserialize");
        assert!(mail.attachments.is_empty());
    }

    #[test]
    fn render_mail_detail_lists_attachments() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Invoice")
            .text("plain")
            .attach("invoice.pdf", "application/pdf", b"%PDF-1.4".to_vec())
            .attach("receipt.csv", "text/csv", b"a,b,c".to_vec())
            .build()
            .expect("mail should build");
        let parsed = parse_eml(&render_eml(&mail));
        let detail = render_mail_detail(&parsed, "captured");
        assert!(detail.contains("Attachments (2)"));
        assert!(detail.contains("invoice.pdf"));
        assert!(detail.contains("receipt.csv"));
    }

    #[test]
    fn render_mail_detail_without_attachments_omits_section() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Plain")
            .text("plain")
            .build()
            .expect("mail should build");
        let parsed = parse_eml(&render_eml(&mail));
        let detail = render_mail_detail(&parsed, "captured");
        assert!(!detail.contains("Attachments"));
    }

    #[test]
    fn mail_builder_rejects_missing_body() {
        let err = Mail::builder()
            .to("user@example.com")
            .subject("Hello")
            .build()
            .expect_err("body should be required");
        assert!(err.to_string().contains("html or text"));
    }

    #[test]
    fn filename_sanitizer_keeps_safe_characters() {
        assert_eq!(
            sanitize_filename("Ada Lovelace <ada@example.com>"),
            "Ada_Lovelace__ada_example.com_"
        );
    }

    #[test]
    fn transport_default_is_disabled() {
        assert_eq!(Transport::default(), Transport::Disabled);
    }

    // ── List-Unsubscribe: Mail surface (Component 1) ─────────────────────────

    #[test]
    fn mail_defaults_have_no_unsubscribe_or_extra_headers() {
        let mail = Mail::builder()
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .build()
            .expect("mail should build");
        assert_eq!(mail.list_unsubscribe, None);
        assert!(mail.extra_headers.is_empty());
        assert!(mail.attachments.is_empty());
    }

    #[test]
    fn mail_builder_sets_list_unsubscribe_and_headers() {
        let mail = Mail::builder()
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .list_unsubscribe("weekly_digest")
            .header("X-Custom", "1")
            .build()
            .expect("mail should build");
        assert_eq!(mail.list_unsubscribe.as_deref(), Some("weekly_digest"));
        assert_eq!(
            mail.extra_headers,
            vec![("X-Custom".to_owned(), "1".to_owned())]
        );
    }

    // ── List-Unsubscribe: token signing (Component 2) ────────────────────────

    fn test_keys() -> crate::security::config::ResolvedSigningKeys {
        crate::security::config::ResolvedSigningKeys::new(
            b"unit-test-signing-key-0123456789".to_vec(),
            vec![],
        )
    }

    #[test]
    fn token_roundtrips_and_hides_subscriber() {
        use base64::Engine as _;
        let engine = base64::engine::general_purpose::URL_SAFE_NO_PAD;
        let keys = test_keys();
        let token =
            unsubscribe::sign_token(&keys, "ada@example.com", "weekly_digest", 4_000_000_000);
        assert!(
            !token.contains("ada@example.com"),
            "raw subscriber must not appear in the token: {token}"
        );
        // The address is encrypted, not merely base64-encoded: its base64url form
        // (which the old signed-token format embedded) must not appear either.
        assert!(
            !token.contains(&engine.encode("ada@example.com")),
            "base64 of subscriber must not appear — the payload must be encrypted: {token}"
        );
        let decoded = unsubscribe::verify_token(&keys, &token, 1_000).expect("token should verify");
        assert_eq!(decoded.subscriber, "ada@example.com");
        assert_eq!(decoded.list_id, "weekly_digest");
    }

    #[test]
    fn token_rejects_tamper_and_expiry() {
        use base64::Engine as _;
        let engine = base64::engine::general_purpose::URL_SAFE_NO_PAD;
        let keys = test_keys();
        let token =
            unsubscribe::sign_token(&keys, "ada@example.com", "weekly_digest", 4_000_000_000);
        // Flip a bit in the trailing GCM tag: AES-GCM authentication must reject it.
        let mut blob = engine.decode(&token).expect("token is base64");
        let last = blob.len() - 1;
        blob[last] ^= 0x01;
        let tampered = engine.encode(&blob);
        assert_eq!(
            unsubscribe::verify_token(&keys, &tampered, 1_000),
            Err(unsubscribe::TokenError::BadSignature)
        );
        // Expired (now > expiry).
        let short = unsubscribe::sign_token(&keys, "ada@example.com", "weekly_digest", 100);
        assert_eq!(
            unsubscribe::verify_token(&keys, &short, 200),
            Err(unsubscribe::TokenError::Expired)
        );
    }

    #[test]
    fn token_verifies_under_rotated_previous_key() {
        let signer = crate::security::config::ResolvedSigningKeys::new(
            b"old-key-old-key-old-key-old-key!".to_vec(),
            vec![],
        );
        let token = unsubscribe::sign_token(&signer, "ada@example.com", "list", 4_000_000_000);
        let rotated = crate::security::config::ResolvedSigningKeys::new(
            b"new-key-new-key-new-key-new-key!".to_vec(),
            vec![b"old-key-old-key-old-key-old-key!".to_vec()],
        );
        assert!(unsubscribe::verify_token(&rotated, &token, 1_000).is_ok());
    }

    #[test]
    fn unsubscribe_url_includes_token_and_path() {
        let url = unsubscribe::unsubscribe_url("https://app.example.com/", "TOK");
        assert_eq!(url, "https://app.example.com/_autumn/unsubscribe?token=TOK");
    }

    // ── List-Unsubscribe: suppression store (Component 3) ────────────────────

    #[tokio::test]
    async fn in_memory_suppression_transitions() {
        let store = InMemorySuppressionStore::new();
        assert!(!store.is_suppressed("a@x.com", "list").await.unwrap());
        store.suppress("a@x.com", "list").await.unwrap();
        assert!(store.is_suppressed("a@x.com", "list").await.unwrap());
        // Scoped to (subscriber, list).
        assert!(!store.is_suppressed("a@x.com", "other").await.unwrap());
        assert!(!store.is_suppressed("b@x.com", "list").await.unwrap());
    }

    // ── List-Unsubscribe: header emission + send (Component 4) ───────────────

    #[test]
    fn render_eml_emits_extra_headers() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .header("List-Unsubscribe", "<https://x/u?token=t>, <mailto:u@x>")
            .header("List-Unsubscribe-Post", "List-Unsubscribe=One-Click")
            .build()
            .expect("mail should build");
        let eml = render_eml(&mail);
        assert!(eml.contains("List-Unsubscribe: <https://x/u?token=t>, <mailto:u@x>"));
        assert!(eml.contains("List-Unsubscribe-Post: List-Unsubscribe=One-Click"));
    }

    #[test]
    fn render_eml_without_headers_has_no_unsubscribe() {
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .build()
            .expect("mail should build");
        assert!(!render_eml(&mail).contains("List-Unsubscribe"));
    }

    #[derive(Clone)]
    struct CapturingTransport {
        sent: Arc<std::sync::Mutex<Vec<Mail>>>,
    }

    impl MailTransport for CapturingTransport {
        fn send<'a>(
            &'a self,
            mail: Mail,
        ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
            Box::pin(async move {
                self.sent.lock().expect("sent lock").push(mail);
                Ok(())
            })
        }
    }

    fn unsubscribe_runtime(
        suppression: Option<Arc<dyn SuppressionStore>>,
    ) -> Arc<UnsubscribeRuntime> {
        Arc::new(UnsubscribeRuntime {
            base_url: Some("https://app.example.com".to_owned()),
            mailto: Some("unsub@example.com".to_owned()),
            signing_keys: Arc::new(test_keys()),
            ttl_days: 30,
            suppression,
        })
    }

    #[tokio::test]
    #[allow(clippy::significant_drop_tightening)]
    async fn send_adds_headers_for_list_mail() {
        let sent = Arc::new(std::sync::Mutex::new(Vec::new()));
        let transport = CapturingTransport { sent: sent.clone() };
        let mailer = Mailer::with_transport(transport).with_unsubscribe(unsubscribe_runtime(None));
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Digest")
            .text("hello")
            .list_unsubscribe("weekly_digest")
            .build()
            .unwrap();
        mailer.send(mail).await.unwrap();
        let captured = sent.lock().unwrap();
        assert_eq!(captured.len(), 1);
        let headers = &captured[0].extra_headers;
        assert!(headers.iter().any(|(n, v)| n == "List-Unsubscribe"

            && v.contains("/_autumn/unsubscribe?token=")
            && v.contains("mailto:unsub@example.com")));
        assert!(
            headers
                .iter()
                .any(|(n, v)| n == "List-Unsubscribe-Post" && v == "List-Unsubscribe=One-Click")
        );
    }

    #[tokio::test]
    #[allow(clippy::significant_drop_tightening)]
    async fn send_replaces_manual_list_unsubscribe_with_generated_one_click() {
        // A template that opts into list_unsubscribe but also set a hand-rolled
        // List-Unsubscribe must end up with the generated per-recipient one-click
        // header (replace, not suppress), so RFC 8058 compliance isn't lost.
        let sent = Arc::new(std::sync::Mutex::new(Vec::new()));
        let transport = CapturingTransport { sent: sent.clone() };
        let mailer = Mailer::with_transport(transport).with_unsubscribe(unsubscribe_runtime(None));
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Digest")
            .text("hello")
            .header("List-Unsubscribe", "<mailto:old@example.com>")
            .list_unsubscribe("weekly_digest")
            .build()
            .unwrap();
        mailer.send(mail).await.unwrap();
        let captured = sent.lock().unwrap();
        assert_eq!(captured.len(), 1);
        let headers = &captured[0].extra_headers;
        // Exactly one List-Unsubscribe, and it's the generated one-click (not the
        // stale manual value).
        let unsub: Vec<&String> = headers
            .iter()
            .filter(|(n, _)| n == "List-Unsubscribe")
            .map(|(_, v)| v)
            .collect();
        assert_eq!(unsub.len(), 1);
        assert!(unsub[0].contains("/_autumn/unsubscribe?token="));
        assert!(!unsub[0].contains("old@example.com"));
        assert!(
            headers
                .iter()
                .any(|(n, v)| n == "List-Unsubscribe-Post" && v == "List-Unsubscribe=One-Click")
        );
    }

    #[tokio::test]
    async fn send_list_mail_rejects_invalid_recipient_before_delivery() {
        let sent = Arc::new(std::sync::Mutex::new(Vec::new()));
        let transport = CapturingTransport { sent: sent.clone() };
        let mailer = Mailer::with_transport(transport).with_unsubscribe(unsubscribe_runtime(None));
        // Second recipient is syntactically invalid. The send must fail before
        // delivering to the first, so a retry cannot duplicate that send.
        let mail = Mail::builder()
            .from("from@example.com")
            .to("good@example.com")
            .to("not a valid address")
            .subject("Digest")
            .text("hello")
            .list_unsubscribe("weekly_digest")
            .build()
            .unwrap();
        let result = mailer.send(mail).await;
        assert!(result.is_err(), "invalid recipient must fail the send");
        assert!(
            sent.lock().unwrap().is_empty(),
            "no recipient may be delivered when the list contains an invalid address"
        );
    }

    #[tokio::test]
    async fn send_list_mail_suppression_error_fails_before_any_delivery() {
        // A suppression store that errors for one specific subscriber.
        struct FailingStore {
            fail_for: String,
        }
        impl SuppressionStore for FailingStore {
            fn is_suppressed<'a>(
                &'a self,
                subscriber: &'a str,
                _list_id: &'a str,
            ) -> Pin<Box<dyn Future<Output = Result<bool, MailError>> + Send + 'a>> {
                let fails = subscriber == self.fail_for;
                Box::pin(async move {
                    if fails {
                        Err(MailError::RuntimeUnavailable(
                            "store unavailable".to_owned(),
                        ))
                    } else {
                        Ok(false)
                    }
                })
            }
            fn suppress<'a>(
                &'a self,
                _subscriber: &'a str,
                _list_id: &'a str,
            ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
                Box::pin(async move { Ok(()) })
            }
        }

        let sent = Arc::new(std::sync::Mutex::new(Vec::new()));
        let transport = CapturingTransport { sent: sent.clone() };
        let store: Arc<dyn SuppressionStore> = Arc::new(FailingStore {
            fail_for: "second@example.com".to_owned(),
        });
        let mailer =
            Mailer::with_transport(transport).with_unsubscribe(unsubscribe_runtime(Some(store)));
        // The second recipient's suppression lookup errors. The whole send must
        // fail before the first recipient is delivered, so a retry can't duplicate
        // that delivery.
        let mail = Mail::builder()
            .from("from@example.com")
            .to("first@example.com")
            .to("second@example.com")
            .subject("Digest")
            .text("hello")
            .list_unsubscribe("weekly_digest")
            .build()
            .unwrap();
        let result = mailer.send(mail).await;
        assert!(
            result.is_err(),
            "suppression-store error must fail the send"
        );
        assert!(
            sent.lock().unwrap().is_empty(),
            "no recipient may be delivered when a later suppression lookup fails"
        );
    }

    #[tokio::test]
    async fn send_skips_suppressed_recipient() {
        let store = Arc::new(InMemorySuppressionStore::new());
        store
            .suppress("user@example.com", "weekly_digest")
            .await
            .unwrap();
        let sent = Arc::new(std::sync::Mutex::new(Vec::new()));
        let transport = CapturingTransport { sent: sent.clone() };
        let mailer =
            Mailer::with_transport(transport).with_unsubscribe(unsubscribe_runtime(Some(store)));
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Digest")
            .text("hello")
            .list_unsubscribe("weekly_digest")
            .build()
            .unwrap();
        mailer.send(mail).await.unwrap();
        assert!(
            sent.lock().unwrap().is_empty(),
            "suppressed recipient must be skipped"
        );
    }

    #[tokio::test]
    #[allow(clippy::significant_drop_tightening)]
    async fn send_without_scope_is_unchanged() {
        let sent = Arc::new(std::sync::Mutex::new(Vec::new()));
        let transport = CapturingTransport { sent: sent.clone() };
        let mailer = Mailer::with_transport(transport).with_unsubscribe(unsubscribe_runtime(None));
        let mail = Mail::builder()
            .from("from@example.com")
            .to("user@example.com")
            .subject("Reset")
            .text("hello")
            .build()
            .unwrap();
        mailer.send(mail).await.unwrap();
        let captured = sent.lock().unwrap();
        assert_eq!(captured.len(), 1);
        assert!(
            captured[0].extra_headers.is_empty(),
            "non-list mail must not gain headers"
        );
    }

    // ── List-Unsubscribe: startup fail-closed (Component 6) ──────────────────

    #[test]
    fn fail_closed_only_in_prod_with_mailers_and_no_config() {
        assert!(unsubscribe_config_fail_closed(true, true, true, false));
        // configured → ok
        assert!(!unsubscribe_config_fail_closed(true, true, true, true));
        // no list mailers → ok
        assert!(!unsubscribe_config_fail_closed(true, true, false, false));
        // not production → ok
        assert!(!unsubscribe_config_fail_closed(true, false, true, false));
        // not enforced (static build) → ok
        assert!(!unsubscribe_config_fail_closed(false, true, true, false));
    }

    #[test]
    fn validate_rejects_non_positive_unsubscribe_ttl() {
        let ttl = |days: i64| MailConfig {
            unsubscribe_token_ttl_days: days,
            ..MailConfig::default()
        };
        assert!(ttl(0).validate(Some("dev")).is_err());
        assert!(ttl(-1).validate(Some("dev")).is_err());
        assert!(ttl(30).validate(Some("dev")).is_ok());
    }

    #[test]
    fn unsubscribe_base_url_set_tracks_config() {
        let with = |base: Option<&str>, mailto: Option<&str>| MailConfig {
            unsubscribe_base_url: base.map(str::to_owned),
            unsubscribe_mailto: mailto.map(str::to_owned),
            ..MailConfig::default()
        };
        assert!(!with(None, None).unsubscribe_base_url_set());
        // mailto-only is not a base URL (RFC 2369, not one-click).
        assert!(!with(None, Some("u@example.com")).unsubscribe_base_url_set());
        assert!(with(Some("https://x"), None).unsubscribe_base_url_set());
        assert!(!with(Some("   "), None).unsubscribe_base_url_set());
    }

    #[test]
    fn should_mount_unsubscribe_endpoint_requires_opt_in_and_base_url() {
        let cfg = |base: Option<&str>, opt_in: bool| MailConfig {
            unsubscribe_base_url: base.map(str::to_owned),
            mount_unsubscribe_endpoint: opt_in,
            ..MailConfig::default()
        };
        // base URL alone does not mount — opt-in is required.
        assert!(!cfg(Some("https://x"), false).should_mount_unsubscribe_endpoint());
        assert!(cfg(Some("https://x"), true).should_mount_unsubscribe_endpoint());
        // opt-in without a base URL does not mount.
        assert!(!cfg(None, true).should_mount_unsubscribe_endpoint());
    }

    #[test]
    fn validate_rejects_malformed_mailto_in_prod() {
        let cfg = |mailto: &str| MailConfig {
            unsubscribe_mailto: Some(mailto.to_owned()),
            ..MailConfig::default()
        };
        assert!(
            cfg("unsubscribe example.com")
                .validate(Some("prod"))
                .is_err()
        );
        assert!(cfg("not-an-email").validate(Some("prod")).is_err());
        assert!(cfg("unsub@example.com").validate(Some("prod")).is_ok());
        // a full mailto: URI is accepted too.
        assert!(
            cfg("mailto:unsub@example.com")
                .validate(Some("prod"))
                .is_ok()
        );
        // dev is lenient.
        assert!(cfg("whatever").validate(Some("dev")).is_ok());
    }

    #[test]
    fn validate_requires_https_base_url_in_prod() {
        let cfg = |url: &str| MailConfig {
            unsubscribe_base_url: Some(url.to_owned()),
            ..MailConfig::default()
        };
        assert!(
            cfg("http://app.example.com")
                .validate(Some("prod"))
                .is_err()
        );
        assert!(
            cfg("https://app.example.com")
                .validate(Some("prod"))
                .is_ok()
        );
        // dev allows http for local testing.
        assert!(cfg("http://localhost:3000").validate(Some("dev")).is_ok());
        // https prefix without a real host is rejected in prod.
        assert!(cfg("https://").validate(Some("prod")).is_err());
        assert!(cfg("https:///path").validate(Some("prod")).is_err());
        // query/fragment bases would break the appended ?token=… link.
        assert!(
            cfg("https://app.example.com?t=acme")
                .validate(Some("prod"))
                .is_err()
        );
        assert!(
            cfg("https://app.example.com#x")
                .validate(Some("prod"))
                .is_err()
        );
        assert!(
            cfg("https://app.example.com/base")
                .validate(Some("prod"))
                .is_ok()
        );
    }

    #[test]
    fn canonical_subscriber_strips_name_and_lowercases() {
        assert_eq!(
            canonical_subscriber("Ada Lovelace <Ada@Example.com>"),
            "ada@example.com"
        );
        assert_eq!(canonical_subscriber("USER@EXAMPLE.COM"), "user@example.com");
    }

    #[test]
    fn mailto_only_runtime_does_not_support_one_click() {
        let runtime = UnsubscribeRuntime {
            base_url: None,
            mailto: Some("u@example.com".to_owned()),
            signing_keys: Arc::new(test_keys()),
            ttl_days: 30,
            suppression: None,
        };
        assert!(!runtime.supports_one_click());
        let header = runtime
            .list_unsubscribe_header("a@x.com", "list")
            .expect("mailto header");
        assert!(header.contains("mailto:u@example.com"));
        assert!(!header.contains("token="));
    }

    #[test]
    fn mailto_value_with_scheme_is_not_double_prefixed() {
        let runtime = UnsubscribeRuntime {
            base_url: None,
            mailto: Some("mailto:u@example.com".to_owned()),
            signing_keys: Arc::new(test_keys()),
            ttl_days: 30,
            suppression: None,
        };
        let header = runtime
            .list_unsubscribe_header("a@x.com", "list")
            .expect("mailto header");
        assert!(header.contains("<mailto:u@example.com?subject=unsubscribe>"));
        assert!(!header.contains("mailto:mailto:"));
    }

    #[test]
    fn one_click_body_detection() {
        assert!(is_one_click_body("List-Unsubscribe=One-Click"));
        assert!(is_one_click_body("foo=bar&List-Unsubscribe=One-Click"));
        assert!(is_one_click_body("list-unsubscribe=one-click")); // case-insensitive
        assert!(!is_one_click_body(""));
        assert!(!is_one_click_body("List-Unsubscribe=Nope"));
        assert!(!is_one_click_body("something=else"));
    }

    #[test]
    fn smtp_config_validation_rejects_whitespace_only_host() {
        let config = MailConfig {
            transport: Transport::Smtp,
            smtp: SmtpConfig {
                host: Some("   ".to_owned()),
                ..Default::default()
            },
            ..Default::default()
        };

        let error = config
            .validate(Some("dev"))
            .expect_err("whitespace SMTP host should be rejected");

        assert!(error.to_string().contains("mail.smtp.host is required"));
    }

    #[test]
    fn transport_env_value_is_trimmed_and_case_insensitive() {
        assert_eq!(Transport::from_env_value(" SMTP "), Some(Transport::Smtp));
        assert_eq!(Transport::from_env_value(" LoG "), Some(Transport::Log));
    }

    #[test]
    fn tls_mode_env_value_is_trimmed_and_case_insensitive() {
        assert_eq!(TlsMode::from_env_value(" TLS "), Some(TlsMode::Tls));
        assert_eq!(
            TlsMode::from_env_value(" START_TLS "),
            Some(TlsMode::StartTls)
        );
        assert_eq!(
            TlsMode::from_env_value(" disabled "),
            Some(TlsMode::Disabled)
        );
    }

    #[test]
    fn file_transport_filename_is_unique_for_same_recipient() {
        let mail = Mail::builder()
            .to("Ada Lovelace <ada@example.com>")
            .subject("Hello")
            .text("body")
            .build()
            .expect("mail should build");

        let first = file_transport_filename(&mail);
        let second = file_transport_filename(&mail);

        assert_ne!(first, second);
        assert!(
            Path::new(&first)
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("eml"))
        );
        assert!(
            Path::new(&second)
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("eml"))
        );
    }

    #[test]
    fn smtp_transport_rejects_missing_password_env_when_username_is_set() {
        let missing_key = format!(
            "AUTUMN_TEST_MISSING_SMTP_PASSWORD_{}_{}",
            std::process::id(),
            chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default()
        );
        let Err(error) = SmtpTransport::new(
            SmtpConfig {
                host: Some("smtp.example.com".to_owned()),
                port: Some(587),
                username: Some("mailer".to_owned()),
                password_env: Some(missing_key.clone()),
                tls: TlsMode::StartTls,
            },
            None,
        ) else {
            panic!("missing password env should fail at startup");
        };

        let displayed = error.to_string();
        assert!(displayed.contains(&missing_key));
        assert!(displayed.contains("environment variable is not set"));
    }

    #[test]
    fn smtp_password_env_error_never_embeds_the_secret_value() {
        // `std::env::VarError::NotUnicode` carries the raw contents of the
        // environment variable — i.e. the SMTP password itself. Formatting
        // that error directly (`{error}` or `{error:?}`) would leak the
        // secret into startup logs, so the redacting helper must map it to a
        // static reason instead.
        let secret = "hunter2-super-secret-password";
        let error = std::env::VarError::NotUnicode(std::ffi::OsString::from(secret));
        // Sanity check: the raw VarError does expose the value, which is
        // exactly why it must never be formatted into a MailError.
        assert!(error.to_string().contains(secret));
        assert!(format!("{error:?}").contains(secret));

        let mail_error = smtp_password_env_error("APP_SMTP_PASSWORD", &error);
        let displayed = mail_error.to_string();
        let debugged = format!("{mail_error:?}");
        assert!(
            !displayed.contains(secret),
            "Display output leaked the SMTP password: {displayed}"
        );
        assert!(
            !debugged.contains(secret),
            "Debug output leaked the SMTP password: {debugged}"
        );
        // The env var *name* is ordinary configuration and stays in the
        // message so operators can tell which variable is misconfigured.
        assert!(displayed.contains("APP_SMTP_PASSWORD"));
        assert!(displayed.contains("environment variable contains non-unicode data"));
    }

    #[test]
    fn smtp_password_env_error_redacts_missing_variable_details() {
        let error = std::env::VarError::NotPresent;
        let mail_error = smtp_password_env_error("APP_SMTP_PASSWORD", &error);
        let displayed = mail_error.to_string();
        assert!(displayed.contains("APP_SMTP_PASSWORD"));
        assert!(displayed.contains("environment variable is not set"));
    }

    #[test]
    fn smtp_transport_rejects_missing_password_env_key_when_username_is_set() {
        let Err(error) = SmtpTransport::new(
            SmtpConfig {
                host: Some("smtp.example.com".to_owned()),
                port: Some(587),
                username: Some("mailer".to_owned()),
                password_env: None,
                tls: TlsMode::StartTls,
            },
            None,
        ) else {
            panic!("missing password_env setting should fail at startup");
        };

        assert!(error.to_string().contains("mail.smtp.password_env"));
    }

    #[test]
    fn mailer_builder_rejects_invalid_default_from_address() {
        let Err(error) = Mailer::builder().from("not an email address").build() else {
            panic!("invalid default from should fail fast");
        };

        match error {
            MailError::InvalidAddress { address, .. } => {
                assert_eq!(address, "not an email address");
            }
            other => panic!("expected invalid address error, got {other:?}"),
        }
    }

    #[test]
    fn mailer_from_config_rejects_invalid_default_reply_to_address() {
        let config = MailConfig {
            transport: Transport::Smtp,
            from: Some("Autumn <noreply@example.com>".to_owned()),
            reply_to: Some("definitely not an address".to_owned()),
            smtp: SmtpConfig {
                host: Some("smtp.example.com".to_owned()),
                ..Default::default()
            },
            ..Default::default()
        };

        let Err(error) = Mailer::from_config(&config) else {
            panic!("invalid configured reply-to should fail at construction");
        };

        match error {
            MailError::InvalidAddress { address, .. } => {
                assert_eq!(address, "definitely not an address");
            }
            other => panic!("expected invalid address error, got {other:?}"),
        }
    }

    #[test]
    fn try_deliver_later_returns_error_without_runtime() {
        let mailer = Mailer::builder().build().expect("mailer should build");
        let mail = Mail::builder()
            .to("user@example.com")
            .subject("Hello")
            .text("hello")
            .build()
            .expect("mail should build");

        let error = mailer
            .try_deliver_later(mail)
            .expect_err("missing runtime should return an error");

        assert!(error.to_string().contains("active Tokio runtime"));
    }

    #[test]
    fn deliver_later_does_not_panic_without_runtime() {
        let mailer = Mailer::builder().build().expect("mailer should build");
        let mail = Mail::builder()
            .to("user@example.com")
            .subject("Hello")
            .text("hello")
            .build()
            .expect("mail should build");

        mailer.deliver_later(mail);
    }

    fn sample_smtp_config() -> MailConfig {
        MailConfig {
            transport: Transport::Smtp,
            from: Some("Autumn <noreply@example.com>".to_owned()),
            smtp: SmtpConfig {
                host: Some("smtp.example.com".to_owned()),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    fn sample_mail() -> Mail {
        Mail::builder()
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .build()
            .expect("mail should build")
    }

    struct NoopQueue;

    impl MailDeliveryQueue for NoopQueue {
        fn enqueue<'a>(
            &'a self,
            _mail: Mail,
        ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
            Box::pin(async { Ok(()) })
        }
    }

    #[test]
    fn install_mailer_rejects_in_process_fallback_in_prod_without_ack() {
        let state = crate::AppState::for_test().with_profile("prod");
        let config = sample_smtp_config();

        let error = install_mailer(&state, &config, true)
            .expect_err("prod must reject in-process deliver_later fallback without ack");

        let message = error.to_string();
        assert!(
            message.contains("allow_in_process_deliver_later_in_production"),
            "error should explain how to opt in: {message}"
        );
    }

    #[test]
    fn install_mailer_allows_in_process_fallback_in_prod_with_explicit_ack() {
        let state = crate::AppState::for_test().with_profile("prod");
        let config = MailConfig {
            allow_in_process_deliver_later_in_production: true,
            ..sample_smtp_config()
        };

        install_mailer(&state, &config, true).expect("explicit ack should permit fallback in prod");
    }

    #[test]
    fn install_mailer_allows_durable_queue_in_prod_without_ack() {
        let state = crate::AppState::for_test().with_profile("prod");
        state.insert_extension(MailDeliveryQueueHandle::new(NoopQueue));
        let config = sample_smtp_config();

        install_mailer(&state, &config, true)
            .expect("a registered durable queue should satisfy the prod guard");
    }

    #[test]
    fn install_mailer_does_not_require_ack_outside_production() {
        let state = crate::AppState::for_test().with_profile("dev");
        let config = sample_smtp_config();

        install_mailer(&state, &config, true).expect("non-prod profiles should not require an ack");
    }

    #[test]
    fn install_mailer_does_not_require_ack_when_transport_is_disabled() {
        let state = crate::AppState::for_test().with_profile("prod");
        let config = MailConfig::default();

        install_mailer(&state, &config, true)
            .expect("disabled transport never sends mail so it should not need an ack");
    }

    struct CapturingQueue {
        tx: tokio::sync::mpsc::UnboundedSender<Mail>,
    }

    impl MailDeliveryQueue for CapturingQueue {
        fn enqueue<'a>(
            &'a self,
            mail: Mail,
        ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
            let tx = self.tx.clone();
            Box::pin(async move {
                tx.send(mail)
                    .map_err(|err| MailError::RuntimeUnavailable(err.to_string()))?;
                Ok(())
            })
        }
    }

    #[cfg(feature = "db")]
    struct FailingQueue {
        tx: tokio::sync::mpsc::UnboundedSender<Mail>,
    }

    #[cfg(feature = "db")]
    impl MailDeliveryQueue for FailingQueue {
        fn enqueue<'a>(
            &'a self,
            mail: Mail,
        ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
            let tx = self.tx.clone();
            Box::pin(async move {
                tx.send(mail)
                    .map_err(|err| MailError::RuntimeUnavailable(err.to_string()))?;
                Err(MailError::RuntimeUnavailable("queue offline".to_owned()))
            })
        }
    }

    #[cfg(feature = "db")]
    async fn drain_after_commit_callbacks_for_test(
        registry: &std::sync::Arc<std::sync::Mutex<Vec<crate::db::CommitCallback>>>,
    ) {
        let callbacks: Vec<crate::db::CommitCallback> = {
            let mut reg = registry
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            std::mem::take(&mut *reg)
        };

        for cb in callbacks {
            if let Err(error) = cb().await {
                crate::db::record_after_commit_failure();
                tracing::error!("test drain: after_commit callback failed: {error}");
            }
        }
    }

    #[cfg(feature = "db")]
    #[tokio::test]
    async fn deferred_deliver_later_queue_failure_increments_after_commit_counter() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Mail>();
        let mailer = Mailer::builder()
            .delivery_queue(FailingQueue { tx })
            .build()
            .expect("mailer should build");
        let registry = std::sync::Arc::new(std::sync::Mutex::new(
            Vec::<crate::db::CommitCallback>::new(),
        ));
        let before =
            crate::db::AFTER_COMMIT_FAILURES_TOTAL.load(std::sync::atomic::Ordering::Relaxed);

        crate::db::AFTER_COMMIT_REGISTRY
            .scope(registry.clone(), async {
                mailer
                    .try_deliver_later(sample_mail())
                    .expect("registering deferred mail should succeed");
            })
            .await;

        drain_after_commit_callbacks_for_test(&registry).await;

        let received = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
            .await
            .expect("queue should be called within 1s")
            .expect("queue should receive the mail");
        assert_eq!(received.subject, "Hi");

        let after =
            crate::db::AFTER_COMMIT_FAILURES_TOTAL.load(std::sync::atomic::Ordering::Relaxed);
        assert!(
            after > before,
            "deferred durable mail handoff failures should count as after_commit failures"
        );
    }

    #[tokio::test]
    async fn deliver_later_routes_through_configured_queue() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Mail>();

        let mailer = Mailer::builder()
            .delivery_queue(CapturingQueue { tx })
            .build()
            .expect("mailer should build");

        mailer
            .try_deliver_later(sample_mail())
            .expect("scheduling onto the queue should succeed");

        let received = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
            .await
            .expect("queue should receive within 1s")
            .expect("queue should receive the mail");

        assert_eq!(received.subject, "Hi");
    }

    #[tokio::test]
    async fn deliver_later_preserves_attachments_through_queue() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Mail>();

        let mailer = Mailer::builder()
            .delivery_queue(CapturingQueue { tx })
            .build()
            .expect("mailer should build");

        let mail = Mail::builder()
            .to("user@example.com")
            .subject("Hi")
            .text("hello")
            .attach("invoice.pdf", "application/pdf", b"%PDF-1.4".to_vec())
            .build()
            .expect("mail should build");

        mailer
            .try_deliver_later(mail.clone())
            .expect("scheduling onto the queue should succeed");

        let received = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
            .await
            .expect("queue should receive within 1s")
            .expect("queue should receive the mail");

        // The deferred path freezes the originating mailer's CSS-inlining default
        // onto the message before enqueue (issue #1254); this mailer defaults
        // inlining off, so the enqueued job carries `Some(false)` where the
        // source had `None`. Everything else (notably attachments) is untouched.
        let mut expected = mail;
        expected.inline_css = Some(false);
        assert_eq!(received, expected);
    }

    #[tokio::test]
    async fn deferred_enqueue_freezes_originating_inline_css_default() {
        // A mailer whose config defaults CSS inlining ON must record that
        // decision on the persisted job when the message carries no explicit
        // override, so a worker consuming the durable queue (with a possibly
        // different/off default) still inlines. Only the flag is frozen — the
        // body is left un-inlined so the single inline pass happens once at the
        // consumer's send() (issue #1254).
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Mail>();
        let mailer = Mailer::builder()
            .inline_css(true)
            .delivery_queue(CapturingQueue { tx })
            .build()
            .expect("mailer should build");

        let mail = Mail::builder()
            .to("user@example.com")
            .subject("Hi")
            .html(
                "<html><head><style>p { color: red; }</style></head><body><p>hi</p></body></html>",
            )
            .build()
            .expect("mail should build");
        assert_eq!(mail.inline_css, None, "sample relies on the mailer default");

        mailer
            .try_deliver_later(mail)
            .expect("scheduling onto the queue should succeed");

        let received = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
            .await
            .expect("queue should receive within 1s")
            .expect("queue should receive the mail");

        assert_eq!(
            received.inline_css,
            Some(true),
            "the originating mailer's inlining default must be frozen onto the enqueued job"
        );
        assert!(
            received
                .html
                .as_deref()
                .expect("html body")
                .contains("<style>"),
            "the body must be left un-inlined at enqueue time; inlining happens once at the consumer's send()"
        );
    }

    #[tokio::test]
    async fn deferred_enqueue_preserves_explicit_inline_css_override() {
        // An explicit per-message `inline_css(false)` opt-out must survive the
        // durable-queue handoff and never be clobbered by the mailer default.
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Mail>();
        let mailer = Mailer::builder()
            .inline_css(true)
            .delivery_queue(CapturingQueue { tx })
            .build()
            .expect("mailer should build");

        let mail = Mail::builder()
            .to("user@example.com")
            .subject("Hi")
            .html(
                "<html><head><style>p { color: red; }</style></head><body><p>hi</p></body></html>",
            )
            .inline_css(false)
            .build()
            .expect("mail should build");

        mailer
            .try_deliver_later(mail)
            .expect("scheduling onto the queue should succeed");

        let received = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
            .await
            .expect("queue should receive within 1s")
            .expect("queue should receive the mail");

        assert_eq!(
            received.inline_css,
            Some(false),
            "an explicit per-message override must be preserved through the queue, not overwritten by the mailer default"
        );
    }

    #[tokio::test]
    async fn deliver_later_without_queue_sends_via_transport_directly() {
        // When no delivery queue is configured, `spawn_mail_delivery` falls back to
        // calling `mailer.send()` in a background task.
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};

        struct TrackingSend(Arc<AtomicBool>);
        impl MailTransport for TrackingSend {
            fn send<'a>(
                &'a self,
                _mail: Mail,
            ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
                self.0.store(true, Ordering::SeqCst);
                Box::pin(async { Ok(()) })
            }
        }

        let sent = Arc::new(AtomicBool::new(false));
        let mailer = Mailer::with_transport(TrackingSend(sent.clone()));

        mailer
            .try_deliver_later(sample_mail())
            .expect("should succeed without queue");

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        assert!(
            sent.load(Ordering::SeqCst),
            "mail should have been sent directly via transport"
        );
    }

    #[cfg(feature = "db")]
    #[tokio::test]
    async fn deferred_deliver_later_without_queue_sends_after_commit() {
        // After-commit callback with no queue falls back to `spawn_mail_delivery`
        // which calls `mailer.send()` in a spawned task.
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};

        struct TrackingSend(Arc<AtomicBool>);
        impl MailTransport for TrackingSend {
            fn send<'a>(
                &'a self,
                _mail: Mail,
            ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
                self.0.store(true, Ordering::SeqCst);
                Box::pin(async { Ok(()) })
            }
        }

        let sent = Arc::new(AtomicBool::new(false));
        let mailer = Mailer::with_transport(TrackingSend(sent.clone()));
        let registry = std::sync::Arc::new(std::sync::Mutex::new(
            Vec::<crate::db::CommitCallback>::new(),
        ));

        crate::db::AFTER_COMMIT_REGISTRY
            .scope(registry.clone(), async {
                mailer
                    .try_deliver_later(sample_mail())
                    .expect("should succeed");
            })
            .await;

        drain_after_commit_callbacks_for_test(&registry).await;
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        assert!(
            sent.load(Ordering::SeqCst),
            "mail should have been sent after commit via direct transport"
        );
    }

    #[tokio::test]
    async fn mailer_with_transport_starts_without_delivery_queue() {
        let mailer = Mailer::with_transport(NoopTransport);
        assert!(
            !mailer.has_durable_delivery_queue(),
            "with_transport should default to no durable queue"
        );
        // Exercise NoopTransport::send so its body is also covered.
        mailer
            .send(sample_mail())
            .await
            .expect("noop transport should always succeed");
    }

    struct NoopTransport;
    impl MailTransport for NoopTransport {
        fn send<'a>(
            &'a self,
            _mail: Mail,
        ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
            Box::pin(async { Ok(()) })
        }
    }

    #[tokio::test]
    async fn deliver_later_is_noop_when_transport_disabled_even_with_queue() {
        // The Mailer-level builder lets callers attach a queue *and* pick
        // Transport::Disabled. The disabled-transport contract requires
        // deliver_later to drop the message in that case — the queue must
        // not persist mail when the operator has turned mail off entirely.
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Mail>();
        let mailer = Mailer::builder()
            .transport(Transport::Disabled)
            .delivery_queue(CapturingQueue { tx })
            .build()
            .expect("mailer should build");

        mailer
            .try_deliver_later(sample_mail())
            .expect("disabled transport should succeed as a no-op");

        // Wait briefly for any spawn that might erroneously fire to land.
        let received = tokio::time::timeout(std::time::Duration::from_millis(100), rx.recv()).await;
        assert!(
            received.is_err(),
            "queue must not be invoked when transport is disabled"
        );
    }

    #[tokio::test]
    async fn deliver_later_uses_in_process_fallback_when_no_queue() {
        // The default Mailer has no durable queue, so deliver_later should
        // still spawn the in-process Tokio task and not call any queue.
        let mailer = Mailer::builder().build().expect("mailer should build");

        mailer
            .try_deliver_later(sample_mail())
            .expect("in-process fallback should still schedule");
    }

    #[test]
    fn mail_delivery_queue_handle_round_trips_via_from_arc_and_inner() {
        let arc: Arc<dyn MailDeliveryQueue> = Arc::new(NoopQueue);
        let handle = MailDeliveryQueueHandle::from_arc(Arc::clone(&arc));

        assert!(Arc::ptr_eq(handle.inner(), &arc));
    }

    #[test]
    fn mail_delivery_queue_handle_debug_does_not_panic() {
        let handle = MailDeliveryQueueHandle::new(NoopQueue);
        let rendered = format!("{handle:?}");
        assert!(rendered.contains("MailDeliveryQueueHandle"));
    }

    #[test]
    fn mailer_has_durable_delivery_queue_reflects_attachment() {
        let plain = Mailer::builder().build().expect("mailer should build");
        assert!(!plain.has_durable_delivery_queue());

        let with_queue = Mailer::builder()
            .delivery_queue(NoopQueue)
            .build()
            .expect("mailer should build");
        assert!(with_queue.has_durable_delivery_queue());
    }

    #[test]
    fn mailer_with_delivery_queue_post_build_attaches_queue() {
        let mailer = Mailer::builder()
            .build()
            .expect("mailer should build")
            .with_delivery_queue(NoopQueue);

        assert!(mailer.has_durable_delivery_queue());
    }

    #[test]
    fn mailer_builder_delivery_queue_arc_attaches_shared_queue() {
        let arc: Arc<dyn MailDeliveryQueue> = Arc::new(NoopQueue);
        let mailer = Mailer::builder()
            .delivery_queue_arc(arc)
            .build()
            .expect("mailer should build");

        assert!(mailer.has_durable_delivery_queue());
    }

    #[test]
    fn install_mailer_warns_but_succeeds_with_explicit_ack_in_prod() {
        // Same as the explicit-ack test, but also asserts the mailer was
        // actually inserted and has no durable queue attached.
        let state = crate::AppState::for_test().with_profile("prod");
        let config = MailConfig {
            allow_in_process_deliver_later_in_production: true,
            ..sample_smtp_config()
        };

        install_mailer(&state, &config, true).expect("explicit ack should permit fallback in prod");

        let installed = state
            .extension::<Mailer>()
            .expect("install_mailer should store a Mailer extension");
        assert!(
            !installed.has_durable_delivery_queue(),
            "no queue was registered, so installed mailer should fall back in-process"
        );
    }

    #[test]
    fn install_mailer_attaches_registered_queue_to_mailer() {
        let state = crate::AppState::for_test().with_profile("prod");
        state.insert_extension(MailDeliveryQueueHandle::new(NoopQueue));
        let config = sample_smtp_config();

        install_mailer(&state, &config, true).expect("durable queue should permit prod startup");

        let installed = state
            .extension::<Mailer>()
            .expect("install_mailer should store a Mailer extension");
        assert!(
            installed.has_durable_delivery_queue(),
            "registered queue handle should be attached to the installed mailer"
        );
    }

    #[test]
    fn install_mailer_with_factory_runs_factory_and_attaches_queue() {
        let state = crate::AppState::for_test().with_profile("prod");
        let config = sample_smtp_config();
        let factory_called = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let captured = Arc::clone(&factory_called);

        let factory = move |_state: &crate::AppState| {
            captured.store(true, std::sync::atomic::Ordering::SeqCst);
            Ok::<_, crate::AutumnError>(Arc::new(NoopQueue) as Arc<dyn MailDeliveryQueue>)
        };

        install_mailer_with_factory(&state, &config, Some(factory), true)
            .expect("factory should produce a queue and satisfy the prod guard");

        assert!(
            factory_called.load(std::sync::atomic::Ordering::SeqCst),
            "factory must run when enforce_durable_guard is true"
        );
        let installed = state
            .extension::<Mailer>()
            .expect("install_mailer should store a Mailer extension");
        assert!(
            installed.has_durable_delivery_queue(),
            "factory's queue should be wired into the installed Mailer"
        );
    }

    #[test]
    fn install_mailer_with_factory_skips_factory_when_not_enforced() {
        let state = crate::AppState::for_test().with_profile("prod");
        let config = sample_smtp_config();
        let factory_called = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let captured = Arc::clone(&factory_called);

        let factory = move |_state: &crate::AppState| {
            captured.store(true, std::sync::atomic::Ordering::SeqCst);
            Ok::<_, crate::AutumnError>(Arc::new(NoopQueue) as Arc<dyn MailDeliveryQueue>)
        };

        install_mailer_with_factory(&state, &config, Some(factory), false)
            .expect("static-build path should skip factory and install cleanly");

        assert!(
            !factory_called.load(std::sync::atomic::Ordering::SeqCst),
            "factory must be skipped when enforce_durable_guard is false"
        );
    }

    #[test]
    fn install_mailer_with_factory_propagates_factory_errors() {
        let state = crate::AppState::for_test().with_profile("prod");
        let config = sample_smtp_config();

        let factory = |_state: &crate::AppState| {
            Err::<Arc<dyn MailDeliveryQueue>, _>(crate::AutumnError::service_unavailable_msg(
                "queue offline",
            ))
        };

        let error = install_mailer_with_factory(&state, &config, Some(factory), true)
            .expect_err("factory error should propagate");
        assert!(error.to_string().contains("queue offline"));
    }

    #[test]
    fn install_mailer_with_factory_skips_factory_when_transport_disabled() {
        // Even when enforce_durable_guard=true (normal server path), a
        // profile with transport=disabled must not run the factory: the
        // factory might open Redis/Harvest/DB connections, but all mail in
        // this profile is supposed to be a no-op.
        let state = crate::AppState::for_test().with_profile("dev");
        let config = MailConfig::default(); // transport = Disabled
        let factory_called = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let captured = Arc::clone(&factory_called);

        let factory = move |_state: &crate::AppState| {
            captured.store(true, std::sync::atomic::Ordering::SeqCst);
            Err::<Arc<dyn MailDeliveryQueue>, _>(crate::AutumnError::service_unavailable_msg(
                "queue must not be reached",
            ))
        };

        install_mailer_with_factory(&state, &config, Some(factory), true)
            .expect("disabled transport should bypass the factory entirely");
        assert!(
            !factory_called.load(std::sync::atomic::Ordering::SeqCst),
            "factory must not run when transport = disabled"
        );
    }

    #[test]
    fn install_mailer_with_factory_works_without_factory() {
        type FactoryFn = fn(&crate::AppState) -> AutumnResult<Arc<dyn MailDeliveryQueue>>;
        let state = crate::AppState::for_test().with_profile("dev");
        let config = sample_smtp_config();
        let no_factory: Option<FactoryFn> = None;

        install_mailer_with_factory(&state, &config, no_factory, true)
            .expect("absent factory should be fine in non-prod");
    }

    #[test]
    fn install_mailer_does_not_run_factory_when_not_enforced_and_no_handle() {
        // Mirrors run_build_mode: queue factory is intentionally skipped, so
        // no MailDeliveryQueueHandle is on AppState. install_mailer must
        // tolerate this and not try to enforce or warn about a missing queue.
        let state = crate::AppState::for_test().with_profile("prod");
        let config = sample_smtp_config();

        install_mailer(&state, &config, false)
            .expect("static-build mode should install cleanly with no queue handle");

        let installed = state
            .extension::<Mailer>()
            .expect("install_mailer should store a Mailer extension");
        assert!(
            !installed.has_durable_delivery_queue(),
            "no queue is expected when run_build_mode skips the factory"
        );
    }

    #[test]
    fn install_mailer_skips_production_guard_when_not_enforced() {
        // Static-site builds (run_build_mode) call install_mailer with
        // enforce_durable_guard=false because they don't run the request
        // loop and don't actually defer mail. Even with a prod profile,
        // an active SMTP transport, no queue, and no ack flag, install
        // must succeed in this mode.
        let state = crate::AppState::for_test().with_profile("prod");
        let config = sample_smtp_config();

        install_mailer(&state, &config, false)
            .expect("static-build mode should not enforce the deliver_later guard");
    }

    #[test]
    fn spawn_mail_delivery_inherits_parent_span() {
        use std::future::Future;
        use std::pin::Pin;
        use std::sync::{Arc, Mutex};

        struct CapturingQueue(Arc<Mutex<Option<tracing::span::Id>>>);
        impl MailDeliveryQueue for CapturingQueue {
            fn enqueue<'a>(
                &'a self,
                _mail: Mail,
            ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
                let captured = self.0.clone();
                Box::pin(async move {
                    *captured.lock().unwrap() = tracing::Span::current().id();
                    Ok(())
                })
            }
        }

        let captured_span_id: Arc<Mutex<Option<tracing::span::Id>>> = Arc::new(Mutex::new(None));

        let mailer = Mailer::builder()
            .delivery_queue(CapturingQueue(captured_span_id.clone()))
            .build()
            .expect("mailer with queue should build");
        let mail = sample_mail();

        // The subscriber must remain active for the entire duration — spanning
        // both the enqueue call and the spawned task's execution — so that
        // `tracing::Span::current()` inside the task sees the same span tree
        // that was active when `try_deliver_later` was called.
        tracing::subscriber::with_default(tracing_subscriber::registry(), || {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("build runtime");

            let outer = tracing::info_span!("deliver_later_outer");
            let outer_id = outer.id();

            rt.block_on(async {
                {
                    let _guard = outer.enter();
                    mailer
                        .try_deliver_later(mail)
                        .expect("deliver_later must not fail");
                }

                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
            });

            let in_task = captured_span_id.lock().unwrap().clone();
            assert_eq!(
                in_task, outer_id,
                "delivery task must run inside the span that called deliver_later"
            );
        });
    }

    #[tokio::test]
    async fn spawn_mail_delivery_logs_error_when_queue_fails() {
        use std::future::Future;
        use std::pin::Pin;

        struct AlwaysFailQueue;
        impl MailDeliveryQueue for AlwaysFailQueue {
            fn enqueue<'a>(
                &'a self,
                _mail: Mail,
            ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
                Box::pin(async { Err(MailError::RuntimeUnavailable("always fails".to_owned())) })
            }
        }

        let mailer = Mailer::builder()
            .delivery_queue(AlwaysFailQueue)
            .build()
            .expect("build");

        mailer
            .try_deliver_later(sample_mail())
            .expect("should schedule");

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }

    #[tokio::test]
    async fn spawn_mail_delivery_logs_error_when_transport_fails() {
        use std::future::Future;
        use std::pin::Pin;

        struct AlwaysFailTransport;
        impl MailTransport for AlwaysFailTransport {
            fn send<'a>(
                &'a self,
                _mail: Mail,
            ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
                Box::pin(async {
                    Err(MailError::RuntimeUnavailable(
                        "transport offline".to_owned(),
                    ))
                })
            }
        }

        let mailer = Mailer::with_transport(AlwaysFailTransport);

        mailer
            .try_deliver_later(sample_mail())
            .expect("should schedule");

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }

    #[test]
    fn install_mailer_does_not_attach_queue_when_transport_disabled() {
        // When mail.transport = "disabled" the operator has explicitly turned
        // mail off for this profile (tests, review apps, etc.). A globally
        // registered queue must not turn deliver_later back into a durable
        // persist; it should remain a no-op.
        let state = crate::AppState::for_test().with_profile("dev");
        state.insert_extension(MailDeliveryQueueHandle::new(NoopQueue));
        let config = MailConfig::default(); // transport = Disabled

        install_mailer(&state, &config, true).expect("disabled transport should install cleanly");

        let installed = state
            .extension::<Mailer>()
            .expect("install_mailer should store a Mailer extension");
        assert!(
            !installed.has_durable_delivery_queue(),
            "disabled transport must suppress queue attachment so deliver_later is a no-op"
        );
    }

    #[tokio::test]
    async fn intercepted_mail_transport_short_circuit_prevents_sync_execution() {
        use std::future::Future;
        use std::pin::Pin;
        use std::sync::atomic::{AtomicU32, Ordering};

        static TRANSPORT_CALLS: AtomicU32 = AtomicU32::new(0);

        struct CountingTransport;
        impl MailTransport for CountingTransport {
            fn send<'a>(
                &'a self,
                _mail: Mail,
            ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
                TRANSPORT_CALLS.fetch_add(1, Ordering::SeqCst);
                Box::pin(async move { Ok(()) })
            }

            fn is_disabled(&self) -> bool {
                false
            }
        }

        struct ShortCircuitMailInterceptor;
        impl crate::interceptor::MailInterceptor for ShortCircuitMailInterceptor {
            fn intercept<'a>(
                &'a self,
                _mail: &'a Mail,
                _next: Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>>,
            ) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>> {
                Box::pin(async move {
                    Err(MailError::RuntimeUnavailable(
                        "blocked by interceptor".to_owned(),
                    ))
                })
            }
        }

        let transport = Arc::new(CountingTransport);
        let interceptor = Arc::new(ShortCircuitMailInterceptor);
        let intercepted = InterceptedMailTransport {
            inner: transport,
            interceptor,
        };

        let mail = Mail::builder()
            .to("test@example.com")
            .subject("test")
            .text("body")
            .build()
            .unwrap();

        TRANSPORT_CALLS.store(0, Ordering::SeqCst);

        let res = intercepted.send(mail).await;
        assert!(res.is_err());
        assert_eq!(TRANSPORT_CALLS.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn test_smtp_transport_circuit_breaker() {
        let _lock = crate::circuit_breaker::TEST_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        crate::circuit_breaker::global_registry().clear();
        let policy = crate::circuit_breaker::CircuitBreakerPolicy {
            failure_ratio_threshold: 0.5,
            sample_window: std::time::Duration::from_secs(10),
            minimum_sample_count: 3,
            open_duration: std::time::Duration::from_secs(60),
            half_open_trial_count: 2,
        };
        let breaker =
            crate::circuit_breaker::global_registry().get_or_create("smtp_mailer", policy);

        // Ensure it is closed initially
        assert_eq!(
            breaker.state(),
            crate::circuit_breaker::CircuitState::Closed
        );

        // Build an SMTP transport pointing to a bogus localhost port so it fails
        let config = SmtpConfig {
            host: Some("127.0.0.1".to_string()),
            port: Some(9999), // Bogus port
            tls: TlsMode::Disabled,
            username: None,
            password_env: None,
        };
        let transport = SmtpTransport::new(config, None).unwrap();

        let mail = Mail::builder()
            .from("sender@example.com")
            .to("test@example.com")
            .subject("test")
            .text("body")
            .build()
            .unwrap();

        // Send 3 times — all should fail and trip the breaker
        for _ in 0..3 {
            let res = transport.send(mail.clone()).await;
            assert!(res.is_err());
        }

        assert_eq!(breaker.state(), crate::circuit_breaker::CircuitState::Open);

        // 4th send should fail fast with a circuit breaker error
        let res = transport.send(mail.clone()).await;
        assert!(res.is_err());
        let err_str = res.err().unwrap().to_string();
        assert!(
            err_str.contains("circuit breaker")
                || err_str.contains("open")
                || err_str.contains("Open")
                || err_str.contains("runtime unavailable")
        );

        crate::circuit_breaker::global_registry().clear();
    }

    #[test]
    fn validate_log_transport_in_prod_fails() {
        let cfg = MailConfig {
            transport: Transport::Log,
            ..MailConfig::default()
        };
        assert!(cfg.validate(Some("prod")).is_err());
        assert!(cfg.validate(Some("production")).is_err());
        // allow flag lifts the restriction.
        let allowed = MailConfig {
            transport: Transport::Log,
            allow_log_in_production: true,
            ..MailConfig::default()
        };
        assert!(allowed.validate(Some("prod")).is_ok());
    }

    #[test]
    fn validate_preview_outside_dev_fails() {
        let cfg = MailConfig {
            preview: true,
            ..MailConfig::default()
        };
        assert!(cfg.validate(Some("prod")).is_err());
        assert!(cfg.validate(Some("dev")).is_ok());
        assert!(cfg.validate(Some("development")).is_ok());
    }

    #[test]
    fn is_valid_https_base_url_edge_cases() {
        assert!(is_valid_https_base_url("https://app.example.com"));
        assert!(is_valid_https_base_url("https://app.example.com/base"));
        assert!(!is_valid_https_base_url("http://app.example.com"));
        assert!(!is_valid_https_base_url("https://"));
        assert!(!is_valid_https_base_url("https:///path"));
        assert!(!is_valid_https_base_url("https://app.example.com?q=1"));
        assert!(!is_valid_https_base_url("https://app.example.com#frag"));
        assert!(!is_valid_https_base_url("https://host name.com"));
        // Malformed authorities that a naive `/`-split would wrongly accept.
        assert!(!is_valid_https_base_url("https://app.example.com:abc"));
        assert!(!is_valid_https_base_url("https://@/base"));
        assert!(!is_valid_https_base_url("https://user@app.example.com"));
        // A valid explicit port is fine.
        assert!(is_valid_https_base_url("https://app.example.com:8443"));
        // Characters unsafe inside an RFC 2369 angle-bracket URI are rejected,
        // even though `Url::parse` would percent-encode them.
        assert!(!is_valid_https_base_url("https://example.com/<x>"));
        assert!(!is_valid_https_base_url("https://example.com/a b"));
        assert!(!is_valid_https_base_url("https://example.com/a\r\nb"));
        // Missing/short authority that `Url::parse` would normalize to a valid
        // host — rejected so prod can't advertise an unusable one-click URL.
        assert!(!is_valid_https_base_url("https:/app.example.com"));
        assert!(!is_valid_https_base_url("https:app.example.com"));
    }

    #[test]
    fn is_valid_mailto_address_edge_cases() {
        assert!(is_valid_mailto_address("unsub@example.com"));
        assert!(is_valid_mailto_address("mailto:unsub@example.com"));
        assert!(is_valid_mailto_address(
            "mailto:unsub@example.com?subject=hi"
        ));
        assert!(!is_valid_mailto_address("not-an-email"));
        assert!(!is_valid_mailto_address("missing@dot"));
        assert!(!is_valid_mailto_address("space @example.com"));
        assert!(!is_valid_mailto_address(""));
        assert!(!is_valid_mailto_address("@example.com")); // empty local
        assert!(!is_valid_mailto_address("local@")); // empty domain
        // Other URI schemes must be rejected, not coerced into <mailto:…>.
        assert!(!is_valid_mailto_address("https://unsub@example.com"));
        assert!(!is_valid_mailto_address("mailto:https://unsub@example.com"));
        assert!(!is_valid_mailto_address("unsub@https://example.com"));
        // CRLF / control characters (header-injection attempt) are rejected even
        // when hidden behind a `?query` the address check would otherwise drop.
        assert!(!is_valid_mailto_address(
            "mailto:unsub@example.com?subject=x\r\nBcc: victim@example.com"
        ));
        assert!(!is_valid_mailto_address("unsub@example.com\nBcc: v@x.com"));
        // RFC 2369 delimiters (`<`/`>`/`,`) would close the angle-bracket entry
        // and inject an extra List-Unsubscribe target.
        assert!(!is_valid_mailto_address(
            "unsub@example.com>,<bogus@example.com"
        ));
        assert!(!is_valid_mailto_address("a@x.com,b@x.com"));
    }

    #[test]
    fn unsubscribe_header_mailto_drops_configured_query_no_injection() {
        // Even if a malformed value slipped past validation (e.g. set outside
        // prod), the rendered header must carry only the bare mailbox plus the
        // canonical subject — never an injected CRLF/Bcc.
        let runtime = UnsubscribeRuntime {
            base_url: None,
            mailto: Some("mailto:u@example.com?subject=x\r\nBcc: v@x.com".to_owned()),
            signing_keys: Arc::new(test_keys()),
            ttl_days: 30,
            suppression: None,
        };
        let header = runtime
            .list_unsubscribe_header("a@x.com", "list")
            .expect("mailto header");
        assert_eq!(header, "<mailto:u@example.com?subject=unsubscribe>");
        assert!(!header.contains('\r') && !header.contains('\n'));
        assert!(!header.contains("Bcc"));
    }

    #[test]
    fn unsubscribe_runtime_header_both_base_url_and_mailto() {
        let runtime = UnsubscribeRuntime {
            base_url: Some("https://app.example.com".to_owned()),
            mailto: Some("u@example.com".to_owned()),
            signing_keys: Arc::new(test_keys()),
            ttl_days: 30,
            suppression: None,
        };
        let header = runtime
            .list_unsubscribe_header("a@x.com", "list")
            .expect("header with both");
        assert!(header.contains("https://app.example.com/_autumn/unsubscribe?token="));
        assert!(header.contains("mailto:u@example.com?subject=unsubscribe"));
        assert!(runtime.supports_one_click());
    }

    #[test]
    fn unsubscribe_runtime_header_neither_configured_returns_none() {
        let runtime = UnsubscribeRuntime {
            base_url: None,
            mailto: None,
            signing_keys: Arc::new(test_keys()),
            ttl_days: 30,
            suppression: None,
        };
        assert!(runtime.list_unsubscribe_header("a@x.com", "list").is_none());
        assert!(!runtime.supports_one_click());
    }
}