autumn-cli 0.8.0

CLI tool for the Autumn web framework
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
//! `autumn generate mailer` — scaffold a `#[mailer]` struct, HTML+text templates,
//! preview registration, and a smoke test.
//!
//! For a name like `Welcome`, the generator produces:
//! - `templates/mailers/_layout.html` / `_layout.txt` — shared email layout shell
//!   (created once; subsequent `generate mailer` calls skip if already present).
//! - `src/mailers/welcome.rs` — `WelcomeMailer` struct with a `#[mailer]` impl.
//!   The macro generates `send_welcome` (async) and `deliver_later_welcome`
//!   (fire-and-forget) from each method.
//! - `src/mailers/previews/welcome.rs` — dev-only `#[mailer_preview]` impl,
//!   kept separate from production code (mirrors Rails `test/mailers/previews/`).
//! - `src/mailers/previews/mod.rs` — created or updated with `pub mod welcome;`.
//! - `templates/mailers/welcome.html` — HTML body fragment (no `<head>`/`<body>`).
//! - `templates/mailers/welcome.txt` — plain-text body fragment.
//! - `src/mailers/mod.rs` — created or updated with `pub mod welcome;` and
//!   `pub mod previews;`.
//! - `src/main.rs` — `mod mailers;` declaration and
//!   `.mail_previews(mail_previews![mailers::welcome::WelcomeMailer])` wired
//!   into the app builder chain.
//! - `Cargo.toml` — `"mail"` feature added to the `autumn-web` dependency.
//!
//! Use `--no-layout` to opt out of the shared layout for a specific mailer.

use std::path::{Path, PathBuf};

use super::emit::Plan;
use super::model::validate_resource_name;
use super::naming::{pascal, snake};
use super::schema_edit::{
    add_mail_preview_to_app, add_mod_declaration, ensure_autumn_web_feature, update_main_rs,
};
use super::{GenerateError, ensure_project_root, read_or_empty, timestamp_now};

/// Compute the file actions for `autumn generate mailer`.
///
/// When `list_unsubscribe` is `Some(scope)`, the mailer opts into RFC 8058
/// one-click List-Unsubscribe and a `mail_unsubscribes` suppression migration
/// is added (idempotently).
///
/// When `no_layout` is `true`, the per-mailer template is emitted as a
/// self-contained full HTML document and the generated mailer omits the
/// `.layout(...)` builder call — useful for one-line plaintext or fully-custom
/// HTML. When `false` (the default), a shared `_layout.html`/`_layout.txt` is
/// created (idempotently) and the generated mailer composes the body fragment
/// into the layout slot at build time.
///
/// # Errors
/// Project layout and name validation errors surface here.
pub fn plan_mailer(
    project_root: &Path,
    name: &str,
    list_unsubscribe: Option<&str>,
    no_layout: bool,
) -> Result<Plan, GenerateError> {
    plan_mailer_ex(project_root, name, list_unsubscribe, no_layout, false)
}

/// Shared implementation of [`plan_mailer`]. The `_for_revert` flag is retained
/// for `destroy`-path symmetry with the other generators, but the mailer
/// generator no longer branches on it: the `--list-unsubscribe` suppression
/// migration is now backend-aware (`SQLite`-dialect DDL under a `SQLite` app,
/// issue #1927), so there is no generate-only rejection left to suppress on the
/// revert path.
///
/// # Errors
/// Project layout and name validation errors surface here.
#[allow(
    clippy::too_many_lines,
    reason = "linear sequence of independent file/revert steps mirroring the files this \
              generator emits; splitting it up would not make any single step clearer"
)]
pub fn plan_mailer_ex(
    project_root: &Path,
    name: &str,
    list_unsubscribe: Option<&str>,
    no_layout: bool,
    _for_revert: bool,
) -> Result<Plan, GenerateError> {
    ensure_project_root(project_root)?;
    validate_resource_name(name)?;
    if let Some(scope) = list_unsubscribe {
        validate_list_unsubscribe_scope(scope)?;
    }

    let snake_name = snake(name);
    let pascal_name = pascal(name);
    let struct_name = format!("{pascal_name}Mailer");
    let mailer_type = format!("mailers::{snake_name}::{struct_name}");

    let mut plan = Plan::new(project_root);

    // ── templates/mailers/_layout.html (idempotent) ────────────────────────
    // Created on the first `generate mailer` call; subsequent calls skip it so
    // user edits to the shared layout are not overwritten. Uses create_if_absent
    // so concurrent generator runs are safe (exclusive-create, no TOCTOU race).
    if !no_layout {
        plan.create_if_absent(
            project_root
                .join("templates")
                .join("mailers")
                .join("_layout.html"),
            render_layout_html(),
        );

        plan.create_if_absent(
            project_root
                .join("templates")
                .join("mailers")
                .join("_layout.txt"),
            render_layout_txt(),
        );
    }

    // ── src/mailers/<snake>.rs ─────────────────────────────────────────────
    plan.create(
        project_root
            .join("src")
            .join("mailers")
            .join(format!("{snake_name}.rs")),
        render_mailer_file(&struct_name, &snake_name, list_unsubscribe, no_layout),
    );

    // ── templates/mailers/<snake>.html ─────────────────────────────────────
    plan.create(
        project_root
            .join("templates")
            .join("mailers")
            .join(format!("{snake_name}.html")),
        render_html_template(&struct_name, no_layout),
    );

    // ── templates/mailers/<snake>.txt ──────────────────────────────────────
    plan.create(
        project_root
            .join("templates")
            .join("mailers")
            .join(format!("{snake_name}.txt")),
        render_txt_template(&struct_name, no_layout),
    );

    // ── src/mailers/previews/<snake>.rs ────────────────────────────────────
    plan.create(
        project_root
            .join("src")
            .join("mailers")
            .join("previews")
            .join(format!("{snake_name}.rs")),
        render_preview_file(&struct_name, &snake_name, no_layout),
    );

    // ── src/mailers/previews/mod.rs (create or update) ─────────────────────
    let previews_mod_path = project_root
        .join("src")
        .join("mailers")
        .join("previews")
        .join("mod.rs");
    plan.modify(
        previews_mod_path.clone(),
        add_mod_declaration(&read_or_empty(&previews_mod_path), &snake_name),
    );
    plan.push_revert(crate::generate::emit::Revert::ModDecl {
        path: previews_mod_path,
        name: snake_name.clone(),
    });

    // ── src/mailers/mod.rs (create or update) ──────────────────────────────
    // The "previews" sub-module declared here is shared by every generated
    // mailer, not owned by this one — `emit::sync_mod_declarations_in`
    // removes it once `src/mailers/previews/mod.rs` no longer exists, so no
    // static revert is pushed for it here.
    let mod_path = project_root.join("src").join("mailers").join("mod.rs");
    let with_mailer_mod = add_mod_declaration(&read_or_empty(&mod_path), &snake_name);
    let with_both_mods = add_mod_declaration(&with_mailer_mod, "previews");
    plan.modify(mod_path.clone(), with_both_mods);
    plan.push_revert(crate::generate::emit::Revert::ModDecl {
        path: mod_path,
        name: snake_name,
    });

    // ── src/main.rs: add mod mailers; and .mail_previews(…) ────────────────
    let main_path = project_root.join("src").join("main.rs");
    let main_existing = std::fs::read_to_string(&main_path).map_err(|e| {
        GenerateError::Io(std::io::Error::new(
            e.kind(),
            format!("{}: {e}", main_path.display()),
        ))
    })?;
    let with_mods = update_main_rs(&main_existing, &["mailers"], &[]);
    let updated_main = add_mail_preview_to_app(&with_mods, &mailer_type);
    plan.modify(main_path.clone(), updated_main);
    plan.push_revert(crate::generate::emit::Revert::MailPreview {
        path: main_path,
        mailer_type,
    });

    // ── Cargo.toml: ensure autumn-web has the "mail" feature ───────────────
    let cargo_path = project_root.join("Cargo.toml");
    let cargo_existing = read_or_empty(&cargo_path);
    let updated_cargo = ensure_autumn_web_feature(&cargo_existing, "mail");
    if updated_cargo != cargo_existing {
        plan.modify(cargo_path.clone(), updated_cargo);
    }
    plan.push_revert(crate::generate::emit::Revert::CargoAutumnWebFeature {
        path: cargo_path,
        feature: "mail".to_owned(),
        owner_dir: Some(project_root.join("src").join("mailers")),
    });

    // ── migrations/<ts>_create_mail_unsubscribes (opt-in, idempotent) ──────
    if list_unsubscribe.is_some() {
        // The suppression migration is backend-aware (issue #1927): a SQLite app
        // gets SQLite-dialect DDL (`INTEGER PRIMARY KEY AUTOINCREMENT`,
        // `DEFAULT CURRENT_TIMESTAMP`) instead of the Postgres-only
        // `BIGSERIAL`/`NOW()` form, so the generated migration applies on either
        // backend.
        let backend = super::detect_backend(project_root);
        plan_unsubscribe_migration(project_root, &mut plan, backend);
    }

    Ok(plan)
}

/// Validate a `--list-unsubscribe` scope. Restricted to a safe identifier-like
/// charset so it can be embedded verbatim in a generated Rust string literal and
/// used as a stable logical list id (DB key, token claim) without escaping.
fn validate_list_unsubscribe_scope(scope: &str) -> Result<(), GenerateError> {
    if scope.is_empty() {
        return Err(GenerateError::InvalidName(
            scope.to_owned(),
            "list_unsubscribe scope cannot be empty".into(),
        ));
    }
    if !scope
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
    {
        return Err(GenerateError::InvalidName(
            scope.to_owned(),
            "list_unsubscribe scope may only contain ASCII letters, digits, '_' or '-'".into(),
        ));
    }
    Ok(())
}

/// Add the `mail_unsubscribes` suppression migration, reusing the existing
/// one (by its real on-disk path) if a prior mailer already created it.
///
/// The old design skipped pushing any action at all once a
/// `*_create_mail_unsubscribes` directory existed — correct for `generate`,
/// but it meant a second `--list-unsubscribe` mailer's plan carried no
/// migration action, so `autumn destroy` recomputing that same plan could
/// never locate (and thus never remove) the suppression migration. Instead,
/// always push `create_if_absent` actions, targeting the *existing*
/// directory's real path when one is already on disk (so `generate` is
/// still a silent no-op there) and a fresh timestamp only when none exists
/// yet. Either way the action is present for `autumn destroy`'s
/// suffix-based migration matching (`resolve_migration_removal`) to find.
fn plan_unsubscribe_migration(
    project_root: &Path,
    plan: &mut Plan,
    backend: autumn_web::config::DatabaseBackend,
) {
    let migrations_dir = project_root.join("migrations");
    let dir = existing_mail_unsubscribes_dir(&migrations_dir).unwrap_or_else(|| {
        migrations_dir.join(format!("{}_create_mail_unsubscribes", timestamp_now()))
    });
    plan.create_if_absent(
        dir.join("up.sql"),
        unsubscribe_migration_up(backend).to_owned(),
    );
    plan.create_if_absent(dir.join("down.sql"), UNSUBSCRIBE_MIGRATION_DOWN.to_owned());
}

/// The `mail_unsubscribes` `up.sql` for the target `backend` (issue #1927).
///
/// Postgres keeps the historical DDL byte-for-byte (`BIGSERIAL PRIMARY KEY`,
/// `TIMESTAMPTZ NOT NULL DEFAULT NOW()`). `SQLite` — which has neither
/// `BIGSERIAL` nor `NOW()` nor a dedicated timestamp type — gets the portable
/// form (`INTEGER PRIMARY KEY AUTOINCREMENT`, ISO-8601 `TEXT ... DEFAULT
/// CURRENT_TIMESTAMP`), matching the `SQLite` dialect the backend-aware
/// model/migration generators emit.
const fn unsubscribe_migration_up(backend: autumn_web::config::DatabaseBackend) -> &'static str {
    match backend {
        autumn_web::config::DatabaseBackend::Postgres => UNSUBSCRIBE_MIGRATION_UP,
        autumn_web::config::DatabaseBackend::Sqlite => UNSUBSCRIBE_MIGRATION_UP_SQLITE,
    }
}

/// The real on-disk `*_create_mail_unsubscribes` migration directory, if one
/// already exists (from a previous `--list-unsubscribe` mailer).
fn existing_mail_unsubscribes_dir(migrations_dir: &Path) -> Option<PathBuf> {
    let entries = std::fs::read_dir(migrations_dir).ok()?;
    entries.filter_map(Result::ok).map(|e| e.path()).find(|p| {
        p.is_dir()
            && p.file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|name| name.ends_with("_create_mail_unsubscribes"))
    })
}

const UNSUBSCRIBE_MIGRATION_UP: &str = "\
-- Suppression list for RFC 8058 List-Unsubscribe.
-- Keyed by (subscriber, list_id, unsubscribed_at); send-time checks skip any
-- recipient with a matching (subscriber, list_id) row.
CREATE TABLE mail_unsubscribes (
    id BIGSERIAL PRIMARY KEY,
    subscriber TEXT NOT NULL,
    list_id TEXT NOT NULL,
    unsubscribed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (subscriber, list_id)
);
";

/// `SQLite`-dialect companion to [`UNSUBSCRIBE_MIGRATION_UP`] (issue #1927):
/// `INTEGER PRIMARY KEY AUTOINCREMENT` for the id and an ISO-8601 `TEXT` column
/// defaulted to `CURRENT_TIMESTAMP` (`SQLite` has no `BIGSERIAL`, `TIMESTAMPTZ`,
/// or `NOW()`). The `UNIQUE` constraint and column names are portable and
/// unchanged.
const UNSUBSCRIBE_MIGRATION_UP_SQLITE: &str = "\
-- Suppression list for RFC 8058 List-Unsubscribe.
-- Keyed by (subscriber, list_id, unsubscribed_at); send-time checks skip any
-- recipient with a matching (subscriber, list_id) row.
CREATE TABLE mail_unsubscribes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    subscriber TEXT NOT NULL,
    list_id TEXT NOT NULL,
    unsubscribed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE (subscriber, list_id)
);
";

const UNSUBSCRIBE_MIGRATION_DOWN: &str = "DROP TABLE mail_unsubscribes;\n";

fn render_mailer_file(
    struct_name: &str,
    snake_name: &str,
    list_unsubscribe: Option<&str>,
    no_layout: bool,
) -> String {
    let mailer_attr = list_unsubscribe.map_or_else(
        || "#[mailer]".to_owned(),
        |scope| format!("#[mailer(list_unsubscribe = \"{scope}\")]"),
    );
    let layout_call = if no_layout {
        String::new()
    } else {
        "\n            .layout(\n                include_str!(\"../../templates/mailers/_layout.html\"),\n                include_str!(\"../../templates/mailers/_layout.txt\"),\n            )".to_owned()
    };
    let base = format!(
        r#"//! Generated by `autumn generate mailer`.
//!
//! Edit freely — once generated, this is ordinary user code.
//!
//! The `#[mailer]` macro generates two helpers for every method:
//!   - `send_{snake_name}` — async, awaits delivery.
//!   - `deliver_later_{snake_name}` — fire-and-forget (uses `deliver_later` semantics).
//!
//! Dev-only preview fixtures live in `src/mailers/previews/{snake_name}.rs`.

use autumn_web::prelude::*;

pub struct {struct_name};

{mailer_attr}
impl {struct_name} {{
    pub fn {snake_name}(&self, to: String) -> Mail {{
        Mail::builder()
            .to(to)
            .subject("{struct_name}")
            .html(include_str!("../../templates/mailers/{snake_name}.html"))
            .text(include_str!("../../templates/mailers/{snake_name}.txt")){layout_call}
            // Rewrite the template's `<style>` rules onto elements as inline
            // `style="…"` attributes at send time, so the mail renders styled in
            // Gmail/Outlook (which strip `<head>`/`<style>`). See issue #1254.
            .inline_css(true)
            .build()
            .expect("valid mail")
    }}
}}
"#
    );
    format!(
        "{}{}",
        base,
        render_smoke_test(struct_name, snake_name, no_layout)
    )
}

fn render_preview_file(struct_name: &str, snake_name: &str, no_layout: bool) -> String {
    let layout_call = if no_layout {
        String::new()
    } else {
        "\n            .layout(\n                include_str!(\"../../../templates/mailers/_layout.html\"),\n                include_str!(\"../../../templates/mailers/_layout.txt\"),\n            )".to_owned()
    };
    format!(
        r#"//! Dev-only mail preview for [`{struct_name}`].
//!
//! Generated by `autumn generate mailer`. Edit freely.
//!
//! The `#[mailer_preview]` macro exposes preview fixtures to the Autumn
//! dev UI at `/_autumn/mail`. Methods must be zero-argument and return `Mail`.

use autumn_web::prelude::*;
use crate::mailers::{snake_name}::{struct_name};

#[mailer_preview]
impl {struct_name} {{
    fn {snake_name}_preview() -> Mail {{
        Mail::builder()
            .to("preview@example.com")
            .subject("{struct_name}")
            .html(include_str!("../../../templates/mailers/{snake_name}.html"))
            .text(include_str!("../../../templates/mailers/{snake_name}.txt")){layout_call}
            // Match the production mailer's opt-in so the preview renders the
            // `<style>` rules inlined regardless of the app's `mail.inline_css`
            // config default. See issue #1254.
            .inline_css(true)
            .build()
            .expect("valid preview mail")
    }}
}}
"#
    )
}

/// Shared HTML layout shell. Contains the document skeleton (charset, viewport,
/// table-based responsive wrapper with inline CSS, header, body slot, footer).
/// Per-mailer templates are body-only fragments composed into `{{ content }}`.
fn render_layout_html() -> String {
    r#"<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
</head>
<body style="margin:0;padding:0;background-color:#f4f4f4;font-family:Arial,Helvetica,sans-serif;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color:#f4f4f4;">
    <tr>
      <td align="center" style="padding:24px 0;">
        <!-- Header / branding -->
        <table role="presentation" width="600" cellspacing="0" cellpadding="0" border="0" style="max-width:600px;width:100%;background-color:#ffffff;border-radius:6px;overflow:hidden;">
          <tr>
            <td style="background-color:#1a1a2e;padding:24px 32px;">
              <p style="margin:0;color:#ffffff;font-size:20px;font-weight:bold;">Your App</p>
            </td>
          </tr>
          <!-- Body content slot -->
          <tr>
            <td style="padding:32px;">
              {{ content }}
            </td>
          </tr>
          <!-- Footer -->
          <tr>
            <td style="background-color:#f4f4f4;padding:16px 32px;border-top:1px solid #e0e0e0;">
              <p style="margin:0;font-size:12px;color:#888888;text-align:center;">
                You are receiving this email because you signed up for our service.
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
"#
    .to_owned()
}

/// Shared plain-text layout shell.
fn render_layout_txt() -> String {
    "========================================\n\
     Your App\n\
     ========================================\n\
     \n\
     {{ content }}\n\
     \n\
     ----------------------------------------\n\
     You are receiving this email because you signed up for our service.\n"
        .to_owned()
}

/// Per-mailer HTML body fragment. No `<!DOCTYPE>`, `<head>`, or `<body>` —
/// those belong in `_layout.html`. When `no_layout` is `true` a self-contained
/// full document is emitted instead.
fn render_html_template(struct_name: &str, no_layout: bool) -> String {
    if no_layout {
        // Full self-contained document with a `<head>` `<style>` block. The
        // generated mailer calls `.inline_css(true)`, so these class rules are
        // rewritten onto the elements as inline `style="…"` at send time and
        // render in Gmail/Outlook (which drop `<head>`/`<style>`). See #1254.
        format!(
            "<!DOCTYPE html>\n\
             <html>\n\
             <head>\n\
               <meta charset=\"utf-8\">\n\
               <style>\n\
            \x20    .lead {{ font-size:16px; line-height:1.6; color:#333333; }}\n\
               </style>\n\
             </head>\n\
             <body>\n\
               <p class=\"lead\">Hello from {struct_name}!</p>\n\
             </body>\n\
             </html>\n"
        )
    } else {
        // Authored with a `<style>` block + CSS classes — the ergonomic way to
        // style email. The generated mailer calls `.inline_css(true)`, so at
        // send time Autumn rewrites these rules onto the elements as
        // `style="…"` attributes (issue #1254); that is what makes them render
        // in Gmail/Outlook, which strip `<head>`/`<style>`. The `@media` rule is
        // preserved in a retained `<style>` block for clients that honor it.
        format!(
            "<style>\n\
            \x20 .greeting {{ margin:0 0 16px; font-size:24px; color:#1a1a2e; }}\n\
            \x20 .lead {{ margin:0 0 24px; font-size:16px; line-height:1.6; color:#333333; }}\n\
            \x20 .btn {{ display:inline-block; padding:12px 20px; background:#1a1a2e; color:#ffffff; text-decoration:none; border-radius:4px; }}\n\
            \x20 @media (max-width:600px) {{ .btn {{ display:block; text-align:center; }} }}\n\
             </style>\n\
             <h1 class=\"greeting\">Hello from {struct_name}!</h1>\n\
             <p class=\"lead\">Your email body goes here.</p>\n\
             <a class=\"btn\" href=\"https://example.com\">Call to action</a>\n"
        )
    }
}

/// Per-mailer plain-text body fragment. When `no_layout` is `true` a
/// self-contained message is emitted instead.
fn render_txt_template(struct_name: &str, no_layout: bool) -> String {
    if no_layout {
        format!("Hello from {struct_name}!\n")
    } else {
        format!("Hello from {struct_name}!\n\nYour email body goes here.\n")
    }
}

fn render_smoke_test(struct_name: &str, snake_name: &str, no_layout: bool) -> String {
    let layout_assertions = if no_layout {
        String::new()
    } else {
        // Assert the layout {{ content }} marker was replaced (composition
        // happened) without asserting the default layout's HTML structure —
        // users may customize _layout.html to use divs, custom CSS, etc.
        r#"                assert!(
                    !html.contains("{{ content }}"),
                    "layout marker must be replaced after composition; got: {html}"
                );
"#
        .to_owned()
    };
    format!(
        "\n\
         #[cfg(test)]\n\
         mod {snake_name}_mailer_tests {{\n\
             use super::{struct_name};\n\
         \n\
             #[test]\n\
             fn {snake_name}_mailer_renders_both_bodies() {{\n\
                 let mailer_instance = {struct_name};\n\
                 let mail = mailer_instance.{snake_name}(\"test@example.com\".to_owned());\n\
                 let html = mail.html.expect(\"html body should be set\");\n\
                 let text = mail.text.expect(\"text body should be set\");\n\
                 assert!(\n\
                     html.contains(\"{struct_name}\"),\n\
                     \"html body must contain the mailer name; got: {{html}}\"\n\
                 );\n\
                 assert!(\n\
                     text.contains(\"{struct_name}\"),\n\
                     \"text body must contain the mailer name; got: {{text}}\"\n\
                 );\n\
                 {layout_assertions}\
             }}\n\
         }}\n"
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generate::Flags;
    use std::fs;
    use tempfile::TempDir;

    fn project_with_main(main_content: &str) -> TempDir {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname=\"x\"\n\n[dependencies]\nautumn-web = \"0.6\"\n",
        )
        .unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(tmp.path().join("src/main.rs"), main_content).unwrap();
        tmp
    }

    fn default_main() -> &'static str {
        r#"use autumn_web::prelude::*;

#[get("/")]
async fn index() -> &'static str { "ok" }

#[autumn_web::main]
async fn main() {
    autumn_web::app()
        .routes(routes![index])
        .run()
        .await;
}
"#
    }

    /// Backend-aware DDL (issue #1927): `generate mailer --list-unsubscribe` on a
    /// `SQLite` app now scaffolds the `mail_unsubscribes` suppression migration in
    /// `SQLite` dialect (`INTEGER PRIMARY KEY AUTOINCREMENT`, `DEFAULT
    /// CURRENT_TIMESTAMP`) instead of being rejected — and no Postgres-only
    /// `BIGSERIAL` / `TIMESTAMPTZ` / `NOW()` leaks into the `SQLite` migration.
    #[test]
    fn plan_mailer_with_list_unsubscribe_emits_sqlite_ddl() {
        let tmp = project_with_main(default_main());
        fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"sqlite://app.db\"\n",
        )
        .unwrap();
        let plan = plan_mailer(tmp.path(), "Welcome", Some("newsletter"), false)
            .expect("a --list-unsubscribe mailer must scaffold on a SQLite app");
        plan.execute(Flags::default()).unwrap();
        assert!(tmp.path().join("src/mailers/welcome.rs").exists());

        let migration_dir = fs::read_dir(tmp.path().join("migrations"))
            .unwrap()
            .filter_map(Result::ok)
            .find(|e| {
                e.file_name()
                    .to_str()
                    .is_some_and(|n| n.ends_with("_create_mail_unsubscribes"))
            })
            .expect("a mail_unsubscribes migration must be generated on SQLite");
        let up = fs::read_to_string(migration_dir.path().join("up.sql")).unwrap();
        assert!(
            up.contains("id INTEGER PRIMARY KEY AUTOINCREMENT"),
            "SQLite up.sql must use INTEGER PRIMARY KEY AUTOINCREMENT: {up}"
        );
        assert!(
            up.contains("unsubscribed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP"),
            "SQLite up.sql must default the timestamp to CURRENT_TIMESTAMP: {up}"
        );
        for leak in ["BIGSERIAL", "TIMESTAMPTZ", "NOW()"] {
            assert!(
                !up.contains(leak),
                "SQLite up.sql leaked Postgres-only `{leak}`: {up}"
            );
        }
    }

    /// Regression guard: on a Postgres app (the default) the suppression
    /// migration stays byte-for-byte the historical Postgres DDL.
    #[test]
    fn plan_mailer_with_list_unsubscribe_emits_postgres_ddl_by_default() {
        let tmp = project_with_main(default_main());
        fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"postgres://localhost/app\"\n",
        )
        .unwrap();
        let plan = plan_mailer(tmp.path(), "Welcome", Some("newsletter"), false).unwrap();
        plan.execute(Flags::default()).unwrap();
        let migration_dir = fs::read_dir(tmp.path().join("migrations"))
            .unwrap()
            .filter_map(Result::ok)
            .find(|e| {
                e.file_name()
                    .to_str()
                    .is_some_and(|n| n.ends_with("_create_mail_unsubscribes"))
            })
            .expect("a mail_unsubscribes migration must be generated on Postgres");
        let up = fs::read_to_string(migration_dir.path().join("up.sql")).unwrap();
        assert!(
            up.contains("id BIGSERIAL PRIMARY KEY"),
            "Postgres up.sql must keep BIGSERIAL PRIMARY KEY: {up}"
        );
        assert!(
            up.contains("unsubscribed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()"),
            "Postgres up.sql must keep TIMESTAMPTZ DEFAULT NOW(): {up}"
        );
    }

    /// Finding F22: a plain `generate mailer` (no `--list-unsubscribe`) emits only
    /// Rust/template files and enables the `mail` feature — nothing
    /// `SQLite`-incompatible — so it must SUCCEED on a `SQLite` app rather than
    /// being over-rejected by the unsubscribe-migration gate.
    #[test]
    fn plan_mailer_without_list_unsubscribe_succeeds_on_sqlite_app() {
        let tmp = project_with_main(default_main());
        fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"sqlite://app.db\"\n",
        )
        .unwrap();
        let plan = plan_mailer(tmp.path(), "Welcome", None, false)
            .expect("a plain mailer must scaffold on a SQLite app");
        // It plans the Rust file and no unsubscribe migration is present.
        plan.execute(Flags::default()).unwrap();
        assert!(tmp.path().join("src/mailers/welcome.rs").exists());
        let has_unsubscribe_migration =
            fs::read_dir(tmp.path().join("migrations")).is_ok_and(|rd| {
                rd.filter_map(Result::ok).any(|e| {
                    e.file_name()
                        .to_string_lossy()
                        .contains("mail_unsubscribes")
                })
            });
        assert!(
            !has_unsubscribe_migration,
            "a plain mailer must not scaffold the Postgres-only unsubscribe migration"
        );
    }

    /// A Postgres app (the default) is not rejected — `generate mailer` still
    /// plans its files.
    #[test]
    fn plan_mailer_not_rejected_on_postgres_app() {
        let tmp = project_with_main(default_main());
        fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"postgres://localhost/app\"\n",
        )
        .unwrap();
        assert!(plan_mailer(tmp.path(), "Welcome", None, false).is_ok());
    }

    /// `autumn destroy mailer` recomputes this same plan with `for_revert` before
    /// [`Plan::revert`], so it must build a revert plan on a `SQLite` app even for
    /// the `--list-unsubscribe` variant (issue #1927 made its generate path
    /// `SQLite`-valid too, so this is now symmetric with the generate path).
    #[test]
    fn plan_mailer_ex_for_revert_not_rejected_on_sqlite_app() {
        let tmp = project_with_main(default_main());
        fs::write(
            tmp.path().join("autumn.toml"),
            "[database]\nprimary_url = \"sqlite://app.db\"\n",
        )
        .unwrap();
        assert!(
            plan_mailer_ex(tmp.path(), "Welcome", Some("newsletter"), false, true).is_ok(),
            "destroy mailer must build its revert plan on a SQLite app even for the \
             --list-unsubscribe variant"
        );
    }

    #[test]
    fn generate_then_destroy_mailer_round_trips_to_original_project_state() {
        let tmp = project_with_main(default_main());
        let cargo_path = tmp.path().join("Cargo.toml");
        let main_path = tmp.path().join("src/main.rs");
        let original_cargo = fs::read_to_string(&cargo_path).unwrap();
        let original_main = fs::read_to_string(&main_path).unwrap();

        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        plan.execute(Flags::default()).unwrap();
        assert!(tmp.path().join("src/mailers/welcome.rs").exists());
        assert!(
            fs::read_to_string(&main_path)
                .unwrap()
                .contains("mail_previews!")
        );
        assert!(
            fs::read_to_string(&cargo_path)
                .unwrap()
                .contains("\"mail\"")
        );

        let destroy_plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        destroy_plan.revert(Flags::default()).unwrap();

        assert!(!tmp.path().join("src/mailers/welcome.rs").exists());
        assert!(!tmp.path().join("src/mailers/mod.rs").exists());
        assert!(!tmp.path().join("src/mailers/previews").exists());
        assert_eq!(fs::read_to_string(&main_path).unwrap(), original_main);
        assert_eq!(fs::read_to_string(&cargo_path).unwrap(), original_cargo);
    }

    #[test]
    fn destroying_one_of_two_mailers_keeps_shared_mail_feature_the_other_still_needs() {
        let tmp = project_with_main(default_main());
        let cargo_path = tmp.path().join("Cargo.toml");

        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        plan_mailer(tmp.path(), "Goodbye", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(
            fs::read_to_string(&cargo_path)
                .unwrap()
                .contains("\"mail\"")
        );

        // Destroying Welcome alone must NOT strip the "mail" feature —
        // Goodbye's mailer still needs it.
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .revert(Flags::default())
            .unwrap();

        assert!(!tmp.path().join("src/mailers/welcome.rs").exists());
        assert!(tmp.path().join("src/mailers/goodbye.rs").exists());
        let cargo_after = fs::read_to_string(&cargo_path).unwrap();
        assert!(
            cargo_after.contains("\"mail\""),
            "mail feature must survive — Goodbye's mailer still uses it: {cargo_after}"
        );

        // Now destroy the last remaining mailer — the feature must finally go.
        plan_mailer(tmp.path(), "Goodbye", None, false)
            .unwrap()
            .revert(Flags::default())
            .unwrap();
        assert!(!tmp.path().join("src/mailers/goodbye.rs").exists());
        assert!(
            !fs::read_to_string(&cargo_path)
                .unwrap()
                .contains("\"mail\""),
            "mail feature must be removed once no mailer uses it anymore"
        );
    }

    #[test]
    fn destroying_one_of_two_mailers_keeps_shared_layout_the_other_still_includes() {
        let tmp = project_with_main(default_main());
        let layout_html = tmp.path().join("templates/mailers/_layout.html");
        let layout_txt = tmp.path().join("templates/mailers/_layout.txt");

        // Welcome creates the shared layout files (create_if_absent);
        // Goodbye's own plan carries the SAME create_if_absent actions
        // (they're silently skipped at execute time since the files already
        // exist), so both mailers' plans mention them.
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        plan_mailer(tmp.path(), "Goodbye", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(layout_html.exists());
        assert!(layout_txt.exists());

        // Destroying Welcome alone must NOT delete the shared layout —
        // Goodbye's mailer/preview files still `include_str!` it.
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .revert(Flags::default())
            .unwrap();

        assert!(!tmp.path().join("src/mailers/welcome.rs").exists());
        assert!(
            layout_html.exists(),
            "shared _layout.html must survive — Goodbye's mailer still includes it"
        );
        assert!(
            layout_txt.exists(),
            "shared _layout.txt must survive — Goodbye's mailer still includes it"
        );

        // Now destroy the last remaining mailer — the shared layout must
        // finally go too.
        plan_mailer(tmp.path(), "Goodbye", None, false)
            .unwrap()
            .revert(Flags::default())
            .unwrap();
        assert!(!layout_html.exists());
        assert!(!layout_txt.exists());
    }

    // ── RED: file plan assertions ─────────────────────────────────────────

    #[test]
    fn plan_creates_mailer_file() {
        let tmp = project_with_main(default_main());
        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("src/mailers/welcome.rs")),
            "plan must include src/mailers/welcome.rs"
        );
    }

    #[test]
    fn plan_creates_preview_file() {
        let tmp = project_with_main(default_main());
        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("src/mailers/previews/welcome.rs")),
            "plan must include src/mailers/previews/welcome.rs"
        );
    }

    #[test]
    fn plan_includes_previews_mod_rs() {
        let tmp = project_with_main(default_main());
        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("src/mailers/previews/mod.rs")),
            "plan must include src/mailers/previews/mod.rs"
        );
    }

    #[test]
    fn plan_creates_html_template() {
        let tmp = project_with_main(default_main());
        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("templates/mailers/welcome.html")),
            "plan must include templates/mailers/welcome.html"
        );
    }

    #[test]
    fn plan_creates_txt_template() {
        let tmp = project_with_main(default_main());
        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("templates/mailers/welcome.txt")),
            "plan must include templates/mailers/welcome.txt"
        );
    }

    #[test]
    fn plan_includes_mailer_mod_rs() {
        let tmp = project_with_main(default_main());
        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("src/mailers/mod.rs")),
            "plan must include src/mailers/mod.rs"
        );
    }

    #[test]
    fn plan_does_not_create_external_smoke_test() {
        let tmp = project_with_main(default_main());
        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        assert!(
            !plan.actions.iter().any(|a| a
                .path()
                .to_string_lossy()
                .contains("tests/welcome_mailer.rs")),
            "plan must not include tests/welcome_mailer.rs"
        );
    }

    #[test]
    fn plan_updates_main_rs() {
        let tmp = project_with_main(default_main());
        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("src/main.rs")),
            "plan must update src/main.rs"
        );
    }

    // ── List-Unsubscribe scaffolding ──────────────────────────────────────

    #[test]
    fn list_unsubscribe_sets_attribute_and_plans_migration() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "WeeklyDigest", Some("weekly_digest"), false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let mailer = fs::read_to_string(tmp.path().join("src/mailers/weekly_digest.rs")).unwrap();
        assert!(
            mailer.contains("#[mailer(list_unsubscribe = \"weekly_digest\")]"),
            "mailer must carry the list_unsubscribe attribute: {mailer}"
        );

        // Exactly one migration directory, with the expected SQL.
        let migration_dir = fs::read_dir(tmp.path().join("migrations"))
            .unwrap()
            .filter_map(Result::ok)
            .find(|e| {
                e.file_name()
                    .to_str()
                    .is_some_and(|n| n.ends_with("_create_mail_unsubscribes"))
            })
            .expect("a mail_unsubscribes migration must be generated");
        let up = fs::read_to_string(migration_dir.path().join("up.sql")).unwrap();
        assert!(up.contains("CREATE TABLE mail_unsubscribes"));
        assert!(up.contains("UNIQUE (subscriber, list_id)"));
        let down = fs::read_to_string(migration_dir.path().join("down.sql")).unwrap();
        assert!(down.contains("DROP TABLE mail_unsubscribes"));
    }

    #[test]
    fn rejects_unsafe_list_unsubscribe_scope() {
        let tmp = project_with_main(default_main());
        // A scope with a quote would inject invalid Rust into the attribute.
        assert!(plan_mailer(tmp.path(), "Welcome", Some("a\" )]"), false).is_err());
        assert!(plan_mailer(tmp.path(), "Welcome", Some("with space"), false).is_err());
        assert!(plan_mailer(tmp.path(), "Welcome", Some(""), false).is_err());
        // Identifier-like scopes are accepted.
        assert!(plan_mailer(tmp.path(), "Welcome", Some("weekly_digest"), false).is_ok());
        assert!(plan_mailer(tmp.path(), "Welcome", Some("product-updates"), false).is_ok());
    }

    #[test]
    fn rejects_unicode_and_special_chars_in_list_unsubscribe_scope() {
        let tmp = project_with_main(default_main());
        // Unicode characters are not allowed (alphanumeric ASCII + _ + - only).
        assert!(plan_mailer(tmp.path(), "Welcome", Some("wöchentlich"), false).is_err());
        assert!(plan_mailer(tmp.path(), "Welcome", Some("list.name"), false).is_err());
        assert!(plan_mailer(tmp.path(), "Welcome", Some("list/name"), false).is_err());
        // Dash and underscore are fine.
        assert!(plan_mailer(tmp.path(), "Welcome", Some("a-b_c"), false).is_ok());
    }

    #[test]
    fn without_list_unsubscribe_no_migration_and_plain_attribute() {
        let tmp = project_with_main(default_main());
        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        assert!(
            !plan
                .actions
                .iter()
                .any(|a| a.path().to_string_lossy().contains("mail_unsubscribes")),
            "no migration without --list-unsubscribe"
        );
    }

    #[test]
    fn second_list_unsubscribe_mailer_does_not_duplicate_migration() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "WeeklyDigest", Some("weekly_digest"), false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        let migrations_dir = tmp.path().join("migrations");
        let existing_dirs = || {
            fs::read_dir(&migrations_dir)
                .unwrap()
                .filter_map(Result::ok)
                .map(|e| e.path())
                .filter(|p| p.is_dir())
                .count()
        };
        assert_eq!(existing_dirs(), 1, "first mailer creates one migration dir");
        let original_dir = fs::read_dir(&migrations_dir)
            .unwrap()
            .filter_map(Result::ok)
            .map(|e| e.path())
            .find(|p| p.is_dir())
            .unwrap();

        // A second list mailer must reuse the existing suppression table:
        // its plan still carries the migration's actions (so `autumn
        // destroy` can find it later), but they all target the SAME
        // already-existing directory, and executing must not create a
        // second migration directory or error.
        let second =
            plan_mailer(tmp.path(), "ProductUpdates", Some("product_updates"), false).unwrap();
        let migration_paths: Vec<_> = second
            .actions
            .iter()
            .map(super::super::emit::Action::path)
            .filter(|p| p.to_string_lossy().contains("mail_unsubscribes"))
            .collect();
        assert!(
            !migration_paths.is_empty(),
            "the plan must still carry the migration's actions so `autumn destroy` can find it"
        );
        for path in &migration_paths {
            assert_eq!(
                path.parent().unwrap(),
                original_dir,
                "migration action must target the existing on-disk directory, not a fresh timestamp"
            );
        }

        second.execute(Flags::default()).unwrap();
        assert_eq!(
            existing_dirs(),
            1,
            "must not plan or create a duplicate suppression migration"
        );
    }

    #[test]
    fn destroying_one_of_two_list_unsubscribe_mailers_keeps_the_shared_migration() {
        let tmp = project_with_main(default_main());
        let migrations_dir = tmp.path().join("migrations");
        let migration_dir_exists =
            || fs::read_dir(&migrations_dir).is_ok_and(|mut d| d.next().is_some());

        plan_mailer(tmp.path(), "WeeklyDigest", Some("weekly_digest"), false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        plan_mailer(tmp.path(), "ProductUpdates", Some("product_updates"), false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(migration_dir_exists());

        // Destroying WeeklyDigest alone must NOT remove the shared
        // mail_unsubscribes migration — ProductUpdates still opts into
        // --list-unsubscribe and needs the suppression table.
        plan_mailer(tmp.path(), "WeeklyDigest", Some("weekly_digest"), false)
            .unwrap()
            .revert(Flags::default())
            .unwrap();

        assert!(!tmp.path().join("src/mailers/weekly_digest.rs").exists());
        assert!(tmp.path().join("src/mailers/product_updates.rs").exists());
        assert!(
            migration_dir_exists(),
            "shared mail_unsubscribes migration must survive — ProductUpdates still needs it"
        );

        // Now destroy the last remaining list-unsubscribe mailer — the
        // migration must finally go too.
        plan_mailer(tmp.path(), "ProductUpdates", Some("product_updates"), false)
            .unwrap()
            .revert(Flags::default())
            .unwrap();
        assert!(!tmp.path().join("src/mailers/product_updates.rs").exists());
        assert!(
            !migration_dir_exists(),
            "mail_unsubscribes migration must be removed once no mailer uses list_unsubscribe anymore"
        );
    }

    #[test]
    fn destroying_the_only_mailer_keeps_mail_feature_auth_still_needs() {
        // Codex PR review (issue #1048): "mail" is needed by BOTH `generate
        // auth` (password reset/confirmation emails) and `generate mailer` —
        // two entirely different generators, so the mailer's own
        // `src/mailers` owner_dir sibling check alone can't see that auth
        // still needs the feature.
        // `generate auth` (issue #1353) requires a shared 4-arg `pub fn layout`
        // in src/main.rs so its views can render through `crate::layout`, so this
        // project's main.rs must expose one (as `autumn new` emits).
        let tmp = project_with_main(
            "use autumn_web::prelude::*;\n\n\
             pub fn layout(title: &str, current_path: &str, flash: maud::Markup, content: maud::Markup) -> maud::Markup {\n\
             \x20   let _ = (current_path, flash);\n\
             \x20   maud::html! { title { (title) } (content) }\n\
             }\n\n\
             #[get(\"/\")]\n\
             async fn index() -> &'static str { \"ok\" }\n\n\
             #[autumn_web::main]\n\
             async fn main() {\n\
             \x20   autumn_web::app().routes(routes![index]).run().await;\n\
             }\n",
        );
        let cargo_path = tmp.path().join("Cargo.toml");

        crate::generate::auth::plan_auth(tmp.path(), "User", "20260508000000")
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        assert!(
            fs::read_to_string(&cargo_path)
                .unwrap()
                .contains("\"mail\"")
        );

        // Destroying the only mailer must NOT strip "mail" — auth's routes
        // still call `Mail::builder()`.
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .revert(Flags::default())
            .unwrap();

        assert!(!tmp.path().join("src/mailers/welcome.rs").exists());
        let cargo_after = fs::read_to_string(&cargo_path).unwrap();
        assert!(
            cargo_after.contains("\"mail\""),
            "mail feature must survive — auth still uses Mail::builder(): {cargo_after}"
        );
    }

    // ── GREEN: execute and inspect written content ────────────────────────

    #[test]
    fn execute_writes_mailer_struct_and_macro_annotations() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let mailer = fs::read_to_string(tmp.path().join("src/mailers/welcome.rs")).unwrap();
        assert!(
            mailer.contains("pub struct WelcomeMailer"),
            "mailer file must define the struct"
        );
        assert!(
            mailer.contains("#[mailer]"),
            "must have #[mailer] attribute"
        );
        assert!(
            !mailer.contains("#[mailer_preview]"),
            "mailer file must NOT contain #[mailer_preview] — it lives in previews/"
        );

        let preview =
            fs::read_to_string(tmp.path().join("src/mailers/previews/welcome.rs")).unwrap();
        assert!(
            preview.contains("#[mailer_preview]"),
            "preview file must have #[mailer_preview] attribute"
        );
    }

    #[test]
    fn execute_mailer_has_deliver_later_capable_method() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let mailer = fs::read_to_string(tmp.path().join("src/mailers/welcome.rs")).unwrap();
        assert!(
            mailer.contains("pub fn welcome("),
            "#[mailer] impl must expose a method; the macro generates deliver_later_welcome from it"
        );
        assert!(
            mailer.contains("deliver_later"),
            "the generated comment must describe the deliver_later API"
        );
    }

    #[test]
    fn execute_writes_html_template_with_expected_content() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let html = fs::read_to_string(tmp.path().join("templates/mailers/welcome.html")).unwrap();
        assert!(
            html.contains("WelcomeMailer"),
            "html template must reference the mailer name"
        );
        // With layout, per-mailer template is body-only; full document is in _layout.html.
        assert!(!html.is_empty(), "html template must not be empty");
    }

    #[test]
    fn html_template_shows_style_block_example_relying_on_inlining() {
        // AC6 (issue #1254): the scaffolded per-mailer template demonstrates the
        // `<style>`-block + CSS-class happy path that inlining resolves.
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let html = fs::read_to_string(tmp.path().join("templates/mailers/welcome.html")).unwrap();
        assert!(
            html.contains("<style>"),
            "with-layout template must show a <style>-block example: {html}"
        );
        assert!(
            html.contains("class=\"btn\""),
            "template must reference a CSS class that inlining resolves: {html}"
        );
    }

    #[test]
    fn generated_mailer_enables_css_inlining() {
        // AC6 (issue #1254): the generated mailer opts into inlining so the
        // `<style>`-block template renders styled end to end.
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let mailer = fs::read_to_string(tmp.path().join("src/mailers/welcome.rs")).unwrap();
        assert!(
            mailer.contains(".inline_css(true)"),
            "generated mailer must enable CSS inlining: {mailer}"
        );
    }

    #[test]
    fn generated_preview_enables_css_inlining() {
        // AC6 (issue #1254): the generated preview fixture must carry the same
        // `.inline_css(true)` opt-in the production mailer has, so a scaffolded
        // mailer's preview is inlined regardless of the app's `mail.inline_css`
        // config default (the preview route resolves per-message-override-or-
        // config-default, so without the override a `false` default would show
        // RAW `<style>` CSS even though a real send is inlined).
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let preview =
            fs::read_to_string(tmp.path().join("src/mailers/previews/welcome.rs")).unwrap();
        assert!(
            preview.contains(".inline_css(true)"),
            "generated preview fixture must enable CSS inlining to match the mailer: {preview}"
        );
    }

    #[test]
    fn no_layout_template_also_shows_style_block() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, true)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let html = fs::read_to_string(tmp.path().join("templates/mailers/welcome.html")).unwrap();
        assert!(
            html.contains("<style>"),
            "--no-layout template must also show a <style>-block example: {html}"
        );
    }

    #[test]
    fn execute_writes_txt_template_with_expected_content() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let txt = fs::read_to_string(tmp.path().join("templates/mailers/welcome.txt")).unwrap();
        assert!(
            txt.contains("WelcomeMailer"),
            "text template must reference the mailer name"
        );
        assert!(!txt.trim().is_empty(), "text template must not be empty");
    }

    #[test]
    fn execute_writes_preview_file_with_mailer_preview() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let preview =
            fs::read_to_string(tmp.path().join("src/mailers/previews/welcome.rs")).unwrap();
        assert!(
            preview.contains("#[mailer_preview]"),
            "preview file must have #[mailer_preview] attribute"
        );
        assert!(
            preview.contains("welcome_preview"),
            "preview file must define a preview method"
        );
        assert!(
            preview.contains("../../../templates/mailers/welcome.html"),
            "preview include_str! path must be three levels up from previews/"
        );
    }

    #[test]
    fn execute_updates_mailer_mod_rs() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let mod_rs = fs::read_to_string(tmp.path().join("src/mailers/mod.rs")).unwrap();
        assert!(
            mod_rs.contains("pub mod welcome;"),
            "mod.rs must declare pub mod welcome"
        );
        assert!(
            mod_rs.contains("pub mod previews;"),
            "mod.rs must declare pub mod previews"
        );

        let previews_mod =
            fs::read_to_string(tmp.path().join("src/mailers/previews/mod.rs")).unwrap();
        assert!(
            previews_mod.contains("pub mod welcome;"),
            "previews/mod.rs must declare pub mod welcome"
        );
    }

    #[test]
    fn execute_updates_main_rs_with_mod_declaration() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(
            main.contains("mod mailers;"),
            "main.rs must declare mod mailers"
        );
    }

    #[test]
    fn execute_updates_main_rs_with_mail_previews_call() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(
            main.contains("mail_previews!["),
            "main.rs must include a mail_previews![] call"
        );
        assert!(
            main.contains("mailers::welcome::WelcomeMailer"),
            "main.rs must reference the generated mailer type"
        );
    }

    #[test]
    fn execute_writes_smoke_test_with_body_assertions() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let test = fs::read_to_string(tmp.path().join("src/mailers/welcome.rs")).unwrap();
        assert!(
            test.contains("WelcomeMailer"),
            "smoke test must reference the mailer struct"
        );
        assert!(
            test.contains("welcome_mailer_renders_both_bodies")
                || test.contains("renders_both_bodies"),
            "smoke test must include a renders-both-bodies test function"
        );
        assert!(
            test.contains("html.contains") || test.contains("html body"),
            "smoke test must assert the html body"
        );
        assert!(
            test.contains("text.contains") || test.contains("text body"),
            "smoke test must assert the text body"
        );
        assert!(
            test.contains("WelcomeMailer"),
            "smoke test body assertion must check for the mailer name"
        );
        assert!(
            !test.contains("cfg(feature = \"mail\")"),
            "smoke test must not be gated by cfg(feature = \"mail\")"
        );
    }

    #[test]
    fn execute_adds_mail_feature_to_cargo_toml() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let cargo = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
        assert!(
            cargo.contains("\"mail\""),
            "Cargo.toml must include the mail feature for autumn-web: {cargo}"
        );
    }

    // ── Flag behaviour ────────────────────────────────────────────────────

    #[test]
    fn dry_run_writes_no_new_files() {
        let tmp = project_with_main(default_main());
        let original_main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags {
                dry_run: true,
                force: false,
            })
            .unwrap();

        assert!(
            !tmp.path().join("src/mailers/welcome.rs").exists(),
            "dry run must not write the mailer file"
        );
        assert!(
            !tmp.path().join("src/mailers/previews/welcome.rs").exists(),
            "dry run must not write the preview file"
        );
        assert!(
            !tmp.path().join("templates/mailers/welcome.html").exists(),
            "dry run must not write html template"
        );
        assert!(
            !tmp.path().join("templates/mailers/welcome.txt").exists(),
            "dry run must not write txt template"
        );
        let main_after = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert_eq!(
            original_main, main_after,
            "dry run must not modify src/main.rs"
        );
    }

    #[test]
    fn collision_without_force_returns_error() {
        let tmp = project_with_main(default_main());
        fs::create_dir_all(tmp.path().join("src/mailers")).unwrap();
        fs::write(tmp.path().join("src/mailers/welcome.rs"), "// existing").unwrap();
        let err = plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap_err();
        assert!(
            matches!(err, GenerateError::Collisions(_)),
            "should return collision error; got {err:?}"
        );
    }

    #[test]
    fn force_overwrites_existing_mailer() {
        let tmp = project_with_main(default_main());
        fs::create_dir_all(tmp.path().join("src/mailers")).unwrap();
        fs::write(tmp.path().join("src/mailers/welcome.rs"), "// old").unwrap();
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags {
                force: true,
                dry_run: false,
            })
            .unwrap();

        let mailer = fs::read_to_string(tmp.path().join("src/mailers/welcome.rs")).unwrap();
        assert!(
            mailer.contains("WelcomeMailer"),
            "force must regenerate the mailer file"
        );
    }

    // ── Name normalisation ────────────────────────────────────────────────

    #[test]
    fn snake_case_input_is_normalised() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "welcome_email", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        assert!(tmp.path().join("src/mailers/welcome_email.rs").exists());
        let content = fs::read_to_string(tmp.path().join("src/mailers/welcome_email.rs")).unwrap();
        assert!(
            content.contains("WelcomeEmailMailer"),
            "PascalCase struct must include both words"
        );
    }

    // ── Error conditions ──────────────────────────────────────────────────

    #[test]
    fn plan_errors_when_main_rs_missing() {
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join("Cargo.toml"), "[package]\nname=\"x\"\n").unwrap();
        let err = plan_mailer(tmp.path(), "Welcome", None, false).unwrap_err();
        assert!(matches!(err, GenerateError::Io(_)));
    }

    #[test]
    fn plan_errors_when_not_in_project() {
        let tmp = TempDir::new().unwrap();
        let err = plan_mailer(tmp.path(), "Welcome", None, false).unwrap_err();
        assert!(matches!(err, GenerateError::NotInProject));
    }

    #[test]
    fn second_mailer_augments_mod_rs_and_previews() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        plan_mailer(tmp.path(), "Notification", None, false)
            .unwrap()
            .execute(Flags {
                force: true,
                dry_run: false,
            })
            .unwrap();

        let mod_rs = fs::read_to_string(tmp.path().join("src/mailers/mod.rs")).unwrap();
        assert!(mod_rs.contains("pub mod welcome;"));
        assert!(mod_rs.contains("pub mod notification;"));
        assert!(
            mod_rs.contains("pub mod previews;"),
            "previews module must appear once"
        );
        assert_eq!(
            mod_rs.matches("pub mod previews;").count(),
            1,
            "pub mod previews; must appear exactly once (idempotent)"
        );

        let previews_mod =
            fs::read_to_string(tmp.path().join("src/mailers/previews/mod.rs")).unwrap();
        assert!(previews_mod.contains("pub mod welcome;"));
        assert!(previews_mod.contains("pub mod notification;"));

        let main = fs::read_to_string(tmp.path().join("src/main.rs")).unwrap();
        assert!(main.contains("mailers::welcome::WelcomeMailer"));
        assert!(main.contains("mailers::notification::NotificationMailer"));
    }

    // ── Shared layout: RED tests ──────────────────────────────────────────

    #[test]
    fn plan_creates_layout_html() {
        let tmp = project_with_main(default_main());
        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("templates/mailers/_layout.html")),
            "plan must include templates/mailers/_layout.html"
        );
    }

    #[test]
    fn plan_creates_layout_txt() {
        let tmp = project_with_main(default_main());
        let plan = plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("templates/mailers/_layout.txt")),
            "plan must include templates/mailers/_layout.txt"
        );
    }

    #[test]
    fn layout_html_contains_table_and_style_and_content_marker() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let layout = fs::read_to_string(tmp.path().join("templates/mailers/_layout.html")).unwrap();
        assert!(
            layout.contains("<table"),
            "_layout.html must contain a table-based wrapper"
        );
        assert!(
            layout.contains("style="),
            "_layout.html must use inline style= attributes"
        );
        assert!(
            layout.contains("{{ content }}"),
            "_layout.html must contain the content slot marker"
        );
        assert!(
            layout.contains("<!DOCTYPE html>"),
            "_layout.html must be a complete document shell"
        );
    }

    #[test]
    fn layout_txt_contains_content_marker() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let layout = fs::read_to_string(tmp.path().join("templates/mailers/_layout.txt")).unwrap();
        assert!(
            layout.contains("{{ content }}"),
            "_layout.txt must contain the content slot marker"
        );
    }

    #[test]
    fn per_mailer_html_template_is_body_fragment_only() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let html = fs::read_to_string(tmp.path().join("templates/mailers/welcome.html")).unwrap();
        assert!(
            !html.contains("<!DOCTYPE"),
            "per-mailer template must NOT contain <!DOCTYPE — that belongs in _layout.html"
        );
        assert!(
            !html.contains("<head"),
            "per-mailer template must NOT contain <head>"
        );
        assert!(
            !html.contains("<body"),
            "per-mailer template must NOT contain <body>"
        );
        assert!(
            html.contains("WelcomeMailer"),
            "per-mailer template must still reference the mailer name"
        );
    }

    #[test]
    fn second_mailer_does_not_recreate_layout_files() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        // Overwrite _layout.html with a sentinel to detect re-creation.
        let layout_path = tmp.path().join("templates/mailers/_layout.html");
        fs::write(&layout_path, "<!-- sentinel -->").unwrap();

        plan_mailer(tmp.path(), "Receipt", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        // The second generator run must NOT recreate the layout file.
        let layout = fs::read_to_string(&layout_path).unwrap();
        assert_eq!(
            layout, "<!-- sentinel -->",
            "second mailer generation must not overwrite _layout.html"
        );
    }

    #[test]
    fn second_mailer_template_has_no_doctype_or_head() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();
        plan_mailer(tmp.path(), "Receipt", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let html = fs::read_to_string(tmp.path().join("templates/mailers/receipt.html")).unwrap();
        assert!(
            !html.contains("<!DOCTYPE"),
            "2nd mailer template must add 0 lines of <!DOCTYPE boilerplate"
        );
        assert!(
            !html.contains("<head"),
            "2nd mailer template must add 0 lines of <head> boilerplate"
        );
    }

    #[test]
    fn generated_mailer_file_includes_layout_builder_call() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let mailer = fs::read_to_string(tmp.path().join("src/mailers/welcome.rs")).unwrap();
        assert!(
            mailer.contains(".layout("),
            "generated mailer must call .layout(...) to compose body into shared layout"
        );
    }

    #[test]
    fn generated_preview_file_includes_layout_builder_call() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let preview =
            fs::read_to_string(tmp.path().join("src/mailers/previews/welcome.rs")).unwrap();
        assert!(
            preview.contains(".layout("),
            "generated preview must call .layout(...) to show layout-wrapped output"
        );
    }

    #[test]
    fn smoke_test_asserts_layout_composition() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, false)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let mailer = fs::read_to_string(tmp.path().join("src/mailers/welcome.rs")).unwrap();
        // The smoke test should assert that the {{ content }} marker was
        // replaced (composition happened), not that the default layout uses
        // tables — users may customize _layout.html to any structure.
        assert!(
            mailer.contains("{{ content }}"),
            "smoke test must assert the layout content marker was replaced"
        );
    }

    // ── --no-layout flag ──────────────────────────────────────────────────

    #[test]
    fn no_layout_flag_omits_layout_call_in_mailer() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, true)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let mailer = fs::read_to_string(tmp.path().join("src/mailers/welcome.rs")).unwrap();
        assert!(
            !mailer.contains(".layout("),
            "--no-layout must not emit .layout() call"
        );
    }

    #[test]
    fn no_layout_flag_emits_full_document_html_template() {
        let tmp = project_with_main(default_main());
        plan_mailer(tmp.path(), "Welcome", None, true)
            .unwrap()
            .execute(Flags::default())
            .unwrap();

        let html = fs::read_to_string(tmp.path().join("templates/mailers/welcome.html")).unwrap();
        assert!(
            html.contains("<!DOCTYPE html>"),
            "--no-layout template must be a self-contained full-document HTML"
        );
    }
}