autumn-cli 0.7.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
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
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
//! End-to-end integration tests for `autumn generate`.
//!
//! These run the real `autumn` binary against a freshly-`new`-ed project and
//! assert the produced filesystem matches the documented contract — covering
//! the user-facing flow described in [Issue #493].
//!
//! [Issue #493]: https://github.com/autumn-foundation/autumn/issues/493

use std::fmt::Write as _;
use std::fs;
use std::io::Read as _;
use std::net::TcpListener;
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::Duration;

/// Spawn the production `autumn` binary in `dir` with the given args and
/// assert it exits successfully, returning the captured stdout + stderr.
fn run_autumn(dir: &Path, args: &[&str]) -> (String, String) {
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(args)
        .current_dir(dir)
        .output()
        .expect("failed to run autumn");
    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
    assert!(
        output.status.success(),
        "autumn {args:?} failed (exit={:?})\nstdout: {stdout}\nstderr: {stderr}",
        output.status.code(),
    );
    (stdout, stderr)
}

/// Spawn the production `autumn` binary with environment overrides.
fn run_autumn_with_env(dir: &Path, args: &[&str], envs: &[(&str, &str)]) -> (String, String) {
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(args)
        .current_dir(dir)
        .envs(envs.iter().copied())
        .output()
        .expect("failed to run autumn");
    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
    assert!(
        output.status.success(),
        "autumn {args:?} failed (exit={:?})\nstdout: {stdout}\nstderr: {stderr}",
        output.status.code(),
    );
    (stdout, stderr)
}

/// Same as [`run_autumn`] but expects a non-zero exit code.
fn run_autumn_failing(dir: &Path, args: &[&str]) -> (String, String, Option<i32>) {
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(args)
        .current_dir(dir)
        .output()
        .expect("failed to run autumn");
    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
    (stdout, stderr, output.status.code())
}

/// `autumn new <name>` in a fresh tempdir, returning that tempdir + the
/// project root inside it.
fn fresh_project(name: &str) -> (tempfile::TempDir, std::path::PathBuf) {
    let tmp = tempfile::tempdir().expect("tempdir");
    run_autumn(tmp.path(), &["new", name]);
    let project = tmp.path().join(name);
    (tmp, project)
}

fn patch_generated_cargo_toml(project_dir: &Path) {
    let cargo_toml_path = project_dir.join("Cargo.toml");
    let mut content = fs::read_to_string(&cargo_toml_path).unwrap();
    let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .expect("workspace root");
    let autumn_web = workspace_root.join("autumn");
    write!(
        content,
        "\n[patch.crates-io]\nautumn-web = {{ path = \"{}\" }}\n",
        autumn_web.display().to_string().replace('\\', "/")
    )
    .unwrap();
    fs::write(&cargo_toml_path, content).unwrap();
}

fn free_port() -> u16 {
    let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
    listener.local_addr().expect("local addr").port()
}

struct ServerGuard(Child);

impl Drop for ServerGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

fn child_output(child: &mut Child) -> (String, String) {
    let mut stdout = String::new();
    let mut stderr = String::new();
    if let Some(mut pipe) = child.stdout.take() {
        let _ = pipe.read_to_string(&mut stdout);
    }
    if let Some(mut pipe) = child.stderr.take() {
        let _ = pipe.read_to_string(&mut stderr);
    }
    (stdout, stderr)
}

// Async HTTP poll used by tests that already run inside a Tokio runtime
// (e.g. #[tokio::test] tests that also drive async testcontainers).
// Using reqwest::blocking inside an existing Tokio runtime panics when the
// blocking client's internal runtime is dropped, so these tests use the
// native async reqwest::Client instead.
async fn wait_for_server_ready_async(
    mut child: Child,
    client: &reqwest::Client,
    base: &str,
) -> ServerGuard {
    for _ in 0..60 {
        if let Some(status) = child.try_wait().expect("server status") {
            let (stdout, stderr) = child_output(&mut child);
            panic!(
                "server exited before becoming ready: {status}\nstdout:\n{stdout}\nstderr:\n{stderr}"
            );
        }

        if client.get(format!("{base}/health")).send().await.is_ok() {
            return ServerGuard(child);
        }
        tokio::time::sleep(Duration::from_millis(500)).await;
    }

    let _ = child.kill();
    let _ = child.wait();
    let (stdout, stderr) = child_output(&mut child);
    panic!("server failed to become ready within 30 seconds\nstdout:\n{stdout}\nstderr:\n{stderr}");
}

#[test]
fn generate_model_in_fresh_project() {
    let (_tmp, project) = fresh_project("model-app");
    run_autumn(
        &project,
        &[
            "generate",
            "model",
            "Post",
            "title:String",
            "body:Text",
            "published:bool",
        ],
    );

    let model = fs::read_to_string(project.join("src/models/post.rs")).unwrap();
    assert!(model.contains("#[autumn_web::model]"));
    assert!(model.contains("pub struct Post"));
    assert!(model.contains("pub title: String,"));
    assert!(model.contains("pub body: String,"));
    assert!(model.contains("pub published: bool,"));

    let mod_rs = fs::read_to_string(project.join("src/models/mod.rs")).unwrap();
    assert!(mod_rs.contains("pub mod post;"));

    let schema = fs::read_to_string(project.join("src/schema.rs")).unwrap();
    assert!(schema.contains("posts (id)"));
    assert!(schema.contains("title -> Text,"));

    // The migration directory exists with both up.sql and down.sql.
    let migrations = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| e.file_name().to_string_lossy().ends_with("_create_posts"))
        .collect::<Vec<_>>();
    assert_eq!(migrations.len(), 1);
    let dir = migrations[0].path();
    let up = fs::read_to_string(dir.join("up.sql")).unwrap();
    assert!(up.contains("CREATE TABLE posts"));
    assert!(up.contains("title TEXT NOT NULL"));
    assert!(up.contains("published BOOLEAN NOT NULL"));
    assert!(up.contains("id BIGSERIAL PRIMARY KEY"));
    let down = fs::read_to_string(dir.join("down.sql")).unwrap();
    assert!(down.contains("DROP TABLE posts"));
}

#[test]
fn generate_model_dry_run_writes_nothing() {
    let (_tmp, project) = fresh_project("dryrun-app");
    let (stdout, _stderr) = run_autumn(
        &project,
        &["generate", "model", "Post", "title:String", "--dry-run"],
    );
    assert!(stdout.contains("Dry run"));
    assert!(stdout.contains("src/models/post.rs"));
    assert!(!project.join("src/models/post.rs").exists());
    assert!(!project.join("src/schema.rs").exists());
}

#[test]
fn generate_scaffold_dry_run_api() {
    let (_tmp, project) = fresh_project("dryrun-scaffold-api-app");
    let (stdout, _stderr) = run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "--api",
            "--dry-run",
        ],
    );
    assert!(stdout.contains("Dry run"));
    assert!(stdout.contains("src/models/post.rs"));
    assert!(!stdout.contains("src/routes/posts.rs"));
    assert!(!stdout.contains("templates"));
}

#[test]
fn generate_model_collision_without_force() {
    let (_tmp, project) = fresh_project("collide-app");
    run_autumn(&project, &["generate", "model", "Post", "title:String"]);
    // Re-run without --force. Should fail with collision message.
    let (_, stderr, code) =
        run_autumn_failing(&project, &["generate", "model", "Post", "title:String"]);
    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("would overwrite") && stderr.contains("post.rs"),
        "expected collision message; got stderr: {stderr}"
    );
}

#[test]
fn generate_model_force_overwrites() {
    let (_tmp, project) = fresh_project("force-app");
    run_autumn(&project, &["generate", "model", "Post", "title:String"]);
    // Modify the model file so we can detect the overwrite.
    let model_path = project.join("src/models/post.rs");
    let original = fs::read_to_string(&model_path).unwrap();
    fs::write(&model_path, "// touched").unwrap();
    run_autumn(
        &project,
        &["generate", "model", "Post", "title:String", "--force"],
    );
    let regenerated = fs::read_to_string(&model_path).unwrap();
    assert_eq!(regenerated, original);
}

#[test]
fn generate_model_invalid_field_lists_supported_set() {
    let (_tmp, project) = fresh_project("badtype-app");
    let (_, stderr, code) =
        run_autumn_failing(&project, &["generate", "model", "Post", "price:Money"]);
    assert_eq!(code, Some(1));
    assert!(stderr.contains("unsupported type"));
    assert!(stderr.contains("Supported:"));
    assert!(stderr.contains("String"));
}

// ── `references` field type (issue #1026) ───────────────────────────────────

#[test]
fn generate_model_references_field_emits_fk_column_constraint_and_index() {
    let (_tmp, project) = fresh_project("references-app");
    run_autumn(
        &project,
        &[
            "generate",
            "model",
            "Comment",
            "body:Text",
            "post:references",
        ],
    );

    let model = fs::read_to_string(project.join("src/models/comment.rs")).unwrap();
    assert!(model.contains("pub post_id: i64,"));

    let schema = fs::read_to_string(project.join("src/schema.rs")).unwrap();
    assert!(schema.contains("post_id -> Int8,"));

    let migrations = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_create_comments")
        })
        .collect::<Vec<_>>();
    assert_eq!(migrations.len(), 1);
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(up.contains("post_id BIGINT NOT NULL REFERENCES posts(id)"));
    assert!(up.contains("CREATE INDEX idx_comments_post_id ON comments (post_id);"));
}

#[test]
fn generate_model_references_warns_when_target_model_missing() {
    let (_tmp, project) = fresh_project("references-warn-app");
    let (_stdout, stderr) = run_autumn(
        &project,
        &["generate", "model", "Comment", "post:references"],
    );
    assert!(
        stderr.contains("Warning") && stderr.contains("posts"),
        "expected a warning about the missing 'post' model; got stderr: {stderr}"
    );
}

#[test]
fn generate_model_references_warning_not_printed_on_a_failed_collision_run() {
    // A run that fails before writing anything (a file collision without
    // --force) must not print advisory warnings for a plan that was never
    // applied — warnings are informational about what *did* happen.
    let (_tmp, project) = fresh_project("references-warn-collision-app");
    run_autumn(
        &project,
        &["generate", "model", "Comment", "post:references"],
    );
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &["generate", "model", "Comment", "post:references"],
    );
    assert_eq!(code, Some(1));
    assert!(stderr.contains("would overwrite"));
    assert!(
        !stderr.contains("Warning"),
        "no warning should print on a failed, no-op run: {stderr}"
    );
}

#[test]
fn generate_model_references_no_warning_when_target_model_exists() {
    let (_tmp, project) = fresh_project("references-nowarn-app");
    run_autumn(&project, &["generate", "model", "Post", "title:String"]);
    let (_stdout, stderr) = run_autumn(
        &project,
        &["generate", "model", "Comment", "post:references"],
    );
    assert!(
        !stderr.contains("Warning"),
        "no warning expected once the Post model exists; got stderr: {stderr}"
    );
}

#[test]
fn generate_model_references_nullable_form() {
    let (_tmp, project) = fresh_project("references-nullable-app");
    run_autumn(
        &project,
        &["generate", "model", "Comment", "post:references?"],
    );
    let model = fs::read_to_string(project.join("src/models/comment.rs")).unwrap();
    assert!(model.contains("pub post_id: Option<i64>,"));
}

#[test]
fn generate_model_help_documents_references_field() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "model", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("references"));
}

#[test]
fn generate_scaffold_help_documents_references_field() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "scaffold", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("references"));
}

#[test]
fn generate_model_help_documents_enum_field() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "model", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("enum{"));
}

#[test]
fn generate_scaffold_help_documents_enum_field() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "scaffold", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("enum{"));
}

// ── enum field type (issue #1030) ───────────────────────────────────────────

#[test]
fn generate_model_with_enum_writes_check_and_enum_type() {
    let (_tmp, project) = fresh_project("enum-model-app");
    run_autumn(
        &project,
        &[
            "generate",
            "model",
            "Post",
            "title:String",
            "status:enum{draft,published,archived}",
        ],
    );

    let model = fs::read_to_string(project.join("src/models/post.rs")).unwrap();
    assert!(model.contains("pub enum Status"), "got:\n{model}");
    assert!(model.contains("pub status: Status,"), "got:\n{model}");

    let migration = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .find(|e| e.file_name().to_string_lossy().ends_with("_create_posts"))
        .expect("create_posts migration should exist");
    let up = fs::read_to_string(migration.path().join("up.sql")).unwrap();
    assert!(
        up.contains("status TEXT NOT NULL CHECK (status IN ('draft', 'published', 'archived'))"),
        "got:\n{up}"
    );
}

#[test]
fn generate_migration_add_enum_column_emits_check() {
    let (_tmp, project) = fresh_project("enum-migration-app");
    run_autumn(
        &project,
        &[
            "generate",
            "migration",
            "AddStatusToPosts",
            "status:enum{draft,published}",
        ],
    );

    let migrations = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_add_status_to_posts")
        })
        .collect::<Vec<_>>();
    assert_eq!(migrations.len(), 1);
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(
        up.contains(
            "ALTER TABLE posts ADD COLUMN status TEXT NOT NULL CHECK (status IN ('draft', 'published'));"
        ),
        "got:\n{up}"
    );
}

#[test]
fn generate_scaffold_rejects_bad_enum_default() {
    let (_tmp, project) = fresh_project("enum-bad-default-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "status:enum{draft,published,archived}",
            "--default",
            "status=bogus",
        ],
    );

    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("bogus") && stderr.contains("draft") && stderr.contains("archived"),
        "expected an enum-default membership error listing the variants; got stderr: {stderr}"
    );
    assert!(!project.join("src/models/post.rs").exists());
}

#[test]
fn generate_scaffold_rejects_unique_field_with_default() {
    // Regression guard (issue #1032 review follow-up): a `--default` field
    // is excluded from the generated HTML form, so a `unique` column that
    // also has a `--default` would have no `UNIQUE_CONSTRAINTS` entry (and,
    // even if it did, no form input to show a duplicate-value error
    // against). Reject the combination outright at generation time.
    let (_tmp, project) = fresh_project("unique-with-default-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email:String:unique",
            "--default",
            "email='a@b.com'",
        ],
    );

    assert_eq!(code, Some(1));
    assert!(stderr.contains("email"), "got stderr: {stderr}");
    assert!(stderr.contains("unique"), "got stderr: {stderr}");
    assert!(stderr.contains("default"), "got stderr: {stderr}");
    assert!(!project.join("src/models/user.rs").exists());
}

#[test]
fn generate_scaffold_rejects_unique_flag_field_with_default() {
    // Same rejection via the `--unique FIELD` flag path instead of the
    // inline `:unique` DSL marker. `--default` is only a `generate scaffold`
    // flag (`generate model` has no `--default`), so this exercises the
    // combination through the scaffold generator.
    let (_tmp, project) = fresh_project("unique-flag-with-default-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email:String",
            "--unique",
            "email",
            "--default",
            "email='a@b.com'",
        ],
    );

    assert_eq!(code, Some(1));
    assert!(stderr.contains("email"), "got stderr: {stderr}");
    assert!(stderr.contains("unique"), "got stderr: {stderr}");
    assert!(stderr.contains("default"), "got stderr: {stderr}");
    assert!(!project.join("src/models/user.rs").exists());
}

#[test]
fn generate_scaffold_with_enum_dry_run_lists_files_and_then_collides_without_force() {
    let (_tmp, project) = fresh_project("enum-dryrun-app");
    let (stdout, _stderr) = run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "status:enum{draft,published,archived}",
            "--dry-run",
        ],
    );
    assert!(stdout.contains("Dry run"));
    assert!(stdout.contains("src/models/post.rs"));
    assert!(stdout.contains("src/repositories/post.rs"));
    assert!(stdout.contains("src/routes/posts.rs"));
    assert!(stdout.contains("tests/post.rs"));
    assert!(!project.join("src/models/post.rs").exists());

    // A real (non-dry-run) run actually writes the files...
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "status:enum{draft,published,archived}",
        ],
    );
    assert!(project.join("src/models/post.rs").exists());

    // ...and running it again without --force must error on collision rather
    // than silently overwriting.
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "status:enum{draft,published,archived}",
        ],
    );
    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("overwrite"),
        "expected a collision error; got stderr: {stderr}"
    );
}

#[test]
fn generate_model_dry_run_lists_migration_file_for_references_field() {
    let (_tmp, project) = fresh_project("references-dryrun-app");
    let (stdout, _stderr) = run_autumn(
        &project,
        &[
            "generate",
            "model",
            "Comment",
            "post:references",
            "--dry-run",
        ],
    );
    assert!(stdout.contains("Dry run"));
    assert!(stdout.contains("migrations/"));
    assert!(stdout.contains("create_comments/up.sql"));
    assert!(!project.join("src/models/comment.rs").exists());
}

#[test]
fn generate_model_references_errors_when_target_has_uuid_pk() {
    let (_tmp, project) = fresh_project("references-uuid-mismatch-app");
    run_autumn(
        &project,
        &["generate", "model", "Post", "--id", "uuid", "title:String"],
    );
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &["generate", "model", "Comment", "post:references"],
    );
    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("UUID"),
        "expected a clear UUID-mismatch error; got stderr: {stderr}"
    );
    assert!(!project.join("src/models/comment.rs").exists());
}

#[test]
fn generate_migration_add_columns_emits_alter() {
    let (_tmp, project) = fresh_project("migrate-app");
    run_autumn(
        &project,
        &["generate", "migration", "AddTitleToPosts", "title:String"],
    );
    let migrations = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_add_title_to_posts")
        })
        .collect::<Vec<_>>();
    assert_eq!(migrations.len(), 1);
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(up.contains("ALTER TABLE posts ADD COLUMN title TEXT NOT NULL"));
}

#[test]
fn generate_migration_add_unique_reference_column_skips_redundant_plain_index() {
    // Regression guard (issue #1032 review follow-up): `AddXToY` emitted
    // both a `references` field's auto-index and its `CREATE UNIQUE INDEX`
    // unconditionally, so `author:references:unique` built two overlapping
    // btree indexes on the same column — the plain one is fully redundant
    // since the unique index already covers the same lookup.
    let (_tmp, project) = fresh_project("migrate-unique-reference-app");
    run_autumn(
        &project,
        &[
            "generate",
            "migration",
            "AddAuthorToPosts",
            "author:references:unique",
        ],
    );
    let migrations = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_add_author_to_posts")
        })
        .collect::<Vec<_>>();
    assert_eq!(migrations.len(), 1);
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(
        up.contains("CREATE UNIQUE INDEX idx_posts_author_id_unique ON posts (author_id);"),
        "got:\n{up}"
    );
    assert!(
        !up.contains("CREATE INDEX idx_posts_author_id ON posts (author_id);"),
        "a references field that is also unique must not get a redundant \
         plain index alongside its unique index; got:\n{up}"
    );
}

#[test]
fn generate_migration_unknown_pattern_is_empty() {
    let (_tmp, project) = fresh_project("empty-mig-app");
    run_autumn(&project, &["generate", "migration", "BackfillSomething"]);
    let migrations = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_backfill_something")
        })
        .collect::<Vec<_>>();
    assert_eq!(migrations.len(), 1);
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(up.is_empty());
}

#[test]
fn generate_task_emits_task_module() {
    let (_tmp, project) = fresh_project("task-app");
    run_autumn(&project, &["generate", "task", "cleanup_users"]);

    let task = fs::read_to_string(project.join("tasks/cleanup_users.rs")).unwrap();
    assert!(task.contains("#[autumn_web::task]"));
    assert!(task.contains("pub async fn cleanup_users"));
    assert!(task.contains("TaskArgs<CleanupUsersArgs>"));
    assert!(task.contains("AutumnResult<()>"));
}

#[test]
fn generate_scaffold_full_e2e_post() {
    let (_tmp, project) = fresh_project("scaffold-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "body:Text",
            "published:bool",
            "subtitle:Option<String>",
            "views:Option<i64>",
            "published_at:Option<NaiveDateTime>",
            "token:Option<Uuid>",
        ],
    );

    // Model + migration + schema entry.
    assert!(project.join("src/models/post.rs").is_file());
    assert!(project.join("src/models/mod.rs").is_file());
    assert!(project.join("src/schema.rs").is_file());

    // Repository file.
    let repo = fs::read_to_string(project.join("src/repositories/post.rs")).unwrap();
    assert!(repo.contains("#[autumn_web::repository(Post, api = \"/api/posts\")]"));
    assert!(repo.contains("pub trait PostRepository"));

    // HTML routes — index/show/new/create/edit_form/update; delete goes
    // through the repository's auto-generated JSON REST API.
    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    for needle in [
        "#[get(\"/posts\")]",
        "#[get(\"/posts/{id}\")]",
        "#[get(\"/posts/new\", name = \"new\")]",
        "#[post(\"/posts\")]",
        "#[get(\"/posts/{id}/edit\", name = \"edit\")]",
        "#[post(\"/posts/{id}/update\")]",
        "pub async fn index",
        "pub async fn show",
        "pub async fn new_form(",
        "pub async fn update",
        "use autumn_web::security::{CsrfFormField, CsrfToken, SubmitFormField, SubmitToken};",
        "input type=\"hidden\" name=(csrf_field_name)",
        "(csrf_input(csrf.as_ref(), csrf_field.as_ref()))",
        // Issue #1360: one-time submit token wired into create/update forms.
        // The hidden field name follows the configured
        // `security.submit_token.field_name` (via the `SubmitFormField`
        // extractor), not a hardcoded `_submit_token`.
        "fn submit_token_input(",
        "input type=\"hidden\" name=(submit_field_name) value=(submit_token.token());",
        "submit_token: Option<SubmitToken>",
    ] {
        assert!(routes.contains(needle), "routes file missing: {needle}");
    }

    // Smoke test: real, in-process, DB-backed index/read test (issue #1023) --
    // no raw TcpStream, no AUTUMN_TEST_BASE_URL, no silent env-gated skip.
    let test = fs::read_to_string(project.join("tests/post.rs")).unwrap();
    assert!(test.contains("posts_index_renders_scaffolded_rows"));
    assert!(test.contains("autumn_web::test::{TestApp, TestClient, TestDb}"));
    assert!(!test.contains("TcpStream"));
    assert!(!test.contains("AUTUMN_TEST_BASE_URL"));
    assert!(!test.contains("AUTUMN_TEST_SESSION_COOKIE"));
    assert!(!test.contains("Cookie: {session_cookie}"));
    assert!(test.contains("#[ignore = \"requires Docker"));

    // `routes![]` registration.
    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(main.contains("mod models;"));
    assert!(main.contains("mod routes;"));
    assert!(main.contains("mod schema;"));
    assert!(main.contains("mod repositories;"));
    for entry in [
        "routes::posts::index",
        "routes::posts::show",
        "routes::posts::new_form",
        "routes::posts::create",
        "routes::posts::edit_form",
        "routes::posts::update",
        // Issue #1312: the bulk delete-selected route is mounted alongside the
        // per-row destroy for every non-live, non-sharded HTML scaffold.
        "routes::posts::bulk_delete",
        // Issue #1315: the CSV export route is mounted for every scaffold whose
        // index row set is a repository call the export can reuse verbatim.
        "routes::posts::export_csv",
        "repositories::post::post_api_list",
        "repositories::post::post_api_get",
    ] {
        assert!(
            main.contains(entry),
            "main.rs missing routes![] entry: {entry}\n{main}"
        );
    }
    for entry in [
        "repositories::post::post_api_create",
        "repositories::post::post_api_update",
        "repositories::post::post_api_delete",
    ] {
        assert!(
            !main.contains(entry),
            "main.rs should not mount public scaffold write API route: {entry}\n{main}"
        );
    }
}

// ── `autumn destroy` (issue #1048) ─────────────────────────────────────────

/// Spawn the system `git` binary in `dir` (NOT the `autumn` binary — see
/// [`run_autumn`]), asserting success, and return its stdout.
fn run_git(dir: &Path, args: &[&str]) -> String {
    let output = Command::new("git")
        .args(args)
        .current_dir(dir)
        .output()
        .expect("failed to run git");
    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
    assert!(
        output.status.success(),
        "git {args:?} failed (exit={:?})\nstdout: {stdout}\nstderr: {stderr}",
        output.status.code(),
    );
    stdout
}

/// Recursively collect every file under `root` as `(relative_path, contents)`,
/// sorted for deterministic comparison. Used to assert a project's working
/// tree is byte-for-byte identical before/after a `generate`+`destroy`
/// round-trip — a filesystem-level equivalent of `git status` being clean
/// that doesn't require a `git` binary in the test sandbox.
fn snapshot_tree(root: &Path) -> Vec<(String, Vec<u8>)> {
    fn walk(dir: &Path, root: &Path, out: &mut Vec<(String, Vec<u8>)>) {
        for entry in fs::read_dir(dir).expect("read_dir").filter_map(Result::ok) {
            let path = entry.path();
            if path.file_name().is_some_and(|n| n == ".git") {
                // Never compare git's own internals — its background
                // maintenance can create/remove transient files (e.g.
                // `.git/objects/maintenance.lock`) between snapshots,
                // producing spurious diffs unrelated to anything
                // generate/destroy touched.
                continue;
            }
            if path.is_dir() {
                walk(&path, root, out);
            } else {
                let rel = path
                    .strip_prefix(root)
                    .unwrap()
                    .display()
                    .to_string()
                    .replace('\\', "/");
                let contents = fs::read(&path).expect("read file");
                out.push((rel, contents));
            }
        }
    }
    let mut out = Vec::new();
    walk(root, root, &mut out);
    out.sort_by(|a, b| a.0.cmp(&b.0));
    out
}

/// The headline acceptance test (issue #1048's success metric): `autumn
/// generate scaffold Post title:String` immediately followed by `autumn
/// destroy scaffold Post title:String` returns the project's working tree
/// byte-for-byte identical to its pre-generate state — both via a
/// filesystem snapshot comparison and via `git status --porcelain` being
/// empty against a real commit, exactly the round-trip the issue describes.
#[test]
fn generate_then_destroy_scaffold_round_trips_git_clean() {
    let (_tmp, project) = fresh_project("destroy-scaffold-app");

    run_git(&project, &["init"]);
    run_git(&project, &["add", "-A"]);
    run_git(
        &project,
        &[
            "-c",
            "user.email=t@t.com",
            "-c",
            "user.name=t",
            "commit",
            "-m",
            "base",
        ],
    );

    let before = snapshot_tree(&project);

    run_autumn(&project, &["generate", "scaffold", "Post", "title:String"]);
    assert!(project.join("src/models/post.rs").is_file());
    assert!(project.join("src/routes/posts.rs").is_file());
    assert!(project.join("src/repositories/post.rs").is_file());

    run_autumn(&project, &["destroy", "scaffold", "Post", "title:String"]);

    let after = snapshot_tree(&project);
    assert_eq!(
        before, after,
        "working tree must be byte-identical after generate+destroy"
    );

    let status_stdout = run_git(&project, &["status", "--porcelain"]);
    assert!(
        status_stdout.trim().is_empty(),
        "git status must be clean after generate+destroy, got:\n{status_stdout}"
    );
}

#[test]
fn generate_then_destroy_model_round_trips_git_clean() {
    let (_tmp, project) = fresh_project("destroy-model-app");
    run_git(&project, &["init"]);
    run_git(&project, &["add", "-A"]);
    run_git(
        &project,
        &[
            "-c",
            "user.email=t@t.com",
            "-c",
            "user.name=t",
            "commit",
            "-m",
            "base",
        ],
    );

    let before = snapshot_tree(&project);
    run_autumn(&project, &["generate", "model", "Post", "title:String"]);
    run_autumn(&project, &["destroy", "model", "Post", "title:String"]);
    let after = snapshot_tree(&project);
    assert_eq!(before, after);

    let status_stdout = run_git(&project, &["status", "--porcelain"]);
    assert!(status_stdout.trim().is_empty());
}

#[test]
fn generate_then_destroy_migration_round_trips_git_clean() {
    let (_tmp, project) = fresh_project("destroy-migration-app");
    run_autumn(&project, &["generate", "model", "Post", "title:String"]);
    run_git(&project, &["init"]);
    run_git(&project, &["add", "-A"]);
    run_git(
        &project,
        &[
            "-c",
            "user.email=t@t.com",
            "-c",
            "user.name=t",
            "commit",
            "-m",
            "base",
        ],
    );

    let before = snapshot_tree(&project);
    run_autumn(
        &project,
        &[
            "generate",
            "migration",
            "AddSubtitleToPosts",
            "subtitle:String",
        ],
    );
    run_autumn(
        &project,
        &[
            "destroy",
            "migration",
            "AddSubtitleToPosts",
            "subtitle:String",
        ],
    );
    let after = snapshot_tree(&project);
    assert_eq!(before, after);

    let status_stdout = run_git(&project, &["status", "--porcelain"]);
    assert!(status_stdout.trim().is_empty());
}

#[test]
fn generate_then_destroy_plugin_round_trips_git_clean() {
    // Regression test (issue #1048 PR review): `plan_plugin` refuses a
    // non-empty target directory unless `--force` — a generate-time
    // collision guard. Without special-casing destroy mode, `autumn destroy
    // plugin Foo` would always hit that same guard (the plugin directory
    // legitimately exists, holding the files this destroy is about to
    // remove) and fail before ever reaching `Plan::revert`, even with no
    // `--force` flag and no actual divergence.
    let (_tmp, project) = fresh_project("destroy-plugin-app");

    run_git(&project, &["init"]);
    run_git(&project, &["add", "-A"]);
    run_git(
        &project,
        &[
            "-c",
            "user.email=t@t.com",
            "-c",
            "user.name=t",
            "commit",
            "-m",
            "base",
        ],
    );

    let before = snapshot_tree(&project);

    run_autumn(&project, &["generate", "plugin", "Foo"]);
    assert!(project.join("autumn-foo-plugin/Cargo.toml").is_file());

    run_autumn(&project, &["destroy", "plugin", "Foo"]);
    assert!(!project.join("autumn-foo-plugin").exists());

    let after = snapshot_tree(&project);
    assert_eq!(
        before, after,
        "working tree must be byte-identical after generate+destroy"
    );

    let status_stdout = run_git(&project, &["status", "--porcelain"]);
    assert!(
        status_stdout.trim().is_empty(),
        "git status must be clean after generate+destroy, got:\n{status_stdout}"
    );
}

/// AC5: `destroy --dry-run` prints a plan and exits 0 without touching disk.
#[test]
fn destroy_dry_run_writes_nothing() {
    let (_tmp, project) = fresh_project("destroy-dry-run-app");
    run_autumn(&project, &["generate", "scaffold", "Post", "title:String"]);
    let before = snapshot_tree(&project);

    let (stdout, _) = run_autumn(
        &project,
        &["destroy", "scaffold", "Post", "title:String", "--dry-run"],
    );
    assert!(stdout.contains("Dry run"));
    assert!(stdout.contains("Would remove") || stdout.contains("Would revert"));

    let after = snapshot_tree(&project);
    assert_eq!(before, after, "--dry-run must not touch disk");
}

/// AC7: destroy refuses on diverged content unless `--force`, and never
/// deletes the hand-edited file in that case.
#[test]
fn destroy_refuses_on_diverged_file_without_force() {
    let (_tmp, project) = fresh_project("destroy-diverged-app");
    run_autumn(&project, &["generate", "scaffold", "Post", "title:String"]);

    let model_path = project.join("src/models/post.rs");
    let mut content = fs::read_to_string(&model_path).unwrap();
    content.push_str("\n// hand-edited by the user\n");
    fs::write(&model_path, &content).unwrap();

    let (_, stderr, code) =
        run_autumn_failing(&project, &["destroy", "scaffold", "Post", "title:String"]);
    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("diverged") || stderr.contains("Diverged"),
        "expected a divergence error, got stderr: {stderr}"
    );
    assert!(model_path.is_file(), "diverged file must not be deleted");
    assert!(
        fs::read_to_string(&model_path)
            .unwrap()
            .contains("hand-edited")
    );

    // --force overrides the guard and proceeds with the destroy.
    run_autumn(
        &project,
        &["destroy", "scaffold", "Post", "title:String", "--force"],
    );
    assert!(!model_path.exists());
}

#[test]
fn generate_scaffold_api_only() {
    let (_tmp, project) = fresh_project("scaffold-api-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "body:Text",
            "published:bool",
            "--api",
        ],
    );

    // Model + migration + schema entry.
    assert!(project.join("src/models/post.rs").is_file());
    assert!(project.join("src/models/mod.rs").is_file());
    assert!(project.join("src/schema.rs").is_file());

    // Repository file.
    let repo = fs::read_to_string(project.join("src/repositories/post.rs")).unwrap();
    assert!(repo.contains("#[autumn_web::repository(Post, api = \"/api/posts\")]"));
    assert!(repo.contains("pub trait PostRepository"));
    assert!(repo.contains("Generated by `autumn generate scaffold --api`"));
    assert!(repo.contains("allow_unauthorized_repository_api = true"));

    // No HTML routes file
    assert!(!project.join("src/routes/posts.rs").is_file());

    // Smoke test: real, in-process, DB-backed read test (issue #1023),
    // paginated per issue #1237 — asserts the `Page` envelope + page 2 advance.
    let test = fs::read_to_string(project.join("tests/post.rs")).unwrap();
    assert!(test.contains("posts_api_list_paginates_against_a_real_database"));
    assert!(test.contains("autumn_web::test::{TestApp, TestClient, TestDb}"));
    assert!(!test.contains("TcpStream"));
    assert!(!test.contains("AUTUMN_TEST_BASE_URL"));
    assert!(test.contains("#[ignore = \"requires Docker"));
    assert!(test.contains("/api/posts"));
    assert!(
        test.contains("PageRequest") && test.contains("Page::new"),
        "the --api smoke test must paginate via the Page envelope: {test}"
    );
    assert!(
        test.contains("page 2 must differ from page 1"),
        "the --api smoke test must assert pages advance: {test}"
    );
    // Required-column seed drives 25 rows off a single `generate_series` and
    // must not fall back to `INSERT ... DEFAULT VALUES` (which cannot satisfy
    // the NOT NULL `title`/`published` columns).
    assert!(
        test.contains("FROM generate_series(1, 25) AS g"),
        "required-column --api seed must use generate_series: {test}"
    );
    assert!(
        !test.contains("INSERT INTO posts DEFAULT VALUES"),
        "required-column --api seed must not fall back to DEFAULT VALUES: {test}"
    );

    // `routes![]` registration.
    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(main.contains("mod models;"));
    assert!(
        !main.contains("mod routes;"),
        "main.rs should not declare routes mod if api is set: {main}"
    );
    assert!(main.contains("mod schema;"));
    assert!(main.contains("mod repositories;"));
    for entry in [
        "repositories::post::post_api_create",
        "repositories::post::post_api_update",
        "repositories::post::post_api_delete",
        "repositories::post::post_api_list",
        "repositories::post::post_api_get",
    ] {
        assert!(
            main.contains(entry),
            "main.rs missing routes![] entry: {entry}\n{main}"
        );
    }
    for entry in [
        "routes::posts::index",
        "routes::posts::show",
        "routes::posts::new_form",
        "routes::posts::create",
        "routes::posts::edit_form",
        "routes::posts::update",
    ] {
        assert!(
            !main.contains(entry),
            "main.rs should not mount HTML route: {entry}\n{main}"
        );
    }
}

#[test]
fn generate_scaffold_accepts_metadata_flags() {
    let (_tmp, project) = fresh_project("scaffold-metadata-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Bookmark",
            "url:String",
            "title:String",
            "tag:String",
            "alive:bool",
            "--index",
            "url",
            "--index",
            "tag",
            "--validate",
            "url=url",
            "--validate",
            "title=length:min=1,max=200",
            "--default",
            "alive=true",
            "--query",
            "find_by_tag:tag",
            "--query",
            "find_by_alive:alive",
        ],
    );

    let model = fs::read_to_string(project.join("src/models/bookmark.rs")).unwrap();
    assert!(model.contains("#[indexed]\n    #[validate(url)]\n    pub url: String,"));
    assert!(model.contains("#[validate(length(min = 1, max = 200))]\n    pub title: String,"));
    assert!(model.contains("#[indexed]\n    pub tag: String,"));
    assert!(model.contains("#[default]\n    pub alive: bool,"));

    let repo = fs::read_to_string(project.join("src/repositories/bookmark.rs")).unwrap();
    assert!(repo.contains("fn find_by_tag(tag: String) -> Vec<Bookmark>;"));
    assert!(repo.contains("fn find_by_alive(alive: bool) -> Vec<Bookmark>;"));

    let routes = fs::read_to_string(project.join("src/routes/bookmarks.rs")).unwrap();
    // The views render through one `form_for` call (issue #1135): the
    // per-field controls (including the required signal for the three
    // non-nullable strings) come from the `#[model]`-derived `FormModel`
    // descriptors, delegated to from the generated form struct.
    assert!(routes.contains("impl autumn_web::form::FormModel for BookmarkForm"));
    assert!(routes.contains("<Bookmark as autumn_web::form::FormModel>::form_fields()"));
    assert!(routes.contains("autumn_web::form::form_for(changeset, action, \"post\")"));
    assert!(!routes.contains("autumn_web::form::required_text_input(&changeset"));
    // `alive` is defaulted → excluded from the FORM entirely. Scoped to the
    // generated form struct + its `form_fields` descriptors rather than the whole
    // file: since issue #1315 the module also carries a `CsvSchema` impl, whose
    // column list is the MODEL's columns (what `show` renders), not the form's —
    // a defaulted column is still data an author downloading a spreadsheet wants.
    // The ONE remaining `"alive"` string in the module is that CSV header; the
    // form struct, its descriptors and every rendered control are free of it.
    assert_eq!(
        routes.matches("\"alive\"").count(),
        1,
        "`alive` is defaulted: its only quoted mention may be the CSV header:\n{routes}"
    );
    assert!(routes.contains(r#"&["id", "url", "title", "tag", "alive", "created_at"]"#));
    assert!(routes.contains("self.alive.to_string(),"));
    assert!(routes.contains("bookmarks::tag.eq(new.tag.clone())"));
    assert!(!routes.contains("bookmarks::alive.eq("));
    assert!(!routes.contains("new.alive"));

    let migration = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .find(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_create_bookmarks")
        })
        .expect("create_bookmarks migration should exist");
    let up = fs::read_to_string(migration.path().join("up.sql")).unwrap();
    assert!(up.contains("alive BOOLEAN NOT NULL DEFAULT TRUE"));
    assert!(up.contains("CREATE INDEX idx_bookmarks_url ON bookmarks (url);"));
    assert!(up.contains("CREATE INDEX idx_bookmarks_tag ON bookmarks (tag);"));

    let cargo_toml = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(
        cargo_toml.contains("validator ="),
        "validation attributes need validator in Cargo.toml:\n{cargo_toml}"
    );
}

#[test]
fn generate_scaffold_rejects_query_name_field_mismatch() {
    let (_tmp, project) = fresh_project("scaffold-bad-query-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "Bookmark",
            "tag:String",
            "alive:bool",
            "--query",
            "find_by_alive:tag",
        ],
    );

    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("find_by_alive:tag") && stderr.contains("must match field 'tag'"),
        "expected query mismatch validation error; got stderr: {stderr}"
    );
}

#[test]
fn generate_scaffold_rejects_validator_field_type_mismatch() {
    let (_tmp, project) = fresh_project("scaffold-bad-validator-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "Bookmark",
            "alive:bool",
            "--validate",
            "alive=url",
        ],
    );

    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("alive=url") && stderr.contains("url validation requires String or Text"),
        "expected validator type validation error; got stderr: {stderr}"
    );
}

#[test]
fn generate_scaffold_rejects_i32_default_outside_sql_integer_range() {
    let (_tmp, project) = fresh_project("scaffold-bad-default-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "Counter",
            "count:i32",
            "--default",
            "count=9223372036854775807",
        ],
    );

    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("count=9223372036854775807")
            && stderr.contains("i32 defaults must fit the SQL INTEGER range"),
        "expected i32 default range validation error; got stderr: {stderr}"
    );
}

/// Issue #1048's success metric, verified end-to-end: `autumn generate
/// scaffold Post title:String` immediately followed by `autumn destroy
/// scaffold Post title:String` leaves `cargo check` green on the
/// round-tripped project — not just a clean working tree (already covered by
/// [`generate_then_destroy_scaffold_round_trips_git_clean`]), but a project
/// that still *compiles*, proving destroy never leaves a dangling `mod`
/// declaration, `routes![]` entry, or Cargo.toml dependency behind.
///
/// Ignored by default; slow (compiles the full `autumn-web` dependency
/// tree) and requires network access to fetch crates. Run with:
/// `cargo test -p autumn-cli --test generate destroy_scaffold_round_trip_leaves_cargo_check_green -- --ignored --exact`
#[test]
#[ignore = "slow: compiles the generated project with cargo check"]
fn destroy_scaffold_round_trip_leaves_cargo_check_green() {
    let (_tmp, project) = fresh_project("destroy-scaffold-check-app");
    patch_generated_cargo_toml(&project);

    run_autumn(&project, &["generate", "scaffold", "Post", "title:String"]);
    run_autumn(&project, &["destroy", "scaffold", "Post", "title:String"]);

    let check = Command::new("cargo")
        .args(["check", "--all-targets"])
        .current_dir(&project)
        .output()
        .expect("failed to run cargo check");
    assert!(
        check.status.success(),
        "cargo check failed on the round-tripped project:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Slow live-HTTP check: scaffold a fresh project, run migrations against a
/// real Postgres testcontainer, boot the generated server, and assert the
/// generated HTML and JSON routes actually respond.
///
/// Ignored by default; requires Docker and `diesel` CLI on PATH. Run with:
/// `cargo test -p autumn-cli --test generate generated_scaffold_serves_posts_index_and_json_api -- --ignored --exact`
#[tokio::test]
#[ignore = "slow: starts Postgres, runs diesel migrations, builds and boots a generated app"]
async fn generated_scaffold_serves_posts_index_and_json_api() {
    use testcontainers::runners::AsyncRunner;
    use testcontainers_modules::postgres::Postgres;

    let (_tmp, project) = fresh_project("scaffold-live");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "body:Text",
            "published:bool",
        ],
    );

    let postgres = Postgres::default()
        .start()
        .await
        .expect("failed to start Postgres testcontainer");
    let host = postgres.get_host().await.expect("postgres host");
    let pg_port = postgres
        .get_host_port_ipv4(5432)
        .await
        .expect("postgres port");
    let database_url = format!("postgres://postgres:postgres@{host}:{pg_port}/postgres");

    run_autumn_with_env(
        &project,
        &["migrate"],
        &[("AUTUMN_DATABASE__URL", database_url.as_str())],
    );

    let build = Command::new("cargo")
        .args(["build"])
        .current_dir(&project)
        .output()
        .expect("failed to run cargo build");
    assert!(
        build.status.success(),
        "cargo build failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&build.stdout),
        String::from_utf8_lossy(&build.stderr),
    );

    let port = free_port();
    let child = Command::new("cargo")
        .args(["run", "--quiet"])
        .current_dir(&project)
        .env("AUTUMN_SERVER__PORT", port.to_string())
        .env("AUTUMN_DATABASE__URL", &database_url)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to spawn generated server");

    let client = reqwest::Client::new();
    let base = format!("http://127.0.0.1:{port}");
    let _server = wait_for_server_ready_async(child, &client, &base).await;

    let response = client
        .get(format!("{base}/posts"))
        .send()
        .await
        .expect("GET /posts failed");
    assert_eq!(response.status(), 200, "GET /posts status");
    let html = response.text().await.expect("GET /posts body");
    assert!(
        html.contains("<h1>Posts</h1>") && html.contains("New Post"),
        "GET /posts did not render the generated index template:\n{html}",
    );

    let response = client
        .get(format!("{base}/api/posts"))
        .send()
        .await
        .expect("GET /api/posts failed");
    assert_eq!(response.status(), 200, "GET /api/posts status");
    let body = response.text().await.expect("GET /api/posts body");
    let envelope: serde_json::Value =
        serde_json::from_str(body.trim()).expect("GET /api/posts must return a JSON Page envelope");
    let content = envelope["content"]
        .as_array()
        .expect("Page envelope must carry a content array");
    assert!(content.is_empty(), "empty JSON index body: {body}");
    assert_eq!(
        envelope["total_elements"], 0,
        "empty JSON index total_elements"
    );
}

#[test]
fn generate_outside_project_root_fails_clearly() {
    let tmp = tempfile::tempdir().unwrap();
    let (_, stderr, code) =
        run_autumn_failing(tmp.path(), &["generate", "model", "Post", "title:String"]);
    assert_eq!(code, Some(1));
    assert!(stderr.contains("not inside an Autumn project"));
}

#[test]
fn generate_help_documents_field_dsl() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("model"));
    assert!(stdout.contains("migration"));
    assert!(stdout.contains("scaffold"));
}

#[test]
fn generate_help_documents_decimal_field_type() {
    // AC4 (issue #1038): `decimal` must be discoverable from `--help`, not
    // just accepted silently by the parser.
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("decimal"), "got: {stdout}");
    assert!(stdout.contains("NUMERIC"), "got: {stdout}");
}

#[test]
fn generate_model_help_shows_example() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "model", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("autumn generate model Post"));
    assert!(stdout.contains("--dry-run"));
    assert!(stdout.contains("--force"));
}

/// Slow end-to-end check: scaffold a fresh project, run `autumn generate
/// scaffold`, and `cargo check --tests` the result against the local `autumn-web`
/// crate. Verifies the generator adds every dep its emitted code needs and
/// that the generated application and smoke test actually type-check.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("scaffold-build");

    // Patch Cargo.toml to point at the *local* autumn-web crate (so we don't
    // depend on crates.io having this exact version published). We do NOT
    // pre-add the diesel/maud/etc deps here — that's what the generator is
    // supposed to do automatically.
    let cargo_toml_path = project.join("Cargo.toml");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "body:Text",
            "published:bool",
            "archived:Option<bool>",
            "subtitle:Option<String>",
            "views:Option<i64>",
            "rank:i32",
            "rating:f64",
            "weight:Option<f32>",
            "published_at:Option<NaiveDateTime>",
            "scheduled_at:DateTime",
            "token:Option<Uuid>",
            "status:enum{draft,published,archived}",
            "mood:Option<enum{happy,sad}>",
            "price:decimal{10,2}",
            "balance:Option<decimal>",
            "payload:Bytea",
            "nickname:Option<Bytea>",
            "--validate",
            "title=length:min=1,max=200",
            "--live-validation",
        ],
    );

    // A `Bytea` field's `{Pascal}Form` representation must actually round-trip:
    // `Vec<u8>` cannot deserialize from a single url-encoded value at all
    // (issue #1124 review), so both nullable and non-nullable Bytea fields
    // are represented as `String`/`Option<String>` on the form.
    let routes_bytea = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    assert!(
        routes_bytea.contains("pub payload: String,"),
        "{routes_bytea}"
    );
    assert!(
        routes_bytea.contains("pub nickname: Option<String>,"),
        "{routes_bytea}"
    );

    // The `--live-validation` inline-validation handler must compile against
    // the real framework too (issue #1124 follow-up: it now decodes the full
    // form via `decode_form` and renders through `text_input_htmx`, rather
    // than a hand-rolled per-rule check returning a bare error span). `title`
    // is non-nullable, so it keeps the `required` htmx variant.
    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    assert!(
        routes.contains("pub async fn validate_title("),
        "expected a validate_title handler:\n{routes}"
    );
    assert!(
        routes.contains("autumn_web::form::required_text_input_htmx(&changeset, \"title\""),
        "validate_title must return the full required_text_input_htmx wrapper:\n{routes}"
    );

    // The generator must have added every dep its emitted code needs.
    let cargo_toml_after = fs::read_to_string(&cargo_toml_path).unwrap();
    for dep in [
        "chrono",
        "diesel",
        "diesel-async",
        "maud",
        "serde",
        "serde_json",
        "serde_urlencoded",
        "url",
        "rust_decimal",
    ] {
        assert!(
            cargo_toml_after.contains(&format!("{dep} =")),
            "Cargo.toml is missing '{dep}' after `generate scaffold`"
        );
    }

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Issue #1323: a `--belongs-to` scaffold compiles against the real framework
/// AND its generated nested write-path test passes.
///
/// This is the only machine proof that the nested surface type-checks: the
/// nested handlers, the shared `children_section` helper, the `exclude_parent_fk`
/// form flag, the `paths::nested_index`/`nested_create` helpers, AND — critically
/// — the *injected* edit to the parent's already-generated `show` handler, which
/// is a textual patch to a file this invocation does not own. A `cargo check`
/// here is what catches that patch going stale if the flat `show` template ever
/// changes shape.
///
/// The generated nested test needs no database (its rows are in-process), so it
/// is run for real rather than just compiled.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_nested_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("nested-scaffold-build");
    patch_generated_cargo_toml(&project);

    run_autumn(&project, &["generate", "scaffold", "Post", "title:String"]);
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Comment",
            "body:Text",
            "post:references",
            "--belongs-to",
            "Post",
        ],
    );

    let child = fs::read_to_string(project.join("src/routes/comments.rs")).unwrap();
    assert!(
        child.contains("#[get(\"/posts/{post_id}/comments\", name = \"nested_index\")]"),
        "missing the nested read route:\n{child}"
    );
    assert!(
        child.contains("#[post(\"/posts/{post_id}/comments\", name = \"nested_create\")]"),
        "missing the nested create route:\n{child}"
    );
    let parent = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    assert!(
        parent.contains("crate::routes::comments::children_section("),
        "the parent show must render its children:\n{parent}"
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on the nested scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );

    // AC7: create child under parent -> appears in that parent's list -> does
    // NOT appear under a different parent. DB-free, so run it here.
    let output = Command::new("cargo")
        .args(["test", "--test", "comment", "comments_nested_under_parent"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "the generated nested write-path test failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("test result: ok"),
        "expected the generated nested test to pass:\n{stdout}"
    );
}

/// Issue #1125: a scaffold WITH an owner column generates a record-level
/// `Policy`/`Scope`, authorizes the mutating HTML handlers, scopes the index,
/// and emits a cross-user 403 smoke test. `cargo check --tests` proves the
/// whole thing (policy file, authorize wiring, scoped index, cross-user test)
/// type-checks against the real framework; the generated cross-user test needs
/// no database, so we also run it directly to prove the 403 semantics hold end
/// to end.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_policy_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("policy-scaffold-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "body:Text",
            "author_id:i64",
        ],
    );

    // The generated policy, its registration, and the authorize wiring exist.
    let policy = fs::read_to_string(project.join("src/policies/post.rs")).unwrap();
    assert!(
        policy.contains("impl Policy<Post> for PostPolicy"),
        "policy file must define PostPolicy:\n{policy}"
    );
    assert!(
        policy.contains("Some(post.author_id)"),
        "owner check must use author_id:\n{policy}"
    );
    let main_rs = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(
        main_rs.contains(".policy::<crate::models::post::Post, _>"),
        "main.rs must register the policy:\n{main_rs}"
    );
    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    assert!(
        routes.contains("autumn_web::authorization::authorize::<Post>"),
        "routes must authorize mutating handlers:\n{routes}"
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated policy scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );

    // The cross-user 403 test needs no database — run it and prove it passes.
    let cross_user = Command::new("cargo")
        .args([
            "test",
            "--test",
            "post",
            "posts_cross_user_mutations_are_forbidden",
        ])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        cross_user.status.success(),
        "generated cross-user 403 test failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&cross_user.stdout),
        String::from_utf8_lossy(&cross_user.stderr),
    );
    assert!(
        String::from_utf8_lossy(&cross_user.stdout).contains("test result: ok"),
        "expected the cross-user test to pass:\n{}",
        String::from_utf8_lossy(&cross_user.stdout)
    );

    // Issue #1315: the generated CSV download test needs no database either.
    // Running it here is the only place the repo proves the emitted test
    // actually passes against the real `export_csv` + `Download` pair, rather
    // than merely type-checking.
    let export_csv = Command::new("cargo")
        .args([
            "test",
            "--test",
            "post",
            "posts_export_csv_downloads_a_spreadsheet",
        ])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        export_csv.status.success(),
        "generated CSV export test failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&export_csv.stdout),
        String::from_utf8_lossy(&export_csv.stderr),
    );
    assert!(
        String::from_utf8_lossy(&export_csv.stdout).contains("1 passed"),
        "expected the CSV export test to run and pass:\n{}",
        String::from_utf8_lossy(&export_csv.stdout)
    );
}

/// Companion to [`generated_policy_scaffold_cargo_checks`] proving the
/// *nullable* owner-column path compiles (PR #1831 review): a `user:references?`
/// owner is `Option<i64>`, so the generated `can_update`/`can_delete` must
/// compare it option-to-option (`ctx.user_id_i64() == post.user_id`) rather
/// than wrapping it in `Some(...)` (which would compare `Option<i64>` to
/// `Option<Option<i64>>` and fail to build), and the scope must still `.eq()`
/// the nullable diesel column.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_nullable_owner_policy_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("policy-nullable-owner-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Note",
            "title:String",
            "body:Text",
            "user:references?",
        ],
    );

    let policy = fs::read_to_string(project.join("src/policies/note.rs")).unwrap();
    assert!(
        policy.contains("ctx.user_id_i64() == note.user_id"),
        "nullable owner must compare option-to-option:\n{policy}"
    );
    assert!(
        !policy.contains("Some(note.user_id)"),
        "nullable owner must not wrap in Some(...):\n{policy}"
    );
    assert!(
        policy.contains("notes::user_id.eq(owner_id)"),
        "scope must filter on the nullable owner column:\n{policy}"
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated nullable-owner policy scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Issue #1830 companion to [`generated_policy_scaffold_cargo_checks`] for the
/// `--live` variant: an owner column on a `--live` scaffold now record-authorizes
/// the mutating handlers (loading the current row through the *repository*, not
/// raw diesel) and owner-scopes the index while keeping the SSE `<ul>` island.
/// `cargo check --tests` proves the repository-based authorize wiring compiles
/// against the real framework.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_live_owner_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("live-owner-scaffold-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "author_id:i64",
            "--live",
        ],
    );

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    assert!(
        routes.contains("autumn_web::authorization::authorize::<Post>"),
        "live routes must authorize mutating handlers:\n{routes}"
    );
    assert!(
        routes.contains("let current: Post = repo.find_by_id(*id).await?"),
        "live variant must load the current row via the repository:\n{routes}"
    );
    assert!(
        routes.contains("posts::author_id.eq(owner_id)"),
        "live index must be owner-scoped:\n{routes}"
    );
    assert!(
        routes.contains("sse-connect=(paths::events())"),
        "live owner index must keep the SSE list contract:\n{routes}"
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated live-owner scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Issue #1830 companion for the `--sharded` variant: an owner column on a
/// `--sharded` scaffold record-authorizes the mutating handlers (loading the
/// current row through a `from_shard` repository) and owner-scopes the index on
/// the `ShardedDb` connection. `cargo check --tests` proves the sharded
/// authorize wiring compiles against the real framework.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_sharded_owner_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("sharded-owner-scaffold-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "author_id:i64",
            "--sharded",
        ],
    );

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    assert!(
        routes.contains("autumn_web::authorization::authorize::<Post>"),
        "sharded routes must authorize mutating handlers:\n{routes}"
    );
    assert!(
        routes.contains(
            "let current: Post = PgPostRepository::from_shard(&db).find_by_id(*id).await?"
        ),
        "sharded variant must load the current row via from_shard:\n{routes}"
    );
    assert!(
        routes.contains("posts::author_id.eq(owner_id)"),
        "sharded index must be owner-scoped:\n{routes}"
    );
    assert!(
        !routes.contains("mut db: Db"),
        "sharded handlers must use ShardedDb, not a bare Db extractor:\n{routes}"
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated sharded-owner scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Issue #1830 companion for the attachment variant: an owner column on an
/// attachment scaffold record-authorizes the mutating handlers by REUSING the
/// `state: State<AppState>` wrapper the multipart upload already threads
/// (`&*state`) rather than injecting a second, conflicting `State` extractor —
/// the exact case #1125 excluded. `cargo check --tests` proves the deref-based
/// authorize wiring compiles against the real framework.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_attachment_owner_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("attachment-owner-scaffold-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "author_id:i64",
            "avatar:Attachment",
        ],
    );

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    assert!(
        routes.contains("autumn_web::authorization::authorize_create::<Post>(&*state, &session)"),
        "attachment create must authorize_create via the reused &*state wrapper:\n{routes}"
    );
    assert!(
        routes.contains(
            "autumn_web::authorization::authorize::<Post>(&*state, &session, \"update\", &current)"
        ),
        "attachment update must authorize via &*state:\n{routes}"
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated attachment-owner scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Slow end-to-end check (issue #1124): scaffold a model with a `--validate`
/// rule and prove the generated changeset round-trip actually compiles *and*
/// runs — a rejected submission gets 422 with the other field preserved and
/// an inline error, a valid one still succeeds (AC1-AC5, AC7). Runs the
/// generated `tests/<snake>.rs` changeset smoke test directly (it needs no
/// Docker/Postgres — see `render_validation_rejection_smoke_test`), not just
/// `cargo check`.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-builds and runs a fresh project's test suite — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_validated_scaffold_round_trip_test_passes() {
    let (_tmp, project) = fresh_project("scaffold-validation-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "body:String",
            "--validate",
            "title=length:min=1,max=200",
        ],
    );

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    assert!(routes.contains("pub struct PostForm"));
    assert!(routes.contains("into_changeset()"));
    assert!(routes.contains("StatusCode::UNPROCESSABLE_ENTITY"));

    let test_file = fs::read_to_string(project.join("tests/post.rs")).unwrap();
    assert!(test_file.contains("posts_rejects_invalid_title_and_preserves_input"));

    let output = Command::new("cargo")
        .args([
            "test",
            "--test",
            "post",
            "posts_rejects_invalid_title_and_preserves_input",
        ])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "the generated changeset round-trip test failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("test result: ok"),
        "expected the generated test to pass:\n{stdout}"
    );

    // Issue #1127: the same generated binary also carries the in-process
    // write-path suite (create/update/delete + the validation-failure
    // re-render). Run it by name and prove it compiles and passes — no Docker,
    // no external services.
    let write_path = Command::new("cargo")
        .args(["test", "--test", "post", "posts_write_path_crud"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        write_path.status.success(),
        "the generated write-path CRUD test failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&write_path.stdout),
        String::from_utf8_lossy(&write_path.stderr),
    );
    assert!(
        String::from_utf8_lossy(&write_path.stdout).contains("test result: ok"),
        "expected the generated write-path test to pass:\n{}",
        String::from_utf8_lossy(&write_path.stdout)
    );
}

/// Slow end-to-end check: scaffold a fresh project, run `autumn generate job`,
/// and `cargo check` the result against the local `autumn-web` crate. Verifies
/// the generator produces code that compiles without hand-editing.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_job_cargo_checks() {
    let (_tmp, project) = fresh_project("job-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "job",
            "SendWelcomeEmail",
            "user_id:i64",
            "email:String",
            "amount:decimal",
        ],
    );

    // The generated Cargo.toml must include serde and — since a `decimal`
    // field is present — rust_decimal (issue #1038 PR review: job_deps
    // previously omitted it, so the generated args struct referenced
    // rust_decimal::Decimal without the crate ever being declared).
    let cargo_toml = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(
        cargo_toml.contains("serde"),
        "Cargo.toml must include serde after generate job"
    );
    assert!(
        cargo_toml.contains("rust_decimal"),
        "Cargo.toml must include rust_decimal after generate job with a decimal field"
    );

    // The generator must have created the expected files.
    assert!(
        project.join("src/jobs/send_welcome_email.rs").exists(),
        "src/jobs/send_welcome_email.rs must exist"
    );
    assert!(
        project.join("src/jobs/mod.rs").exists(),
        "src/jobs/mod.rs must exist"
    );

    // main.rs must be wired up.
    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(main.contains("mod jobs;"), "main.rs must declare mod jobs");
    assert!(
        main.contains(".jobs(jobs::registered_jobs())"),
        "main.rs must include .jobs() call"
    );

    // The whole project must cargo-check cleanly (inline tests included).
    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated job failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

// ── `unique` field marker (issue #1032) ─────────────────────────────────────

#[test]
fn generate_model_unique_field_emits_unique_index() {
    let (_tmp, project) = fresh_project("unique-app");
    run_autumn(
        &project,
        &["generate", "model", "User", "email:String:unique"],
    );

    let migration = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .find(|e| e.file_name().to_string_lossy().ends_with("_create_users"))
        .expect("create_users migration should exist");
    let up = fs::read_to_string(migration.path().join("up.sql")).unwrap();
    assert!(
        up.contains("CREATE UNIQUE INDEX idx_users_email_unique ON users (email);"),
        "got:\n{up}"
    );
    assert!(
        !up.contains("CREATE INDEX idx_users_email ON"),
        "a unique field must not also emit a plain, non-unique index; got:\n{up}"
    );
}

#[test]
fn generate_model_unique_flag_marks_field_unique() {
    let (_tmp, project) = fresh_project("unique-flag-app");
    run_autumn(
        &project,
        &[
            "generate",
            "model",
            "User",
            "email:String",
            "--unique",
            "email",
        ],
    );

    let migration = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .find(|e| e.file_name().to_string_lossy().ends_with("_create_users"))
        .expect("create_users migration should exist");
    let up = fs::read_to_string(migration.path().join("up.sql")).unwrap();
    assert!(
        up.contains("CREATE UNIQUE INDEX idx_users_email_unique ON users (email);"),
        "got:\n{up}"
    );
}

#[test]
fn generate_model_unique_flag_rejects_unknown_field() {
    let (_tmp, project) = fresh_project("unique-flag-unknown-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "model",
            "User",
            "email:String",
            "--unique",
            "bogus",
        ],
    );
    assert_eq!(code, Some(1));
    assert!(stderr.contains("bogus"), "got: {stderr}");
}

#[test]
fn generate_migration_add_unique_column_emits_unique_index() {
    let (_tmp, project) = fresh_project("unique-migration-app");
    run_autumn(
        &project,
        &[
            "generate",
            "migration",
            "AddEmailToUsers",
            "email:String:unique",
        ],
    );

    let migrations = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_add_email_to_users")
        })
        .collect::<Vec<_>>();
    assert_eq!(migrations.len(), 1);
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(
        up.contains("ALTER TABLE users ADD COLUMN email TEXT NOT NULL;"),
        "got:\n{up}"
    );
    assert!(
        up.contains("CREATE UNIQUE INDEX idx_users_email_unique ON users (email);"),
        "got:\n{up}"
    );
}

#[test]
fn generate_migration_unique_flag_emits_unique_index() {
    let (_tmp, project) = fresh_project("unique-migration-flag-app");
    run_autumn(
        &project,
        &[
            "generate",
            "migration",
            "AddEmailToUsers",
            "email:String",
            "--unique",
            "email",
        ],
    );

    let migrations = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_add_email_to_users")
        })
        .collect::<Vec<_>>();
    assert_eq!(migrations.len(), 1);
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(
        up.contains("CREATE UNIQUE INDEX idx_users_email_unique ON users (email);"),
        "got:\n{up}"
    );
}

#[test]
fn generate_migration_remove_unique_column_rollback_restores_unique_index() {
    let (_tmp, project) = fresh_project("unique-migration-remove-app");
    run_autumn(
        &project,
        &[
            "generate",
            "migration",
            "RemoveEmailFromUsers",
            "email:String:unique",
        ],
    );

    let migrations = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_remove_email_from_users")
        })
        .collect::<Vec<_>>();
    assert_eq!(migrations.len(), 1);
    let down = fs::read_to_string(migrations[0].path().join("down.sql")).unwrap();
    assert!(
        down.contains("CREATE UNIQUE INDEX idx_users_email_unique ON users (email);"),
        "rollback must restore the UNIQUE index, not just the bare column; got:\n{down}"
    );
}

#[test]
fn generate_scaffold_unique_field_adds_find_by_query_to_repository() {
    let (_tmp, project) = fresh_project("unique-scaffold-repo-app");
    run_autumn(
        &project,
        &["generate", "scaffold", "User", "email:String:unique"],
    );

    let repo = fs::read_to_string(project.join("src/repositories/user.rs")).unwrap();
    assert!(
        repo.contains("fn find_by_email(email: String) -> Vec<User>;"),
        "a unique field must get a derived find_by_ repository lookup for free; got:\n{repo}"
    );
}

#[test]
fn generate_scaffold_unique_flag_adds_find_by_query_to_repository() {
    let (_tmp, project) = fresh_project("unique-scaffold-flag-repo-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email:String",
            "--unique",
            "email",
        ],
    );

    let repo = fs::read_to_string(project.join("src/repositories/user.rs")).unwrap();
    assert!(
        repo.contains("fn find_by_email(email: String) -> Vec<User>;"),
        "got:\n{repo}"
    );
}

#[test]
fn generate_scaffold_unique_field_does_not_duplicate_explicit_query() {
    let (_tmp, project) = fresh_project("unique-scaffold-explicit-query-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email:String:unique",
            "--query",
            "find_by_email:email",
        ],
    );

    let repo = fs::read_to_string(project.join("src/repositories/user.rs")).unwrap();
    assert_eq!(
        repo.matches("fn find_by_email(").count(),
        1,
        "an explicit --query and the automatic unique-field derivation for the \
         same field must not produce two trait methods:\n{repo}"
    );
}

#[test]
fn generate_scaffold_unique_field_routes_handle_duplicate_with_inline_error() {
    let (_tmp, project) = fresh_project("unique-scaffold-routes-app");
    run_autumn(
        &project,
        &["generate", "scaffold", "User", "email:String:unique"],
    );

    let routes = fs::read_to_string(project.join("src/routes/users.rs")).unwrap();
    assert!(routes.contains("UNIQUE_CONSTRAINTS"), "got:\n{routes}");
    assert!(routes.contains("idx_users_email_unique"), "got:\n{routes}");
    assert!(
        routes.contains("autumn_web::error::unique_violation_field"),
        "got:\n{routes}"
    );
    assert!(
        routes.contains("StatusCode::UNPROCESSABLE_ENTITY"),
        "got:\n{routes}"
    );
    assert!(
        !routes.contains(
            "pub async fn create(flash: Flash, mut db: Db, body: Bytes) -> AutumnResult<Markup>"
        ),
        "a scaffold with a unique field must not use the plain create signature \
         that can only ever 500 on a duplicate; got:\n{routes}"
    );
}

#[test]
fn generate_scaffold_unique_field_create_violation_form_preserves_submitted_values() {
    // Regression guard (issue #1032 review follow-up): a duplicate
    // submission must not wipe every field the user entered — only the
    // colliding unique field needs an inline error; every other field's
    // submitted value should still be pre-filled when the form re-renders
    // with a 422.
    let (_tmp, project) = fresh_project("unique-create-preserve-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email:String:unique",
            "age:i32",
            "active:bool",
            "status:enum{draft,published}",
        ],
    );

    let routes = fs::read_to_string(project.join("src/routes/users.rs")).unwrap();
    // The plain `new_form` (blank form, no prior submission) must stay
    // untouched — no reference to `new` at all.
    let new_form_start = routes
        .find("pub async fn new_form")
        .expect("new_form handler");
    let create_start = routes.find("pub async fn create(").expect("create handler");
    let new_form_body = &routes[new_form_start..create_start];
    assert!(
        !new_form_body.contains("new."),
        "the blank new_form must not reference `new`; got:\n{new_form_body}"
    );

    // The violation-branch re-render (spliced into `create`) rebuilds the
    // changeset with the duplicate error via `Changeset::from_errors` and
    // re-renders through the same changeset-aware helpers, so every submitted
    // value is preserved (issue #1124 unifies the unique path with validation).
    let create_body = &routes[create_start..];
    assert!(
        create_body.contains("Changeset::from_errors(changeset.into_inner(), errors)"),
        "got:\n{create_body}"
    );
    // The re-render goes through the same shared `form_for` helper as the GET
    // views (issue #1135) — every submitted value is preserved because the
    // controls all read from the rebuilt changeset.
    assert!(
        create_body.contains("user_form_for(&changeset"),
        "got:\n{create_body}"
    );
    assert!(
        routes.contains(".override_field(\"status\", autumn_web::form::FieldControl::Select"),
        "got:\n{routes}"
    );
}

#[test]
fn generate_scaffold_unique_field_update_violation_form_preserves_submitted_values() {
    // Regression guard (issue #1032 review follow-up): the update path's
    // violation re-render used to always source field values from the
    // stale, re-fetched `row` (its pre-update values), silently reverting
    // every other field the user had changed in the same submission back to
    // what was stored before — even though only the unique column actually
    // collided. It must instead source from `form`, the just-decoded
    // (otherwise valid) rejected submission, the same way the create path
    // already does from `new`.
    let (_tmp, project) = fresh_project("unique-update-preserve-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email:String:unique",
            "age:i32",
            "active:bool",
            "status:enum{draft,published}",
        ],
    );

    let routes = fs::read_to_string(project.join("src/routes/users.rs")).unwrap();
    // The plain `edit_form` seeds its changeset from the persisted row.
    let edit_form_start = routes
        .find("pub async fn edit_form")
        .expect("edit_form handler");
    let update_start = routes.find("pub async fn update(").expect("update handler");
    let edit_form_body = &routes[edit_form_start..update_start];
    assert!(
        edit_form_body.contains("Changeset::new(UserForm::from(&row))"),
        "the edit_form seeds a changeset from the loaded row; got:\n{edit_form_body}"
    );

    // The violation-branch re-render (spliced into `update`) preserves the
    // *submitted* edits by rebuilding the changeset from the decoded form via
    // `Changeset::from_errors` — no stale `row` refetch (issue #1124). Scope to
    // the `update` handler only (the trailing `destroy` handler also loads its
    // row for the authorize preamble).
    let update_only = &routes[update_start..];
    let destroy_off = update_only
        .find("pub async fn destroy")
        .expect("destroy handler after update");
    let update_body = &update_only[..destroy_off];
    assert!(
        update_body.contains("Changeset::from_errors(changeset.into_inner(), errors)"),
        "got:\n{update_body}"
    );
    // Same shared `form_for` helper as the GET views (issue #1135): the
    // rebuilt changeset carries the submitted values into every control.
    assert!(
        update_body.contains("user_form_for(&changeset"),
        "got:\n{update_body}"
    );
    // Issue #1830: the mutating handlers now record-authorize the actor, which
    // loads the target row ONCE up front (`.first(&mut *db)` → `authorize`). That
    // load feeds the policy check, NOT the 422 re-render — the violation branch
    // still rebuilds the changeset from the submitted `form`, never a refetched
    // row. So the only row load in `update` is the authorize preamble.
    assert_eq!(
        update_body.matches(".first(&mut *db)").count(),
        1,
        "the update violation path must not re-fetch the row for its re-render; \
         the only load is the authorize preamble; got:\n{update_body}"
    );
    assert!(
        update_body.contains("authorize::<User>(&state, &session, \"update\", &current)"),
        "the single row load must be the authorize preamble; got:\n{update_body}"
    );
}

#[test]
fn generate_scaffold_unique_field_emits_duplicate_rejection_smoke_test() {
    let (_tmp, project) = fresh_project("unique-scaffold-smoke-app");
    run_autumn(
        &project,
        &["generate", "scaffold", "User", "email:String:unique"],
    );

    let test_file = fs::read_to_string(project.join("tests/user.rs")).unwrap();
    assert!(
        test_file.contains("async fn users_rejects_duplicate_email()"),
        "got:\n{test_file}"
    );
    assert!(
        test_file.contains("idx_users_email_unique"),
        "got:\n{test_file}"
    );
    assert!(
        test_file.contains("autumn_web::error::unique_violation_field"),
        "got:\n{test_file}"
    );
    // The DB-level check: a real duplicate INSERT must violate the UNIQUE
    // index and be classified by field.
    assert!(
        test_file.contains("must violate the UNIQUE index"),
        "got:\n{test_file}"
    );
    // The request-boundary check: a stand-in POST handler proves the full
    // 422-with-inline-error path (issue #1032's success metric).
    assert!(
        test_file.contains(".assert_status(422)") && test_file.contains(".assert_status(200)"),
        "got:\n{test_file}"
    );
    // Regression guard: the DB-level check above already inserts the target
    // value once, so the table must be truncated again before the first
    // client POST — otherwise that "must succeed with 200" request collides
    // with the row the DB-level check left behind and the smoke test fails
    // under `cargo test -- --ignored`.
    let before_200 = test_file
        .split(".assert_status(200)")
        .next()
        .expect("assert_status(200) must appear in the generated test");
    assert!(
        before_200
            .matches("TRUNCATE users RESTART IDENTITY")
            .count()
            >= 2,
        "the table must be truncated again before the request-boundary POSTs; got:\n{test_file}"
    );
}

#[test]
fn generate_scaffold_unique_enum_field_smoke_test_inserts_a_valid_variant() {
    // Regression guard: the duplicate-insert smoke test's first INSERT must
    // actually succeed so the *second* insert is the one that trips the
    // UNIQUE index. A generic `'dup_value'` literal is not a valid enum
    // variant and would fail the first insert on the enum's CHECK
    // constraint instead, so the target field's sample value must be one of
    // its declared variants.
    let (_tmp, project) = fresh_project("unique-enum-smoke-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "status:enum{draft,published}:unique",
        ],
    );

    let test_file = fs::read_to_string(project.join("tests/post.rs")).unwrap();
    assert!(
        test_file.contains("async fn posts_rejects_duplicate_status()"),
        "got:\n{test_file}"
    );
    assert!(
        !test_file.contains("'dup_value'"),
        "a unique enum field's smoke test must not insert an invalid variant \
         literal; got:\n{test_file}"
    );
    assert!(
        test_file.contains("(status) VALUES ('draft')"),
        "the target enum field must be seeded with its first declared \
         variant; got:\n{test_file}"
    );
}

#[test]
fn generate_scaffold_unique_reference_field_smoke_test_uses_seeded_fk_value() {
    // Regression guard (issue #1032 review follow-up): `unique_sample_literal`
    // used to lump `references` in with plain integers and emit an arbitrary
    // `424242` FK value. `render_reference_stub_tables_sql` seeds real rows
    // (ids 1 and 2) into the stub target table, so that arbitrary id fails
    // the FK constraint before the insert ever reaches the UNIQUE index this
    // test exists to exercise.
    let (_tmp, project) = fresh_project("unique-reference-smoke-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Membership",
            "profile:references:unique",
        ],
    );

    let test_file = fs::read_to_string(project.join("tests/membership.rs")).unwrap();
    assert!(
        test_file.contains("async fn memberships_rejects_duplicate_profile_id()"),
        "got:\n{test_file}"
    );
    assert!(
        !test_file.contains("424242"),
        "a unique `references` field's smoke test must not insert an \
         arbitrary FK id that doesn't exist in the seeded stub table; \
         got:\n{test_file}"
    );
    assert!(
        test_file.contains("(profile_id) VALUES (1)"),
        "the target references field must be seeded with the stub table's \
         real row id; got:\n{test_file}"
    );
}

#[test]
fn generate_scaffold_multiple_unique_fields_smoke_test_isolates_the_target_field() {
    // Regression guard (issue #1032 review follow-up): with more than one
    // `unique` field, the duplicate-insert SQL used to fill every *other*
    // required column (including other unique ones) with the same fixed
    // literal on both inserts. Testing `username`'s duplicate would then
    // *also* duplicate `email`, so Postgres could report `email`'s
    // constraint first and the `assert_eq!(field, "username")` assertion
    // would fail even though `username`'s constraint genuinely exists. The
    // second (duplicate) insert must vary every *other* unique column's
    // value so only the field under test actually collides.
    let (_tmp, project) = fresh_project("unique-multi-field-smoke-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email:String:unique",
            "username:String:unique",
        ],
    );

    let test_file = fs::read_to_string(project.join("tests/user.rs")).unwrap();
    let username_test_start = test_file
        .find("async fn users_rejects_duplicate_username()")
        .expect("users_rejects_duplicate_username test should exist");
    let email_test_start = test_file
        .find("async fn users_rejects_duplicate_email()")
        .expect("users_rejects_duplicate_email test should exist");
    // The two generated tests can appear in either order; slice from
    // whichever comes first to the end so this doesn't depend on it.
    let (test_body, other_field_name) = if username_test_start < email_test_start {
        (&test_file[username_test_start..], "email")
    } else {
        (&test_file[email_test_start..], "username")
    };
    // Within a single duplicate-rejection test, the two `diesel::sql_query`
    // calls (first insert, then the duplicate) must use different literals
    // for the *other* unique field so it doesn't also collide.
    let insert_calls: Vec<&str> = test_body
        .lines()
        .filter(|l| l.contains("diesel::sql_query(") && l.contains(other_field_name))
        .take(2)
        .collect();
    assert_eq!(
        insert_calls.len(),
        2,
        "expected two inserts referencing the non-target unique field \
         {other_field_name}; got:\n{test_body}"
    );
    assert_ne!(
        insert_calls[0], insert_calls[1],
        "the first and duplicate inserts must give the non-target unique \
         field {other_field_name} different values, or it would collide \
         with itself the same way the target field is meant to; got:\n{test_body}"
    );
}

#[test]
fn generate_scaffold_multiple_unique_fields_request_boundary_check_isolates_the_target_field() {
    // Regression guard (issue #1032 review follow-up): the DB-level check's
    // duplicate insert was fixed to vary non-target unique columns (see
    // generate_scaffold_multiple_unique_fields_smoke_test_isolates_the_target_field),
    // but the request-boundary stand-in handler is a single compiled
    // function invoked via two separate HTTP calls with no way to tell
    // "first call" from "second call" apart -- it kept reusing one literal
    // insert for both, so a non-target unique column would still collide
    // with itself. It must instead pick between the two insert variants at
    // runtime based on whether the table is still empty.
    let (_tmp, project) = fresh_project("unique-multi-field-boundary-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email:String:unique",
            "username:String:unique",
        ],
    );

    let test_file = fs::read_to_string(project.join("tests/user.rs")).unwrap();
    for (field, other_field) in [("email", "username"), ("username", "email")] {
        let test_start = test_file
            .find(&format!("async fn users_rejects_duplicate_{field}()"))
            .unwrap_or_else(|| panic!("users_rejects_duplicate_{field} test should exist"));
        let next_test_start = test_file[test_start + 1..]
            .find("async fn users_rejects_duplicate_")
            .map_or(test_file.len(), |i| test_start + 1 + i);
        let test_body = &test_file[test_start..next_test_start];

        assert!(
            test_body
                .contains("let existing: i64 = users::table.count().get_result(&mut *db).await?;"),
            "the request-boundary handler must branch on the table's row \
             count to tell the two calls apart; got:\n{test_body}"
        );
        let branch_line = test_body
            .lines()
            .find(|l| l.contains("let insert_sql = if existing == 0"))
            .unwrap_or_else(|| panic!("expected an insert_sql branch; got:\n{test_body}"));
        // Pull out just the quoted SQL literal from each branch (the second
        // `"..."`-delimited token — the first is the `if existing == 0`
        // condition itself, which has no quotes) so the comparison is
        // against the actual INSERT statement, not incidental surrounding
        // syntax that always differs between an if- and else-arm.
        let quoted: Vec<&str> = branch_line.split('"').collect();
        assert!(
            quoted.len() >= 4,
            "expected two quoted SQL literals in the branch; got: {branch_line}"
        );
        let (if_sql, else_sql) = (quoted[1], quoted[3]);
        assert_ne!(
            if_sql, else_sql,
            "the two insert_sql branches must give the non-target unique \
             field {other_field} different values, or the second HTTP call \
             would collide on it too; got: {branch_line}"
        );
    }
}

#[test]
fn generate_scaffold_long_unique_field_name_agrees_across_migration_and_routes() {
    // Regression guard (issue #1032 review follow-up): `idx_<table>_<field>_
    // unique` is unbounded, and PostgreSQL silently truncates identifiers
    // past its 63-byte limit. If the migration's `CREATE UNIQUE INDEX` and
    // the generated routes' `UNIQUE_CONSTRAINTS` computed that name
    // independently, a long enough table/field combination would make them
    // disagree with what Postgres actually names the index, and a real
    // duplicate submission would fall through to a 500 instead of the
    // intended 422. Both must resolve to the identical (possibly
    // truncated+hashed) name.
    let (_tmp, project) = fresh_project("unique-longname-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "AVeryLongModelNameForTruncationTesting",
            "an_equally_long_field_name_for_good_measure:String:unique",
        ],
    );

    let migration = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .find(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_create_a_very_long_model_name_for_truncation_testings")
        })
        .expect("create migration for the long-named model should exist");
    let up = fs::read_to_string(migration.path().join("up.sql")).unwrap();
    let index_line = up
        .lines()
        .find(|l| l.starts_with("CREATE UNIQUE INDEX"))
        .unwrap_or_else(|| panic!("expected a CREATE UNIQUE INDEX line; got:\n{up}"));
    let index_name = index_line
        .strip_prefix("CREATE UNIQUE INDEX ")
        .and_then(|rest| rest.split(' ').next())
        .expect("index name token");
    assert!(
        index_name.len() <= 63,
        "index name must fit Postgres's identifier limit, got {} bytes: {index_name}",
        index_name.len()
    );

    let routes = fs::read_to_string(
        project.join("src/routes/a_very_long_model_name_for_truncation_testings.rs"),
    )
    .unwrap();
    assert!(
        routes.contains(&format!("\"{index_name}\"")),
        "the generated routes' UNIQUE_CONSTRAINTS must reference the exact \
         same (possibly truncated) index name as the migration; index_name=\
         {index_name}, got:\n{routes}"
    );
}

#[test]
fn generate_scaffold_unique_field_avoids_name_collision_with_coincidentally_named_index() {
    // Regression guard (issue #1032 review follow-up): a plain index always
    // names itself after its own column (`idx_<table>_<name>`, no `_unique`
    // suffix). A field literally named `<other_field>_unique` that also
    // gets a plain index therefore claims the exact name
    // `<other_field>:unique` would otherwise compute for itself
    // (`idx_<table>_<other_field>_unique`), even though the two fields are
    // otherwise unrelated. Without disambiguation the generated migration
    // fails with "relation already exists" before the table is usable.
    let (_tmp, project) = fresh_project("unique-collision-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email:String:unique",
            "email_unique:String",
            "--index",
            "email_unique",
        ],
    );

    let migration = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .find(|e| e.file_name().to_string_lossy().ends_with("_create_users"))
        .expect("create_users migration should exist");
    let up = fs::read_to_string(migration.path().join("up.sql")).unwrap();
    assert!(
        up.contains("CREATE INDEX idx_users_email_unique ON users (email_unique);"),
        "got:\n{up}"
    );
    assert!(
        !up.contains("CREATE UNIQUE INDEX idx_users_email_unique ON users (email);"),
        "the unique index must not collide with the plain index's exact \
         name; got:\n{up}"
    );

    let disambiguated_line = up
        .lines()
        .find(|l| l.starts_with("CREATE UNIQUE INDEX") && l.contains(" (email);"))
        .unwrap_or_else(|| panic!("expected a disambiguated unique index for email; got:\n{up}"));
    let index_name = disambiguated_line
        .strip_prefix("CREATE UNIQUE INDEX ")
        .and_then(|rest| rest.split(' ').next())
        .expect("index name token");
    assert_ne!(index_name, "idx_users_email_unique");

    // The generated routes' UNIQUE_CONSTRAINTS must reference the exact
    // same disambiguated name, or a real duplicate submission would fall
    // through to a 500 instead of the intended 422.
    let routes = fs::read_to_string(project.join("src/routes/users.rs")).unwrap();
    assert!(
        routes.contains(&format!("\"{index_name}\"")),
        "got:\n{routes}"
    );
}

#[test]
fn generate_migration_add_unique_field_avoids_collision_with_earlier_migrations_column() {
    // Regression guard (issue #1032 review follow-up): the create-table
    // collision fix above only sees the fields in a single `generate`
    // invocation. This reproduces the cross-migration case Codex flagged: a
    // table already has a plain-indexed `email_unique` column from an
    // earlier `generate scaffold`, and a *later*, separate `generate
    // migration AddEmailToUsers email:String:unique` call must still avoid
    // colliding with it -- `src/schema.rs` (kept in sync by the scaffold
    // generator) is what lets the migration generator see across that gap.
    let (_tmp, project) = fresh_project("unique-cross-migration-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email_unique:String",
            "--index",
            "email_unique",
        ],
    );
    run_autumn(
        &project,
        &[
            "generate",
            "migration",
            "AddEmailToUsers",
            "email:String:unique",
        ],
    );

    let migration = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .find(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_add_email_to_users")
        })
        .expect("add_email_to_users migration should exist");
    let up = fs::read_to_string(migration.path().join("up.sql")).unwrap();
    assert!(
        !up.contains("CREATE UNIQUE INDEX idx_users_email_unique ON users (email);"),
        "must not collide with the pre-existing email_unique column's plain \
         index (created by the earlier `generate scaffold` call); got:\n{up}"
    );
    assert!(
        up.contains("CREATE UNIQUE INDEX idx_users_email_unique_"),
        "the unique index must still exist, under a disambiguated name; \
         got:\n{up}"
    );
}

#[test]
fn generate_scaffold_unique_attachment_field_is_skipped_in_smoke_test() {
    // A unique constraint on an always-nullable attachment blob is a
    // degenerate case (Postgres allows unlimited NULLs under a unique
    // index) — no meaningful violation to provoke, so no smoke test should
    // be emitted for it.
    let (_tmp, project) = fresh_project("unique-attachment-smoke-app");
    run_autumn(
        &project,
        &["generate", "scaffold", "Document", "file:Attachment:unique"],
    );

    let test_file = fs::read_to_string(project.join("tests/document.rs")).unwrap();
    assert!(
        !test_file.contains("rejects_duplicate_file"),
        "got:\n{test_file}"
    );
}

/// PR #1867 review (Finding 2): destroying the last attachment *model* must
/// not strip `autumn-web/multipart` or `autumn-web/storage` from Cargo.toml
/// when a hand-written route still uses those APIs — otherwise the project
/// stops compiling. The `Revert::CargoAutumnWebFeature` bookkeeping alone
/// would strip them (its `owner_dir` sibling check only sees the scaffold's
/// own `src/models`), so `autumn_web_feature_markers` must retain them via a
/// whole-project marker scan.
#[test]
fn destroy_attachment_scaffold_keeps_features_used_by_handwritten_route() {
    let (_tmp, project) = fresh_project("destroy-attachment-features-app");

    run_autumn(
        &project,
        &["generate", "scaffold", "Document", "file:Attachment"],
    );

    let cargo_before = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(
        cargo_before.contains("\"multipart\"") && cargo_before.contains("\"storage\""),
        "attachment scaffold must enable multipart+storage, got:\n{cargo_before}"
    );

    // A hand-written route that uses both the multipart extractor and the
    // blob store directly — unrelated to the scaffold's generated files. It
    // imports through `use autumn_web::prelude::*;` and names `Multipart`
    // UNQUALIFIED (the prelude re-exports it), the shape the earlier
    // `extract::Multipart` marker would have missed — so destroy would have
    // wrongly stripped `multipart`. The blob store stays a
    // `autumn_web::storage::` path since the prelude re-exports no storage type.
    fs::write(
        project.join("src/routes/manual.rs"),
        "use autumn_web::prelude::*;\n\n\
         pub async fn manual_upload(\n    \
         mut multipart: Multipart,\n    \
         store: autumn_web::storage::BlobStoreState,\n\
         ) {\n    let _ = (&mut multipart, &store);\n}\n",
    )
    .unwrap();

    run_autumn(
        &project,
        &["destroy", "scaffold", "Document", "file:Attachment"],
    );

    let cargo_after = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(
        cargo_after.contains("\"multipart\""),
        "multipart must be retained while a hand-written route uses the Multipart extractor, got:\n{cargo_after}"
    );
    assert!(
        cargo_after.contains("\"storage\""),
        "storage must be retained while a hand-written route references autumn_web::storage::, got:\n{cargo_after}"
    );
}

#[test]
fn generate_scaffold_without_unique_field_omits_unique_constraints() {
    // A scaffold with NO unique fields emits no UNIQUE_CONSTRAINTS const, but
    // (issue #1124) every scaffold now uses the changeset round-trip: create
    // returns a Response and carries the CSRF params for the 422 re-render.
    let (_tmp, project) = fresh_project("no-unique-scaffold-routes-app");
    run_autumn(&project, &["generate", "scaffold", "Post", "title:String"]);

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    assert!(!routes.contains("UNIQUE_CONSTRAINTS"), "got:\n{routes}");
    // Issue #1830: no-owner scaffolds record-authorize their handlers too, so
    // `State`/`Session` are threaded in before the last `body: Bytes` extractor.
    assert!(
        routes.contains(
            "pub async fn create(flash: Flash, csrf: Option<CsrfToken>, csrf_field: Option<CsrfFormField>, submit_token: Option<SubmitToken>, submit_field: Option<SubmitFormField>, mut db: Db, \n    autumn_web::extract::State(state): autumn_web::extract::State<autumn_web::AppState>,\n    session: autumn_web::session::Session,\n    body: Bytes) -> AutumnResult<autumn_web::reexports::axum::response::Response>"
        ),
        "got:\n{routes}"
    );
    assert!(routes.contains("form.into_changeset()"), "got:\n{routes}");
}

#[test]
fn generate_model_help_documents_unique_field() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "model", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("unique"), "got:\n{stdout}");
    assert!(stdout.contains("--unique"), "got:\n{stdout}");
}

#[test]
fn generate_scaffold_help_documents_unique_field() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "scaffold", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("unique"), "got:\n{stdout}");
    assert!(stdout.contains("--unique"), "got:\n{stdout}");
}

/// Issue #1340: the `{encrypted}` modifier must be discoverable from the help
/// of the two subcommands that actually accept it. Documenting it only on the
/// parent `autumn generate --help` is not enough — clap builds each
/// subcommand's long help from its own doc block, and `model`/`scaffold` are
/// what a user checking "how do I declare this field?" actually runs.
#[test]
fn generate_model_help_documents_the_encrypted_modifier() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "model", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("{encrypted}"), "got:\n{stdout}");
    assert!(
        stdout.contains("{encrypted:deterministic}"),
        "got:\n{stdout}"
    );
    // The one manual step the generator cannot do for the user.
    assert!(stdout.contains("autumn credentials edit"), "got:\n{stdout}");
}

#[test]
fn generate_scaffold_help_documents_the_encrypted_modifier() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "scaffold", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("{encrypted}"), "got:\n{stdout}");
    assert!(
        stdout.contains("{encrypted:deterministic}"),
        "got:\n{stdout}"
    );
    assert!(stdout.contains("autumn credentials edit"), "got:\n{stdout}");
}

/// The advertised examples must survive a copy-paste into bash/zsh: an
/// unquoted `{…}` is brace-expanded by the shell before `autumn` ever sees it,
/// so every `String{encrypted…}` token shown in help must be single-quoted.
///
/// Checked positionally rather than per-line, so it holds whichever way clap
/// wraps the block (`verbatim_doc_comment` or reflowed) and for examples given
/// inline in a paragraph as well as in an `Examples:` list.
#[test]
fn generate_help_encrypted_examples_are_shell_quoted() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    for args in [
        vec!["generate", "--help"],
        vec!["generate", "model", "--help"],
        vec!["generate", "scaffold", "--help"],
    ] {
        let label = args.join(" ");
        let output = Command::new(autumn_bin)
            .args(&args)
            .current_dir(tmp.path())
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut checked = 0usize;
        for (idx, _) in stdout.match_indices("String{encrypted") {
            // Walk back to the start of the `name:String{encrypted…}` token.
            let token_start = stdout[..idx]
                .rfind(|c: char| c.is_whitespace())
                .map_or(0, |i| i + 1);
            // Only the runnable examples need quoting — a bare mention of the
            // syntax in prose is wrapped in markdown backticks instead.
            let is_example = stdout[..token_start].ends_with("autumn generate ")
                || stdout[..token_start]
                    .rsplit('\n')
                    .next()
                    .is_some_and(|line| line.contains("autumn generate "));
            if !is_example {
                continue;
            }
            checked += 1;
            assert!(
                stdout[token_start..].starts_with('\''),
                "`{label}` shows an unquoted example — bash/zsh would \
                 brace-expand it before `autumn` sees it: {}",
                &stdout[token_start
                    ..stdout[token_start..]
                        .find(char::is_whitespace)
                        .map_or(stdout.len(), |i| token_start + i)]
            );
        }
        // `generate --help` and both subcommands each advertise at least one.
        assert!(checked > 0, "`{label}` shows no runnable encrypted example");
    }
}

#[test]
fn generate_scaffold_help_documents_unique_is_html_only() {
    // Regression guard (issue #1032 review follow-up): `unique`'s 422
    // inline-error handling is only wired into the HTML routes generator —
    // an `--api` scaffold's JSON CRUD routes are auto-generated by
    // `#[repository]` and a duplicate create/update there still falls
    // through to a 500. This is a deliberately deferred slice (also
    // recorded in CHANGELOG.md), but it must say so in `--help` too, or a
    // `--api` user has no way to discover the gap before hitting it.
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "scaffold", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("HTML-only"), "got:\n{stdout}");
    assert!(stdout.contains("--api"), "got:\n{stdout}");
    assert!(stdout.contains("#[repository]"), "got:\n{stdout}");
}

#[test]
fn generate_migration_help_documents_unique_field() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "migration", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("unique"), "got:\n{stdout}");
    assert!(stdout.contains("--unique"), "got:\n{stdout}");
}

#[test]
fn generate_scaffold_with_unique_dry_run_lists_migration_file() {
    let (_tmp, project) = fresh_project("unique-dryrun-app");
    let (stdout, _stderr) = run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email:String:unique",
            "--dry-run",
        ],
    );
    assert!(stdout.contains("Dry run"));
    assert!(stdout.contains("src/models/user.rs"));
    // The migration file (which will contain the UNIQUE index — see
    // generate_model_unique_field_emits_unique_index for the SQL-level
    // assertion) shows up in the dry-run's file plan like every other
    // generated file.
    assert!(
        stdout.contains("_create_users") && stdout.contains("up.sql"),
        "the migration file plan must be listed under --dry-run; got:\n{stdout}"
    );
    assert!(!project.join("src/models/user.rs").exists());
}

/// Slow end-to-end check: scaffold a `unique` field and `cargo check` the
/// result. The generated `create`/`update` handlers (issue #1032) use a
/// hand-templated `maud::html!` re-render on a constraint violation — this
/// is the one test that actually compiles that generated code, catching any
/// template/escaping mistake a string-content assertion alone would miss.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_unique_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("unique-scaffold-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &["generate", "scaffold", "User", "email:String:unique"],
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated unique scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Slow end-to-end check (issue #1260): scaffold a `slug` field and `cargo
/// check` the result. The rekeyed `show`/`edit`/`update`/`delete` handlers
/// (`Path<String>` instead of `Path<i64>`, `.filter(...)` instead of
/// `.find(*id)`, the create-time collision-suffix loop) are hand-templated
/// string codegen with no compiler feedback at generation time — this is the
/// one test that actually compiles that generated code, catching any
/// template/escaping/borrow mistake a string-content assertion alone would
/// miss.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
// `"slug:slug{from:title}"` is a literal DSL token passed to the CLI, not a
// format string — the `{…}` is the scaffold's own constraint-modifier syntax.
#[allow(clippy::literal_string_with_formatting_args)]
fn generated_slug_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("slug-scaffold-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            r"slug:slug{from:title}",
        ],
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated slug scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// `--live` (SSE-backed repository writes) routes the insert/update through
/// `repo.save`/`repo.update` instead of a bare `diesel::insert_into` — a
/// different error-propagation path into `unique_violation_field` (see its
/// doc comment on recovering the diesel error either way). This can't be a
/// `cargo check` test like [`generated_unique_scaffold_cargo_checks`]:
/// `--live` scaffolds fail to compile independent of `unique` (a pre-existing
/// `<Model>DraftExt` import gap in `broadcasts = true` repositories,
/// reproducible with zero unique fields — out of scope for issue #1032), so
/// this only asserts the unique-aware codegen paths are wired correctly.
#[test]
fn generate_scaffold_unique_live_field_wires_repository_save_and_db_refetch() {
    let (_tmp, project) = fresh_project("unique-live-scaffold-app");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "User",
            "email:String:unique",
            "--live",
        ],
    );

    let routes = fs::read_to_string(project.join("src/routes/users.rs")).unwrap();
    assert!(
        routes.contains("repo.save(&new).await?;"),
        "the create failure branch must still route inserts through the \
         repository on --live, not a bare diesel call; got:\n{routes}"
    );
    assert!(
        routes.contains("repo.update(*id, &update_changes).await?;"),
        "got:\n{routes}"
    );
    // Regression guard (issue #1032 review follow-up): `update`'s signature
    // must NOT carry a second `Db` extractor alongside `repo` — holding both a
    // `Db` and `repo`'s own checkout at once self-deadlocks a pool sized for
    // one connection per request. Issue #1124 drops the unique-violation
    // row-refetch entirely (the 422 re-renders the submitted changeset), so the
    // live update path no longer needs any refetch connection at all.
    let update_start = routes.find("pub async fn update(").expect("update handler");
    let update_body = &routes[update_start..];
    assert!(
        !update_body.contains("mut db:"),
        "the live update handler must not also take a `Db` extractor; \
         got:\n{update_body}"
    );
    assert!(
        update_body.contains("Changeset::from_errors(changeset.into_inner(), errors)"),
        "the update violation path re-renders the submitted changeset; got:\n{update_body}"
    );
    assert!(routes.contains("repo: PgUserRepository"), "got:\n{routes}");
    assert!(
        routes.contains("autumn_web::error::unique_violation_field"),
        "got:\n{routes}"
    );
}

// ── autumn generate channel integration tests ─────────────────────────────────

#[test]
fn generate_channel_creates_all_expected_files() {
    let (_tmp, project) = fresh_project("channel-app");
    let (stdout, _stderr) = run_autumn(&project, &["generate", "channel", "Chat"]);
    assert!(
        stdout.contains("chat.rs") || stdout.contains("Created"),
        "output should mention created files: {stdout}"
    );

    assert!(project.join("src/channels/chat.rs").is_file());
    let channel = fs::read_to_string(project.join("src/channels/chat.rs")).unwrap();
    assert!(channel.contains(r#"#[get("/chat")]"#));
    assert!(channel.contains(r#"#[get("/chat/events")]"#));
    assert!(channel.contains(r#"#[post("/chat/messages")]"#));
    assert!(channel.contains(r#"sse-connect="/chat/events""#));
    assert!(channel.contains(r#"sse-swap="message""#));
    assert!(channel.contains("autumn_web::sse::stream"));

    assert!(project.join("src/channels/mod.rs").is_file());
    let mod_rs = fs::read_to_string(project.join("src/channels/mod.rs")).unwrap();
    assert!(mod_rs.contains("pub mod chat;"));

    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(main.contains("mod channels;"));
    assert!(main.contains("channels::chat::chat_page"));
    assert!(main.contains("channels::chat::chat_events"));
    assert!(main.contains("channels::chat::chat_publish"));

    assert!(project.join("tests/chat_channel.rs").is_file());
    let test_src = fs::read_to_string(project.join("tests/chat_channel.rs")).unwrap();
    assert!(test_src.contains("TestApp"));
    assert!(test_src.contains(".subscribe("));
    assert!(!test_src.contains("#[ignore"));

    let cargo = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(
        cargo.contains("\"ws\""),
        "Cargo.toml must enable the ws feature: {cargo}"
    );
    assert!(cargo.contains("maud"));
    assert!(cargo.contains("serde"));
}

#[test]
fn generate_channel_ws_emits_ws_handler() {
    let (_tmp, project) = fresh_project("channel-ws-app");
    run_autumn(&project, &["generate", "channel", "Chat", "--ws"]);

    let channel = fs::read_to_string(project.join("src/channels/chat.rs")).unwrap();
    assert!(channel.contains(r#"#[ws("/chat/ws")]"#));
    assert!(channel.contains("WithShutdown"));
    assert!(!channel.contains("sse-connect"));

    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(main.contains("channels::chat::chat_ws"));
    assert!(main.contains("channels::chat::chat_publish"));

    let cargo = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(cargo.contains("\"ws\""));
}

/// Regression test: `autumn generate channel Chat --ws --force` after a
/// plain SSE run must not leave `main.rs` referencing `chat_page`/
/// `chat_events`, which `src/channels/chat.rs` no longer defines once
/// `--ws` overwrites it.
#[test]
fn generate_channel_force_transport_switch_does_not_strand_stale_routes() {
    let (_tmp, project) = fresh_project("channel-switch-app");
    run_autumn(&project, &["generate", "channel", "Chat"]);
    run_autumn(
        &project,
        &["generate", "channel", "Chat", "--ws", "--force"],
    );

    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(
        !main.contains("chat_page"),
        "stale SSE page route must be removed: {main}"
    );
    assert!(
        !main.contains("chat_events"),
        "stale SSE events route must be removed: {main}"
    );
    assert!(main.contains("channels::chat::chat_ws"));
    assert!(main.contains("channels::chat::chat_publish"));

    let channel = fs::read_to_string(project.join("src/channels/chat.rs")).unwrap();
    assert!(channel.contains(r#"#[ws("/chat/ws")]"#));
}

#[test]
fn generate_channel_dry_run_writes_nothing() {
    let (_tmp, project) = fresh_project("channel-dry-app");
    let (stdout, _) = run_autumn(&project, &["generate", "channel", "Chat", "--dry-run"]);
    assert!(
        stdout.contains("Dry run"),
        "dry run must print Dry run header: {stdout}"
    );
    assert!(!project.join("src/channels/chat.rs").exists());
    assert!(!project.join("tests/chat_channel.rs").exists());
}

#[test]
fn generate_channel_collision_without_force_fails() {
    let (_tmp, project) = fresh_project("channel-collide-app");
    run_autumn(&project, &["generate", "channel", "Chat"]);
    let (_, stderr, code) = run_autumn_failing(&project, &["generate", "channel", "Chat"]);
    assert_eq!(code, Some(1), "second run without --force must exit 1");
    assert!(
        stderr.contains("would overwrite") || stderr.contains("chat.rs"),
        "must report collision: {stderr}"
    );
}

#[test]
fn generate_channel_force_overwrites_existing() {
    let (_tmp, project) = fresh_project("channel-force-app");
    run_autumn(&project, &["generate", "channel", "Chat"]);
    let path = project.join("src/channels/chat.rs");
    fs::write(&path, "// corrupted").unwrap();
    run_autumn(&project, &["generate", "channel", "Chat", "--force"]);
    let content = fs::read_to_string(&path).unwrap();
    assert!(
        content.contains("TOPIC"),
        "--force must regenerate the channel file"
    );
}

#[test]
fn generate_channel_sse_ws_conflict_fails() {
    let (_tmp, project) = fresh_project("channel-conflict-app");
    let (_, stderr, code) =
        run_autumn_failing(&project, &["generate", "channel", "Chat", "--sse", "--ws"]);
    assert_ne!(code, Some(0), "--sse and --ws together must fail");
    assert!(
        stderr.contains("cannot be used with") || stderr.contains("conflict"),
        "clap should report the conflicting flags: {stderr}"
    );
}

/// Slow end-to-end check: scaffold a fresh project, run `autumn generate
/// channel` (default SSE transport), and `cargo check --tests` the result
/// against the local `autumn-web` crate. Verifies the generator adds every
/// dep its emitted code needs and that the generated application and smoke
/// test actually type-check.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_channel_cargo_checks() {
    let (_tmp, project) = fresh_project("channel-build");
    patch_generated_cargo_toml(&project);

    run_autumn(&project, &["generate", "channel", "Chat"]);

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated channel (SSE) failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Same as [`generated_channel_cargo_checks`] but for the `--ws` transport.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_channel_ws_cargo_checks() {
    let (_tmp, project) = fresh_project("channel-ws-build");
    patch_generated_cargo_toml(&project);

    run_autumn(&project, &["generate", "channel", "Chat", "--ws"]);

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated channel (--ws) failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Slow end-to-end check: scaffold a fresh project, run `autumn generate
/// channel`, and actually run the generated smoke test with `cargo test`.
/// This is the acceptance-criterion proof that the smoke test does not just
/// compile but passes on first run with no manual edits — it publishes a
/// message and asserts a live subscriber receives it.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: builds and runs a fresh project's test suite — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_channel_smoke_test_passes() {
    let (_tmp, project) = fresh_project("channel-smoke-build");
    patch_generated_cargo_toml(&project);

    run_autumn(&project, &["generate", "channel", "Chat"]);

    let test_run = Command::new("cargo")
        .args(["test", "--test", "chat_channel"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        test_run.status.success(),
        "generated chat_channel smoke test failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&test_run.stdout),
        String::from_utf8_lossy(&test_run.stderr),
    );
    assert!(
        String::from_utf8_lossy(&test_run.stdout).contains("test result: ok"),
        "expected the smoke test to report success"
    );
}

// ── autumn generate webhook integration tests (issue #1366) ───────────────────

#[test]
fn generate_webhook_creates_all_expected_files() {
    let (_tmp, project) = fresh_project("webhook-app");
    let (stdout, stderr) = run_autumn(&project, &["generate", "webhook", "stripe", "Payments"]);
    assert!(
        stdout.contains("Created") && stdout.contains("payments.rs"),
        "output should list the created handler: {stdout}"
    );

    assert!(project.join("src/webhooks/payments.rs").is_file());
    assert!(project.join("src/webhooks/mod.rs").is_file());

    let handler = fs::read_to_string(project.join("src/webhooks/payments.rs")).unwrap();
    assert!(
        handler.contains("#[post(\"/webhooks/stripe\")]"),
        "handler must own the provider route path:\n{handler}"
    );
    assert!(
        handler.contains("webhook: SignedWebhook"),
        "handler must take the shipped extractor:\n{handler}"
    );
    assert!(
        handler.contains("webhook.event_type()")
            && handler.contains("\"payment_intent.succeeded\""),
        "handler must dispatch on the event type:\n{handler}"
    );

    let main_rs = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(main_rs.contains("mod webhooks;"), "got:\n{main_rs}");
    assert!(
        main_rs.contains("webhooks::payments::payments_webhook"),
        "the route must be registered in routes![...]:\n{main_rs}"
    );

    let autumn_toml = fs::read_to_string(project.join("autumn.toml")).unwrap();
    assert!(
        autumn_toml.contains("[[security.webhooks.endpoints]]"),
        "got:\n{autumn_toml}"
    );
    assert!(
        autumn_toml.contains("secret_env = \"STRIPE_WEBHOOK_SECRET\""),
        "the endpoint must reference a secret env var, never an inline secret:\n{autumn_toml}"
    );
    assert!(
        autumn_toml.contains("replay_protection = true"),
        "replay protection must be on by default:\n{autumn_toml}"
    );
    // No CSRF/CAPTCHA exemption copies: the framework derives those from the
    // endpoint block on every boot, so a literal copy would only go stale.
    assert!(
        !autumn_toml.contains("exempt_paths"),
        "path exemptions are derived from the endpoint block, not copied:\n{autumn_toml}"
    );

    // The printed next steps name the secret env var, the dashboard target, and
    // how to fire a test delivery — on stdout, not as warnings.
    assert!(
        stdout.contains("Next steps:") && stdout.contains("STRIPE_WEBHOOK_SECRET"),
        "the secret env var must be part of the printed next steps:\n{stdout}"
    );
    assert!(
        stdout.contains("autumn webhook sim stripe"),
        "the next steps should show how to fire a signed test delivery:\n{stdout}"
    );
    assert!(
        !stderr.contains("Warning:"),
        "a clean run must not print warnings:\n{stderr}"
    );
}

#[test]
fn generate_webhook_supports_every_provider_preset() {
    let (_tmp, project) = fresh_project("webhook-presets");
    for (provider, name, snake) in [
        ("stripe", "Payments", "payments"),
        ("github", "Repo", "repo"),
        ("slack", "Events", "events"),
        ("generic", "Partner", "partner"),
    ] {
        run_autumn(&project, &["generate", "webhook", provider, name]);
        let handler = fs::read_to_string(project.join(format!("src/webhooks/{snake}.rs"))).unwrap();
        assert!(
            handler.contains(&format!("#[post(\"/webhooks/{provider}\")]")),
            "{provider}: wrong route path:\n{handler}"
        );
    }
    let autumn_toml = fs::read_to_string(project.join("autumn.toml")).unwrap();
    assert_eq!(
        autumn_toml
            .matches("[[security.webhooks.endpoints]]")
            .count(),
        4,
        "each preset must add its own endpoint:\n{autumn_toml}"
    );
}

#[test]
fn generate_webhook_dry_run_writes_nothing() {
    let (_tmp, project) = fresh_project("webhook-dry-run");
    let toml_before = fs::read_to_string(project.join("autumn.toml")).unwrap();
    let (stdout, _stderr) = run_autumn(
        &project,
        &["generate", "webhook", "stripe", "Payments", "--dry-run"],
    );

    assert!(stdout.contains("Dry run"), "got:\n{stdout}");
    assert!(stdout.contains("Would create"), "got:\n{stdout}");
    assert!(
        !project.join("src/webhooks").exists(),
        "--dry-run must not write any file"
    );
    assert_eq!(
        fs::read_to_string(project.join("autumn.toml")).unwrap(),
        toml_before,
        "--dry-run must not touch autumn.toml"
    );
}

#[test]
fn generate_webhook_rejects_an_unknown_provider() {
    let (_tmp, project) = fresh_project("webhook-bad-provider");
    let (_stdout, stderr, code) =
        run_autumn_failing(&project, &["generate", "webhook", "twilio", "Sms"]);
    assert_eq!(code, Some(1), "got:\n{stderr}");
    assert!(
        stderr.contains("twilio") && stderr.contains("generic"),
        "got:\n{stderr}"
    );
    assert!(!project.join("src/webhooks").exists());
}

#[test]
fn generate_webhook_rejects_hostile_path_and_secret_env_overrides() {
    let (_tmp, project) = fresh_project("webhook-hostile-input");
    let toml_before = fs::read_to_string(project.join("autumn.toml")).unwrap();

    // A quote would break out of the generated `#[post("…")]` attribute.
    let (_stdout, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "webhook",
            "stripe",
            "Payments",
            "--path",
            "/a\")]pub fn evil(){}//",
        ],
    );
    assert_eq!(code, Some(1), "got:\n{stderr}");

    // A newline in --secret-env used to smuggle a whole endpoint block, with a
    // plaintext secret and replay protection off, into autumn.toml.
    let (_stdout, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "webhook",
            "stripe",
            "Payments",
            "--secret-env",
            "X\n\n[[security.webhooks.endpoints]]\nname = \"evil\"\npath = \"/evil\"\nprovider = \"generic\"\nsecret = \"attacker-known\"\nreplay_protection = false\n# ",
        ],
    );
    assert_eq!(code, Some(1), "got:\n{stderr}");
    assert!(
        stderr.contains("secret environment variable"),
        "got:\n{stderr}"
    );

    assert!(!project.join("src/webhooks").exists());
    assert_eq!(
        fs::read_to_string(project.join("autumn.toml")).unwrap(),
        toml_before,
        "a rejected invocation must not touch autumn.toml"
    );
}

#[test]
fn generate_webhook_rejects_a_second_endpoint_on_the_same_path() {
    let (_tmp, project) = fresh_project("webhook-dup-path");
    run_autumn(&project, &["generate", "webhook", "stripe", "Payments"]);
    let (_stdout, stderr, code) =
        run_autumn_failing(&project, &["generate", "webhook", "stripe", "Billing"]);
    assert_eq!(code, Some(1), "got:\n{stderr}");
    assert!(
        stderr.contains("/webhooks/stripe") && stderr.contains("--path"),
        "the duplicate-path error must suggest --path:\n{stderr}"
    );

    // …and the override succeeds.
    run_autumn(
        &project,
        &[
            "generate",
            "webhook",
            "stripe",
            "Billing",
            "--path",
            "/webhooks/stripe-billing",
        ],
    );
    let handler = fs::read_to_string(project.join("src/webhooks/billing.rs")).unwrap();
    assert!(
        handler.contains("#[post(\"/webhooks/stripe-billing\")]"),
        "got:\n{handler}"
    );
}

#[test]
fn destroy_webhook_removes_the_generated_files_and_config() {
    let (_tmp, project) = fresh_project("webhook-destroy");
    let toml_before = fs::read_to_string(project.join("autumn.toml")).unwrap();
    let main_before = fs::read_to_string(project.join("src/main.rs")).unwrap();

    run_autumn(&project, &["generate", "webhook", "stripe", "Payments"]);
    run_autumn(&project, &["destroy", "webhook", "stripe", "Payments"]);

    assert!(
        !project.join("src/webhooks").exists(),
        "the handler module must be gone"
    );
    assert_eq!(
        fs::read_to_string(project.join("autumn.toml")).unwrap(),
        toml_before,
        "autumn.toml must be restored exactly"
    );
    assert_eq!(
        fs::read_to_string(project.join("src/main.rs")).unwrap(),
        main_before,
        "src/main.rs must be restored exactly"
    );
}

/// Slow end-to-end check: scaffold a fresh project, generate every provider
/// preset, and `cargo check --tests` it — the acceptance-criterion proof that
/// generated webhook code compiles with no hand-editing.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_webhook_cargo_checks() {
    let (_tmp, project) = fresh_project("webhook-build");
    patch_generated_cargo_toml(&project);

    for (provider, name) in [
        ("stripe", "Payments"),
        ("github", "Repo"),
        ("slack", "Events"),
        ("generic", "Partner"),
    ] {
        run_autumn(&project, &["generate", "webhook", provider, name]);
    }

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated webhooks failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Slow end-to-end check: actually RUN the generated webhook tests. This is the
/// acceptance-criterion proof that a valid signature is accepted, a
/// missing/invalid signature is rejected, and a replayed delivery is rejected —
/// on first run, with no manual edits beyond the ones the issue allows.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: builds and runs a fresh project's test suite — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_webhook_tests_pass() {
    let (_tmp, project) = fresh_project("webhook-smoke");
    patch_generated_cargo_toml(&project);

    for (provider, name) in [
        ("stripe", "Payments"),
        ("github", "Repo"),
        ("slack", "Events"),
        ("generic", "Partner"),
    ] {
        run_autumn(&project, &["generate", "webhook", provider, name]);
    }

    let test_run = Command::new("cargo")
        .args(["test", "webhooks::"])
        .current_dir(&project)
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&test_run.stdout);
    assert!(
        test_run.status.success(),
        "generated webhook tests failed:\nstdout:\n{stdout}\nstderr:\n{}",
        String::from_utf8_lossy(&test_run.stderr),
    );
    assert!(
        stdout.contains("16 passed"),
        "expected all four presets' four cases to pass; got:\n{stdout}"
    );
}

// ── autumn generate auth integration tests ────────────────────────────────────

#[allow(clippy::too_many_lines)]
#[test]
fn generate_auth_in_fresh_project_creates_expected_files() {
    let (_tmp, project) = fresh_project("auth-app");
    run_autumn(&project, &["generate", "auth", "User"]);

    // Migration directory exists with up.sql and down.sql.
    let migrations: Vec<_> = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| e.file_name().to_string_lossy().ends_with("_create_users"))
        .collect();
    assert_eq!(migrations.len(), 1, "expected one create_users migration");
    let mig_dir = migrations[0].path();
    let up = fs::read_to_string(mig_dir.join("up.sql")).unwrap();
    assert!(
        up.contains("CREATE TABLE users"),
        "up.sql missing CREATE TABLE"
    );
    assert!(up.contains("email"), "up.sql missing email column");
    assert!(
        up.contains("time_zone TEXT NULL"),
        "up.sql missing time_zone column"
    );
    assert!(
        up.contains("password_digest"),
        "up.sql missing password_digest"
    );
    assert!(
        up.contains("reset_token_digest"),
        "up.sql missing reset_token_digest"
    );
    assert!(up.contains("UNIQUE"), "email must be UNIQUE");
    let down = fs::read_to_string(mig_dir.join("down.sql")).unwrap();
    assert!(
        down.contains("DROP TABLE users"),
        "down.sql missing DROP TABLE"
    );

    // Model file
    let model = fs::read_to_string(project.join("src/models/user.rs")).unwrap();
    assert!(model.contains("pub struct User"), "model missing struct");
    assert!(
        model.contains("pub email: String"),
        "model missing email field"
    );
    assert!(
        model.contains("pub time_zone: Option<String>"),
        "model missing time_zone field"
    );
    assert!(
        model.contains("pub password_digest: String"),
        "model missing password_digest"
    );
    assert!(
        !model.contains("pub password:"),
        "raw password must not be stored"
    );

    // mod.rs declares user module
    let mod_rs = fs::read_to_string(project.join("src/models/mod.rs")).unwrap();
    assert!(
        mod_rs.contains("pub mod user;"),
        "models/mod.rs missing pub mod user"
    );

    // schema.rs entry
    let schema = fs::read_to_string(project.join("src/schema.rs")).unwrap();
    assert!(
        schema.contains("users (id)"),
        "schema.rs missing users table block"
    );
    assert!(
        schema.contains("email -> Text"),
        "schema.rs missing email column"
    );
    assert!(
        schema.contains("time_zone -> Nullable<Text>"),
        "schema.rs missing time_zone column"
    );
    assert!(
        schema.contains("reset_token_digest -> Nullable<Text>"),
        "schema.rs missing nullable reset_token_digest"
    );

    // Routes file
    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    for handler in [
        "pub async fn signup_form",
        "pub async fn signup",
        "pub async fn login_form",
        "pub async fn login",
        "pub async fn logout",
        "pub async fn account",
        "pub async fn forgot_password_form",
        "pub async fn forgot_password",
        "pub async fn reset_password_form",
        "pub async fn reset_password",
    ] {
        assert!(
            routes.contains(handler),
            "routes/auth.rs missing: {handler}"
        );
    }
    assert!(
        routes.contains("#[secured]"),
        "account route must be protected"
    );
    assert!(
        routes.contains("session.destroy"),
        "logout must destroy session"
    );
    assert!(
        routes.contains("session.rotate_id"),
        "login must rotate session id"
    );
    assert!(
        routes.contains("State(state): State<AppState>"),
        "auth routes must receive AppState so sessions use the configured auth key"
    );
    assert!(
        routes.contains("session.insert(state.auth_session_key()"),
        "auth routes must populate the configured auth session key"
    );
    assert_eq!(
        routes.matches("session.insert(\"user_id\"").count(),
        4,
        "User auth routes should only write user_id as the generated account id key \
         (login, reset_password, confirm_email, and the remember-me restore path \
         establish_remember_login, which must set the same identity keys as a fresh login)"
    );
    assert!(
        routes.contains("email.split_once('@')"),
        "signup email validation should use split_once"
    );
    assert!(
        !routes.contains("email.find('@').unwrap()"),
        "signup email validation should not search for @ repeatedly"
    );
    // Issue #1353: auth views render through the app's shared `crate::layout`
    // (nav/header/footer shell) rather than a private bare-DOCTYPE `fn layout`
    // stub, and pending flashes are threaded to the layout's 3rd argument via
    // the accessible `flash_messages()` helper (not the old `flash.render()`).
    assert!(
        !routes.contains("fn layout(title: &str, content: Markup)"),
        "the private 2-arg layout stub must be removed"
    );
    assert!(
        routes.contains("crate::layout("),
        "auth views must render through crate::layout"
    );
    assert!(
        routes.contains(
            "crate::layout(\"Log In\", \"/login\", flash_messages(&flash.consume().await),"
        ),
        "login must render through crate::layout with /login + flash"
    );
    assert!(
        !routes.contains("flash.render().await"),
        "auth views must not use the old in-content flash.render() path"
    );

    // routes/mod.rs
    let route_mod = fs::read_to_string(project.join("src/routes/mod.rs")).unwrap();
    assert!(
        route_mod.contains("pub mod auth;"),
        "routes/mod.rs missing pub mod auth"
    );

    // Generated tests file
    let tests = fs::read_to_string(project.join("tests/auth.rs")).unwrap();
    for flow in [
        "auth_signup_returns_200",
        "auth_login_returns_200",
        "auth_logout_redirects",
        "auth_forgot_password_returns_200",
        "auth_reset_password_returns_200",
        "auth_account_rejects_anonymous",
    ] {
        assert!(tests.contains(flow), "tests/auth.rs missing: {flow}");
    }

    // Documentation
    assert!(
        project.join("docs/guide/authentication.md").exists(),
        "docs/guide/authentication.md must be created"
    );

    // main.rs registers auth routes
    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    for entry in [
        "routes::auth::signup_form",
        "routes::auth::login_form",
        "routes::auth::logout",
        "routes::auth::account",
        "routes::auth::forgot_password_form",
        "routes::auth::reset_password_form",
    ] {
        assert!(main.contains(entry), "main.rs missing route: {entry}");
    }
}

#[test]
fn generate_auth_dry_run_writes_nothing() {
    let (_tmp, project) = fresh_project("auth-dry-app");
    let (stdout, _) = run_autumn(&project, &["generate", "auth", "User", "--dry-run"]);
    assert!(
        stdout.contains("Dry run"),
        "expected dry-run output; got: {stdout}"
    );
    assert!(
        !project.join("src/models/user.rs").exists(),
        "dry run must not create model file"
    );
    assert!(
        !project.join("src/routes/auth.rs").exists(),
        "dry run must not create routes file"
    );
    assert!(
        !project.join("tests/auth.rs").exists(),
        "dry run must not create tests file"
    );
}

#[test]
fn generate_auth_collision_without_force_fails() {
    let (_tmp, project) = fresh_project("auth-collide-app");
    run_autumn(&project, &["generate", "auth", "User"]);
    // Re-run without --force should fail with collision error.
    let (_, stderr, code) = run_autumn_failing(&project, &["generate", "auth", "User"]);
    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("would overwrite"),
        "expected collision message; got stderr: {stderr}"
    );
}

#[test]
fn generate_auth_force_overwrites_existing_files() {
    let (_tmp, project) = fresh_project("auth-force-app");
    run_autumn(&project, &["generate", "auth", "User"]);
    let model_path = project.join("src/models/user.rs");
    let original = fs::read_to_string(&model_path).unwrap();
    fs::write(&model_path, "// touched").unwrap();
    run_autumn(&project, &["generate", "auth", "User", "--force"]);
    let regenerated = fs::read_to_string(&model_path).unwrap();
    assert_eq!(
        regenerated, original,
        "--force must restore original content"
    );
}

#[test]
fn generate_auth_help_documents_command() {
    let tmp = tempfile::tempdir().unwrap();
    let autumn_bin = env!("CARGO_BIN_EXE_autumn");
    let output = Command::new(autumn_bin)
        .args(["generate", "auth", "--help"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("--dry-run"),
        "help should mention --dry-run"
    );
    assert!(stdout.contains("--force"), "help should mention --force");
    assert!(stdout.contains("--totp"), "help should mention --totp");
}

// ── autumn generate auth --totp (issue #799) ──────────────────────────────────

#[allow(clippy::too_many_lines)]
#[test]
fn generate_auth_totp_creates_expected_files() {
    let (_tmp, project) = fresh_project("auth-totp-app");
    run_autumn(&project, &["generate", "auth", "User", "--totp"]);

    // Migration: TOTP columns on users + recovery_codes table.
    let migrations: Vec<_> = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| e.file_name().to_string_lossy().ends_with("_create_users"))
        .collect();
    assert_eq!(migrations.len(), 1, "expected one create_users migration");
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(
        up.contains("totp_secret_encrypted"),
        "up.sql missing totp_secret_encrypted"
    );
    assert!(up.contains("totp_enabled"), "up.sql missing totp_enabled");
    assert!(
        up.contains("CREATE TABLE recovery_codes"),
        "up.sql missing recovery_codes table"
    );
    assert!(up.contains("code_digest"), "up.sql missing code_digest");
    assert!(up.contains("used_at"), "up.sql missing used_at");
    let down = fs::read_to_string(migrations[0].path().join("down.sql")).unwrap();
    assert!(
        down.contains("DROP TABLE recovery_codes"),
        "down.sql must drop recovery_codes"
    );

    // Model gains TOTP fields; recovery_code model exists.
    let model = fs::read_to_string(project.join("src/models/user.rs")).unwrap();
    assert!(model.contains("pub totp_secret_encrypted: Option<String>"));
    assert!(model.contains("pub totp_enabled: bool"));
    assert!(
        project.join("src/models/recovery_code.rs").exists(),
        "recovery_code model missing"
    );
    let mod_rs = fs::read_to_string(project.join("src/models/mod.rs")).unwrap();
    assert!(
        mod_rs.contains("pub mod recovery_code;"),
        "models/mod.rs missing recovery_code"
    );

    // schema.rs: totp columns + recovery_codes table.
    let schema = fs::read_to_string(project.join("src/schema.rs")).unwrap();
    assert!(schema.contains("totp_secret_encrypted -> Nullable<Text>"));
    assert!(schema.contains("totp_enabled -> Bool"));
    assert!(schema.contains("recovery_codes (id)"));

    // Routes: 2FA handlers + paths.
    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    for needle in [
        "pub async fn two_factor_status",
        "pub async fn two_factor_enable",
        "pub async fn two_factor_confirm",
        "pub async fn two_factor_disable",
        "pub async fn login_verify",
        "otpauth://",
        "Aes256Gcm",
        "totp_pending",
    ] {
        assert!(routes.contains(needle), "routes/auth.rs missing: {needle}");
    }

    // Generated 2FA integration tests cover the full round trip.
    let tests = fs::read_to_string(project.join("tests/auth_2fa.rs")).unwrap();
    for flow in [
        "two_factor_enroll_and_confirm",
        "login_with_totp_code",
        "login_with_recovery_code",
        "recovery_code_reuse_rejected",
        "two_factor_disable",
    ] {
        assert!(tests.contains(flow), "tests/auth_2fa.rs missing: {flow}");
    }

    // Cargo deps + docs.
    let cargo = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(cargo.contains("totp-rs ="), "Cargo.toml missing totp-rs");
    assert!(cargo.contains("aes-gcm ="), "Cargo.toml missing aes-gcm");
    let docs = fs::read_to_string(project.join("docs/guide/authentication.md")).unwrap();
    assert!(
        docs.contains("Two-Factor Authentication"),
        "docs missing 2FA section"
    );

    // main.rs registers the new routes.
    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    for entry in [
        "routes::auth::two_factor_enable",
        "routes::auth::login_verify",
    ] {
        assert!(main.contains(entry), "main.rs missing route: {entry}");
    }
}

#[test]
fn generate_auth_without_totp_has_no_totp_artifacts() {
    let (_tmp, project) = fresh_project("auth-no-totp-app");
    run_autumn(&project, &["generate", "auth", "User"]);
    let model = fs::read_to_string(project.join("src/models/user.rs")).unwrap();
    assert!(
        !model.contains("totp_enabled"),
        "default auth must not include totp fields"
    );
    assert!(!project.join("src/models/recovery_code.rs").exists());
    assert!(!project.join("tests/auth_2fa.rs").exists());
}

#[test]
fn generate_auth_passkeys_creates_expected_files() {
    let (_tmp, project) = fresh_project("auth-passkeys-app");
    run_autumn(&project, &["generate", "auth", "User", "--passkeys"]);

    // Migration: Webauthn credentials table exists.
    let migrations: Vec<_> = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_create_webauthn_credentials")
        })
        .collect();
    assert_eq!(
        migrations.len(),
        1,
        "expected one create_webauthn_credentials migration"
    );
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(
        up.contains("CREATE TABLE webauthn_credentials"),
        "up.sql missing webauthn_credentials table"
    );

    // Model: webauthn_credential model exists.
    assert!(
        project.join("src/models/webauthn_credential.rs").exists(),
        "webauthn_credential model missing"
    );

    // Routes: passkey routes.
    let routes = fs::read_to_string(project.join("src/routes/passkeys.rs")).unwrap();
    for needle in [
        "pub async fn passkey_register_page",
        "pub async fn passkey_login_page",
        "let script_nonce = nonce.map(|n| n.value().to_owned());",
    ] {
        assert!(
            routes.contains(needle),
            "routes/passkeys.rs missing or incorrect: {needle}"
        );
    }

    // Ensure it does not contain the old private field access.
    assert!(
        !routes.contains("nonce.map(|n| n.0.clone())"),
        "routes/passkeys.rs must not access private field n.0"
    );
}

#[test]
fn generate_auth_without_passkeys_has_no_passkeys_artifacts() {
    let (_tmp, project) = fresh_project("auth-no-passkeys-app");
    run_autumn(&project, &["generate", "auth", "User"]);
    assert!(!project.join("src/models/webauthn_credential.rs").exists());
    assert!(!project.join("src/routes/passkeys.rs").exists());
}

#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_auth_passkeys_cargo_checks() {
    let (_tmp, project) = fresh_project("auth-passkeys-build");
    patch_generated_cargo_toml(&project);

    run_autumn(&project, &["generate", "auth", "User", "--passkeys"]);

    let cargo_after = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    for dep in ["webauthn-rs", "uuid", "serde", "diesel", "maud", "chrono"] {
        assert!(
            cargo_after.contains(&format!("{dep} =")),
            "Cargo.toml missing '{dep}' after `generate auth --passkeys`"
        );
    }

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated --passkeys auth failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

// ── autumn generate auth --magic-link (issue #1328) ───────────────────────────

#[test]
fn generate_auth_magic_link_creates_expected_files() {
    let (_tmp, project) = fresh_project("auth-magic-link-app");
    run_autumn(&project, &["generate", "auth", "User", "--magic-link"]);

    // Migration: dedicated magic_link_tokens table with single-use marker.
    let up = fs::read_to_string(
        fs::read_dir(project.join("migrations"))
            .unwrap()
            .filter_map(Result::ok)
            .find(|e| e.file_name().to_string_lossy().ends_with("_create_users"))
            .unwrap()
            .path()
            .join("up.sql"),
    )
    .unwrap();
    assert!(up.contains("CREATE TABLE magic_link_tokens"));
    assert!(up.contains("token_digest TEXT NOT NULL UNIQUE"));
    assert!(up.contains("consumed_at TIMESTAMP NULL"));

    // Model file + module declaration.
    assert!(project.join("src/models/magic_link_token.rs").exists());
    let mod_rs = fs::read_to_string(project.join("src/models/mod.rs")).unwrap();
    assert!(mod_rs.contains("pub mod magic_link_token;"));

    // Routes: request/email/verify handlers + throttle.
    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    for needle in [
        "#[get(\"/login/magic\")]",
        "#[post(\"/login/magic\")]",
        "#[get(\"/login/magic/verify\")]",
        "#[throttle(",
        "pub async fn magic_link_verify",
        "async fn send_magic_link_email",
    ] {
        assert!(routes.contains(needle), "routes/auth.rs missing: {needle}");
    }

    // Routes registered in main.rs.
    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(main.contains("routes::auth::magic_link_verify"));

    // Docs document the flow.
    let docs = fs::read_to_string(project.join("docs/guide/authentication.md")).unwrap();
    assert!(docs.contains("Passwordless Magic-Link Login"));
}

#[test]
fn generate_auth_without_magic_link_emits_no_magic_link_artifacts() {
    let (_tmp, project) = fresh_project("auth-no-magic-link-app");
    run_autumn(&project, &["generate", "auth", "User"]);
    assert!(!project.join("src/models/magic_link_token.rs").exists());
    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    assert!(!routes.contains("/login/magic"));
}

/// Slow: scaffold `generate auth --magic-link` and `cargo check --tests` the
/// result against the local `autumn-web` crate, proving the generated
/// magic-link app and its test suite type-check with zero edits (issue #1328).
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_auth_magic_link_cargo_checks() {
    let (_tmp, project) = fresh_project("auth-magic-link-build");
    patch_generated_cargo_toml(&project);

    run_autumn(&project, &["generate", "auth", "User", "--magic-link"]);

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated --magic-link auth failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Slow: prove `--magic-link` composes with `--totp` in a single generated app
/// that still type-checks (issue #1328 composability AC1).
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_auth_magic_link_with_totp_cargo_checks() {
    let (_tmp, project) = fresh_project("auth-magic-totp-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &["generate", "auth", "User", "--totp", "--magic-link"],
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated --totp --magic-link auth failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Slow: scaffold `generate auth --totp` and `cargo check --tests` the result
/// against the local `autumn-web` crate, proving the generated 2FA app and its
/// test suite type-check with zero edits (issue #799 success metric).
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_auth_totp_cargo_checks() {
    let (_tmp, project) = fresh_project("auth-totp-build");
    patch_generated_cargo_toml(&project);

    run_autumn(&project, &["generate", "auth", "User", "--totp"]);

    let cargo_after = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    for dep in ["totp-rs", "aes-gcm", "base64", "diesel", "maud", "chrono"] {
        assert!(
            cargo_after.contains(&format!("{dep} =")),
            "Cargo.toml missing '{dep}' after `generate auth --totp`"
        );
    }

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated --totp auth failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

// ── TOML config (issue #669) ──────────────────────────────────────────────────

/// Scaffold a resource using only a `--config` file, no inline CLI metadata.
#[test]
fn generate_scaffold_from_config_file() {
    let (_tmp, project) = fresh_project("scaffold-config-app");

    fs::write(
        project.join("autumn.generate.toml"),
        "[scaffold.Bookmark]\n\
         fields      = [\"url:String\", \"title:String\", \"tag:String\", \"alive:bool\"]\n\
         indexes     = [\"url\", \"tag\"]\n\
         validations = [\"url=url\", \"title=length:min=1,max=200\"]\n\
         defaults    = [\"alive=true\"]\n\
         queries     = [\"find_by_tag:tag\", \"find_by_alive:alive\"]\n",
    )
    .unwrap();

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Bookmark",
            "--config",
            "autumn.generate.toml",
        ],
    );

    let model = fs::read_to_string(project.join("src/models/bookmark.rs")).unwrap();
    assert!(
        model.contains("#[indexed]\n    #[validate(url)]\n    pub url: String,"),
        "model missing indexed+validated url field:\n{model}"
    );
    assert!(
        model.contains("#[validate(length(min = 1, max = 200))]\n    pub title: String,"),
        "model missing length-validated title field:\n{model}"
    );
    assert!(
        model.contains("#[indexed]\n    pub tag: String,"),
        "model missing indexed tag field:\n{model}"
    );
    assert!(
        model.contains("#[default]\n    pub alive: bool,"),
        "model missing defaulted alive field:\n{model}"
    );

    let repo = fs::read_to_string(project.join("src/repositories/bookmark.rs")).unwrap();
    assert!(
        repo.contains("fn find_by_tag(tag: String) -> Vec<Bookmark>;"),
        "repo missing find_by_tag query:\n{repo}"
    );
    assert!(
        repo.contains("fn find_by_alive(alive: bool) -> Vec<Bookmark>;"),
        "repo missing find_by_alive query:\n{repo}"
    );

    let migration = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .find(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_create_bookmarks")
        })
        .expect("create_bookmarks migration must exist");
    let up = fs::read_to_string(migration.path().join("up.sql")).unwrap();
    assert!(
        up.contains("alive BOOLEAN NOT NULL DEFAULT TRUE"),
        "SQL missing default: {up}"
    );
    assert!(
        up.contains("CREATE INDEX idx_bookmarks_url ON bookmarks (url);"),
        "SQL missing url index: {up}"
    );
    assert!(
        up.contains("CREATE INDEX idx_bookmarks_tag ON bookmarks (tag);"),
        "SQL missing tag index: {up}"
    );

    let cargo_toml = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(
        cargo_toml.contains("validator ="),
        "Cargo.toml missing validator dep:\n{cargo_toml}"
    );
}

/// CLI flags override the corresponding TOML values when both are present.
#[test]
fn generate_scaffold_cli_overrides_toml_config() {
    let (_tmp, project) = fresh_project("scaffold-config-override-app");

    fs::write(
        project.join("autumn.generate.toml"),
        "[scaffold.Post]\nfields  = [\"title:String\", \"body:Text\"]\nindexes = [\"title\"]\n",
    )
    .unwrap();

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "content:String",
            "--index",
            "content",
            "--config",
            "autumn.generate.toml",
        ],
    );

    let model = fs::read_to_string(project.join("src/models/post.rs")).unwrap();
    assert!(
        model.contains("pub content: String"),
        "model must have CLI field 'content': {model}"
    );
    assert!(
        !model.contains("pub title: String"),
        "model must not have TOML field 'title': {model}"
    );
    assert!(
        !model.contains("pub body:"),
        "model must not have TOML field 'body': {model}"
    );

    let migration = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .find(|e| e.file_name().to_string_lossy().ends_with("_create_posts"))
        .expect("create_posts migration must exist");
    let up = fs::read_to_string(migration.path().join("up.sql")).unwrap();
    assert!(
        up.contains("CREATE INDEX idx_posts_content ON posts (content);"),
        "SQL must have CLI index on 'content': {up}"
    );
    assert!(
        !up.contains("idx_posts_title"),
        "SQL must not have TOML index on 'title': {up}"
    );
}

/// A non-existent config file must cause a non-zero exit with the filename
/// mentioned in the error output.
#[test]
fn generate_scaffold_rejects_missing_config_file() {
    let (_tmp, project) = fresh_project("scaffold-missing-config-app");

    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "--config",
            "nonexistent.toml",
        ],
    );

    assert_eq!(code, Some(1), "expected exit code 1; got {code:?}");
    assert!(
        stderr.contains("nonexistent.toml"),
        "error must mention the missing file name; got:\n{stderr}"
    );
}

/// Explicit `--config` with no matching `[scaffold.X]` section but WITH CLI
/// fields succeeds: the field list comes from the CLI and the config is only
/// consulted for project defaults.
#[test]
fn generate_scaffold_missing_resource_section_uses_defaults() {
    let (_tmp, project) = fresh_project("scaffold-missing-section-app");

    fs::write(
        project.join("autumn.generate.toml"),
        "[scaffold.OtherResource]\nfields = [\"name:String\"]\n",
    )
    .unwrap();

    // No [scaffold.Post] section, but fields supplied on the CLI → succeed.
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "--config",
            "autumn.generate.toml",
        ],
    );

    // Default id type is BigSerial when no [generate] id is set.
    let model = fs::read_to_string(project.join("src/models/post.rs")).unwrap();
    assert!(
        model.contains("pub id: i64,"),
        "missing-section scaffold should default to i64 PK; got:\n{model}"
    );
}

/// Typo protection (Codex P2): explicit `--config` with no matching
/// `[scaffold.X]` section, the file DOES define other scaffold resources, and
/// NO CLI fields were given → the command must error rather than silently
/// generate an empty resource.
#[test]
fn generate_scaffold_explicit_config_missing_section_errors() {
    let (_tmp, project) = fresh_project("scaffold-typo-section-app");

    fs::write(
        project.join("autumn.generate.toml"),
        "[scaffold.OtherResource]\nfields = [\"name:String\"]\n",
    )
    .unwrap();

    // Misspelled/missing [scaffold.Post] + no CLI fields → likely a typo.
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "--config",
            "autumn.generate.toml",
        ],
    );
    assert_eq!(
        code,
        Some(1),
        "missing section with no CLI fields must fail"
    );
    assert!(
        stderr.contains("no [scaffold.Post] section found"),
        "error must name the missing section; got:\n{stderr}"
    );
    assert!(
        !project.join("src/models/post.rs").exists(),
        "errored scaffold must not write a model file"
    );
}

/// Slow compile-check: scaffold a fresh project from a TOML config file and
/// verify that `cargo check --tests` succeeds against the local `autumn-web`
/// crate.  Ensures that the config-driven generator adds every dependency its
/// emitted code needs (validator, maud, etc.) and that all generated files
/// type-check without manual edits.
///
/// Ignored by default; run with:
/// `cargo test -p autumn-cli --test generate generated_scaffold_config_cargo_checks -- --ignored --exact`
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_scaffold_config_cargo_checks() {
    let (_tmp, project) = fresh_project("scaffold-config-build");

    patch_generated_cargo_toml(&project);

    fs::write(
        project.join("autumn.generate.toml"),
        "[scaffold.Bookmark]\n\
         fields      = [\"url:String\", \"title:String\", \"tag:String\", \"alive:bool\"]\n\
         indexes     = [\"url\", \"tag\"]\n\
         validations = [\"url=url\", \"title=length:min=1,max=200\"]\n\
         defaults    = [\"alive=true\"]\n\
         queries     = [\"find_by_tag:tag\", \"find_by_alive:alive\"]\n",
    )
    .unwrap();

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Bookmark",
            "--config",
            "autumn.generate.toml",
        ],
    );

    let cargo_toml = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    for dep in [
        "chrono",
        "diesel",
        "diesel-async",
        "maud",
        "serde",
        "serde_urlencoded",
        "url",
        "validator",
    ] {
        assert!(
            cargo_toml.contains(&format!("{dep} =")),
            "Cargo.toml missing '{dep}' after config-driven scaffold"
        );
    }

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on config-driven scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

// ── Pagination scaffold tests (issue #681) ──────────────────────────────────

#[test]
fn generate_scaffold_index_uses_paginated_repo_method() {
    let (_tmp, project) = fresh_project("scaffold-paginated-app");
    run_autumn(
        &project,
        &["generate", "scaffold", "Post", "title:String", "body:Text"],
    );

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();

    assert!(
        routes.contains("PageRequest") || routes.contains("page_req"),
        "scaffold index must use PageRequest for pagination: {routes}"
    );
    assert!(
        routes.contains("pagination_nav") || routes.contains("pagination"),
        "scaffold index must render a pagination nav partial: {routes}"
    );
    // Since #1126 the default (non-live) index calls the paginated, sort/filter
    // `list(&ListQuery, &PageRequest)` method instead of the bare `page()`;
    // either paginated repository method satisfies issue #681 (both take a
    // `PageRequest` and return a `Page`, never loading every row).
    assert!(
        routes.contains(".page(") || routes.contains(".list("),
        "scaffold index must call a paginated repository method (page()/list()): {routes}"
    );
    // Scoped to the `index` handler body: since issue #1312 the module also
    // emits a `bulk_delete` handler whose SELECT is bounded by the submitted id
    // list (`WHERE id = ANY($1)`), which is not an unpaginated index load.
    let index = routes
        .split_once("pub async fn index(")
        .expect("scaffold must emit an index handler")
        .1;
    let index = index.split("pub async fn ").next().unwrap_or(index);
    assert!(
        !index.contains(".load(&mut *db)"),
        "scaffold index must not load every row without pagination: {index}"
    );
    // The repository trait must be imported so `repo.list()`/`repo.page()` (trait
    // methods) resolve at compile time — without it the generated code fails with E0599.
    assert!(
        routes.contains("PostRepository"),
        "scaffold routes must import the PostRepository trait (needed to call repo.list()): {routes}"
    );
}

#[test]
fn generate_scaffold_index_uses_page_request_extractor() {
    let (_tmp, project) = fresh_project("scaffold-paginated-extractor-app");
    run_autumn(&project, &["generate", "scaffold", "Post", "title:String"]);

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    // PageRequest extractor handles all clamping — no manual HashMap parsing.
    assert!(
        routes.contains("page_req: PageRequest") || routes.contains("PageRequest,"),
        "scaffold index must use the PageRequest extractor: {routes}"
    );
    assert!(
        !routes.contains("HashMap"),
        "scaffold index must not manually parse query params via HashMap: {routes}"
    );
}

#[test]
fn generate_scaffold_repository_exposes_page_method() {
    let (_tmp, project) = fresh_project("scaffold-repo-page-app");
    run_autumn(&project, &["generate", "scaffold", "Post", "title:String"]);

    let repo = fs::read_to_string(project.join("src/repositories/post.rs")).unwrap();
    // The page() and cursor_page() methods are code-generated by the
    // #[autumn_web::repository] macro — they are not written out in the source
    // file.  Asserting the macro attribute is present is the correct contract:
    // the macro tests already verify it generates page() + cursor_page().
    assert!(
        repo.contains("#[autumn_web::repository("),
        "scaffold repository must use #[autumn_web::repository] (which generates page()): {repo}"
    );
    // Sanity-check that the trait is declared (confirms the scaffold structure).
    assert!(
        repo.contains("pub trait PostRepository"),
        "scaffold repository must declare a public PostRepository trait: {repo}"
    );
}

// ── autumn generate mailer ────────────────────────────────────────────────────

#[test]
fn generate_mailer_creates_all_expected_files() {
    let (_tmp, project) = fresh_project("mailer-app");
    let (stdout, _stderr) = run_autumn(&project, &["generate", "mailer", "Welcome"]);

    assert!(
        stdout.contains("welcome.rs") || stdout.contains("Created"),
        "output should mention created files: {stdout}"
    );

    // Mailer source file — production code only, no preview.
    assert!(project.join("src/mailers/welcome.rs").is_file());
    let mailer = fs::read_to_string(project.join("src/mailers/welcome.rs")).unwrap();
    assert!(mailer.contains("pub struct WelcomeMailer"));
    assert!(mailer.contains("#[mailer]"));
    assert!(
        !mailer.contains("#[mailer_preview]"),
        "#[mailer_preview] must live in previews/, not the mailer file"
    );
    assert!(mailer.contains("pub fn welcome("));
    assert!(mailer.contains("deliver_later"));

    // Shared layout files (created on first generate mailer).
    assert!(project.join("templates/mailers/_layout.html").is_file());
    let layout_html = fs::read_to_string(project.join("templates/mailers/_layout.html")).unwrap();
    assert!(
        layout_html.contains("<!DOCTYPE html>"),
        "_layout.html must be a full document shell"
    );
    assert!(
        layout_html.contains("<table"),
        "_layout.html must contain a table-based wrapper"
    );
    assert!(
        layout_html.contains("style="),
        "_layout.html must use inline styles"
    );
    assert!(
        layout_html.contains("{{ content }}"),
        "_layout.html must contain the content slot"
    );
    assert!(project.join("templates/mailers/_layout.txt").is_file());
    let layout_txt = fs::read_to_string(project.join("templates/mailers/_layout.txt")).unwrap();
    assert!(
        layout_txt.contains("{{ content }}"),
        "_layout.txt must contain the content slot"
    );

    // Per-mailer HTML + text templates — body fragment only, no document shell.
    assert!(project.join("templates/mailers/welcome.html").is_file());
    let html = fs::read_to_string(project.join("templates/mailers/welcome.html")).unwrap();
    assert!(html.contains("WelcomeMailer"));
    assert!(
        !html.contains("<!DOCTYPE"),
        "per-mailer template must be a body fragment, not a full document"
    );
    assert!(project.join("templates/mailers/welcome.txt").is_file());
    let txt = fs::read_to_string(project.join("templates/mailers/welcome.txt")).unwrap();
    assert!(txt.contains("WelcomeMailer"));

    // Module index declares both the mailer and the previews sub-module.
    assert!(project.join("src/mailers/mod.rs").is_file());
    let mod_rs = fs::read_to_string(project.join("src/mailers/mod.rs")).unwrap();
    assert!(mod_rs.contains("pub mod welcome;"));
    assert!(mod_rs.contains("pub mod previews;"));

    // Smoke test is inline in the mailer file.
    assert!(!project.join("tests/welcome_mailer.rs").exists());
    assert!(mailer.contains("mod welcome_mailer_tests"));
    assert!(mailer.contains("welcome_mailer_renders_both_bodies"));
}

#[test]
fn generate_mailer_creates_preview_files_and_wires_main() {
    let (_tmp, project) = fresh_project("mailer-preview-files-app");
    run_autumn(&project, &["generate", "mailer", "Welcome"]);

    // Separate preview file with #[mailer_preview].
    assert!(project.join("src/mailers/previews/welcome.rs").is_file());
    let preview = fs::read_to_string(project.join("src/mailers/previews/welcome.rs")).unwrap();
    assert!(preview.contains("#[mailer_preview]"));
    assert!(preview.contains("welcome_preview"));

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

    // main.rs wiring.
    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(main.contains("mod mailers;"));
    assert!(main.contains("mail_previews!["));
    assert!(main.contains("mailers::welcome::WelcomeMailer"));

    // Cargo.toml: mail feature enabled.
    let cargo = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(
        cargo.contains("\"mail\""),
        "Cargo.toml must include the mail feature: {cargo}"
    );
}

#[test]
fn generate_mailer_dry_run_writes_nothing() {
    let (_tmp, project) = fresh_project("mailer-dry-app");
    let (stdout, _) = run_autumn(&project, &["generate", "mailer", "Welcome", "--dry-run"]);
    assert!(
        stdout.contains("Dry run"),
        "dry run must print Dry run header: {stdout}"
    );
    assert!(
        !project.join("src/mailers/welcome.rs").exists(),
        "dry run must not create the mailer file"
    );
    assert!(
        !project.join("src/mailers/previews/welcome.rs").exists(),
        "dry run must not create the preview file"
    );
    assert!(
        !project.join("templates/mailers/welcome.html").exists(),
        "dry run must not create html template"
    );
    assert!(
        !project.join("templates/mailers/welcome.txt").exists(),
        "dry run must not create txt template"
    );
}

#[test]
fn generate_mailer_collision_without_force_fails() {
    let (_tmp, project) = fresh_project("mailer-collide-app");
    run_autumn(&project, &["generate", "mailer", "Welcome"]);
    let (_, stderr, code) = run_autumn_failing(&project, &["generate", "mailer", "Welcome"]);
    assert_eq!(code, Some(1), "second run without --force must exit 1");
    assert!(
        stderr.contains("would overwrite") || stderr.contains("welcome.rs"),
        "must report collision: {stderr}"
    );
}

#[test]
fn generate_mailer_force_overwrites_existing() {
    let (_tmp, project) = fresh_project("mailer-force-app");
    run_autumn(&project, &["generate", "mailer", "Welcome"]);
    // Corrupt the mailer file so we can detect the overwrite.
    let path = project.join("src/mailers/welcome.rs");
    fs::write(&path, "// corrupted").unwrap();
    run_autumn(&project, &["generate", "mailer", "Welcome", "--force"]);
    let content = fs::read_to_string(&path).unwrap();
    assert!(
        content.contains("WelcomeMailer"),
        "--force must regenerate the mailer file"
    );
    assert!(
        project.join("src/mailers/previews/welcome.rs").exists(),
        "--force must also create the preview file"
    );
}

#[test]
fn generate_mailer_preview_registry_wired_into_main() {
    let (_tmp, project) = fresh_project("mailer-preview-app");
    run_autumn(&project, &["generate", "mailer", "Welcome"]);

    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();

    // The preview registry wiring must appear before `.run()`.
    let preview_pos = main
        .find("mail_previews![")
        .expect("mail_previews![] must be present in main.rs");
    let run_pos = main.find(".run()").expect(".run() must still be present");
    assert!(
        preview_pos < run_pos,
        "mail_previews![] must be wired before .run() in the builder chain"
    );
    assert!(
        main.contains("mailers::welcome::WelcomeMailer"),
        "preview registry must reference the generated mailer type"
    );
}

// ── autumn generate teams (issue #1261) ────────────────────────────────────

#[test]
fn generate_teams_emits_organization_membership_invitation_models() {
    let (_tmp, project) = fresh_project("teams-app");
    let (stdout, _stderr) = run_autumn(&project, &["generate", "teams"]);
    assert!(
        stdout.contains("Created") || stdout.contains("teams"),
        "output should mention created files: {stdout}"
    );

    // Models: Organization, Membership, Invitation.
    assert!(project.join("src/teams/models.rs").is_file());
    let models = fs::read_to_string(project.join("src/teams/models.rs")).unwrap();
    assert!(models.contains("pub struct Organization"), "{models}");
    assert!(models.contains("pub struct Membership"), "{models}");
    assert!(models.contains("pub struct Invitation"), "{models}");

    // Role enum + require_role guard.
    assert!(project.join("src/teams/role.rs").is_file());
    let role = fs::read_to_string(project.join("src/teams/role.rs")).unwrap();
    assert!(role.contains("pub enum Role"), "{role}");
    assert!(role.contains("Owner"), "{role}");
    assert!(role.contains("Admin"), "{role}");
    assert!(role.contains("Member"), "{role}");
    assert!(role.contains("pub async fn require_role"), "{role}");
    assert!(
        role.contains("pub async fn establish_org_session"),
        "{role}"
    );

    // Repositories, tenant_scoped.
    assert!(project.join("src/teams/repositories.rs").is_file());
    let repos = fs::read_to_string(project.join("src/teams/repositories.rs")).unwrap();
    assert!(repos.contains("tenant_scoped"), "{repos}");

    // InvitationMailer.
    assert!(
        project
            .join("src/teams/mailers/invitation_mailer.rs")
            .is_file()
    );
    let mailer =
        fs::read_to_string(project.join("src/teams/mailers/invitation_mailer.rs")).unwrap();
    assert!(mailer.contains("pub struct InvitationMailer"), "{mailer}");
    assert!(mailer.contains("#[mailer]"), "{mailer}");

    // Route handlers.
    assert!(project.join("src/teams/routes/organizations.rs").is_file());
    assert!(project.join("src/teams/routes/invitations.rs").is_file());
    assert!(project.join("src/teams/routes/members.rs").is_file());

    // Migration: organizations, memberships, invitations tables.
    let migrations_root = project.join("migrations");
    let teams_migration_dir = fs::read_dir(&migrations_root)
        .unwrap()
        .filter_map(Result::ok)
        .find(|e| e.file_name().to_string_lossy().ends_with("_create_teams"))
        .expect("a *_create_teams migration must be generated")
        .path();
    let up = fs::read_to_string(teams_migration_dir.join("up.sql")).unwrap();
    assert!(up.contains("CREATE TABLE organizations"), "{up}");
    assert!(up.contains("CREATE TABLE memberships"), "{up}");
    assert!(up.contains("CREATE TABLE invitations"), "{up}");

    // main.rs wiring.
    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(main.contains("mod teams;"), "{main}");
    assert!(
        main.contains("teams::routes::organizations::create_organization"),
        "{main}"
    );
    assert!(
        main.contains("teams::routes::invitations::accept_invitation"),
        "{main}"
    );
    assert!(
        main.contains("teams::routes::members::list_members"),
        "{main}"
    );

    // Cargo.toml: mail feature enabled.
    let cargo = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(
        cargo.contains("\"mail\""),
        "Cargo.toml must include the mail feature: {cargo}"
    );
}

#[test]
fn generate_teams_dry_run_writes_nothing() {
    let (_tmp, project) = fresh_project("teams-dry-app");
    let cargo_before = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    let (stdout, _) = run_autumn(&project, &["generate", "teams", "--dry-run"]);
    assert!(
        stdout.contains("Dry run"),
        "dry run must print Dry run header: {stdout}"
    );
    assert!(
        !project.join("src/teams").exists(),
        "dry run must not create the src/teams directory"
    );
    let has_teams_migration = fs::read_dir(project.join("migrations")).is_ok_and(|rd| {
        rd.filter_map(Result::ok)
            .any(|e| e.file_name().to_string_lossy().ends_with("_create_teams"))
    });
    assert!(
        !has_teams_migration,
        "dry run must not create a *_create_teams migration"
    );
    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(
        !main.contains("mod teams;"),
        "dry run must not touch main.rs: {main}"
    );
    let cargo_after = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert_eq!(
        cargo_after, cargo_before,
        "dry run must not touch Cargo.toml"
    );
}

#[test]
fn generate_teams_invite_accept_routes_use_invite_prefix_not_invitations() {
    let (_tmp, project) = fresh_project("teams-invite-prefix-app");
    run_autumn(&project, &["generate", "teams"]);

    let invitations = fs::read_to_string(project.join("src/teams/routes/invitations.rs")).unwrap();

    // Invitee-facing accept flow lives under its own `/invite` prefix so
    // `[tenancy] public_paths = ["/invite"]` doesn't also exempt the
    // Admin-only routes below from tenant resolution.
    assert!(
        invitations.contains(r#"#[get("/invite/{token}")]"#),
        "{invitations}"
    );
    assert!(
        invitations.contains(r#"#[post("/invite/{token}/accept")]"#),
        "{invitations}"
    );
    assert!(
        !invitations.contains(r#"#[get("/invitations/{token}")]"#),
        "{invitations}"
    );
    assert!(
        !invitations.contains(r#"#[post("/invitations/{token}/accept")]"#),
        "{invitations}"
    );

    // Admin-only create/revoke/resend stay under `/invitations`.
    assert!(
        invitations.contains(r#"#[post("/invitations")]"#),
        "{invitations}"
    );
    assert!(
        invitations.contains(r#"#[post("/invitations/{id}/revoke")]"#),
        "{invitations}"
    );
    assert!(
        invitations.contains(r#"#[post("/invitations/{id}/resend")]"#),
        "{invitations}"
    );
}

#[test]
fn generate_teams_sends_invite_mail_synchronously_not_deliver_later() {
    let (_tmp, project) = fresh_project("teams-sync-mail-app");
    run_autumn(&project, &["generate", "teams"]);

    let invitations = fs::read_to_string(project.join("src/teams/routes/invitations.rs")).unwrap();
    assert!(
        invitations.contains(".send_invite("),
        "invite mail must be sent synchronously: {invitations}"
    );
    assert!(
        !invitations.contains(".deliver_later_invite("),
        "invite mail must not be a fire-and-forget background send: {invitations}"
    );
}

#[test]
fn generate_teams_guards_against_admin_self_promotion_to_owner() {
    let (_tmp, project) = fresh_project("teams-owner-guard-app");
    run_autumn(&project, &["generate", "teams"]);

    // create_invitation: an Admin cannot mint a fresh Owner invite.
    let invitations = fs::read_to_string(project.join("src/teams/routes/invitations.rs")).unwrap();
    assert!(
        invitations.contains("role == Role::Owner && caller_role != Role::Owner"),
        "{invitations}"
    );
    assert!(
        invitations.contains("Only an owner can invite someone as owner"),
        "{invitations}"
    );

    // change_role: an Admin cannot promote an existing member to Owner.
    let members = fs::read_to_string(project.join("src/teams/routes/members.rs")).unwrap();
    assert!(
        members.contains("new_role == Role::Owner && caller_role != Role::Owner"),
        "{members}"
    );
    assert!(
        members.contains("Only an owner can grant the owner role"),
        "{members}"
    );
}

// ── autumn generate auth email confirmation (issue #823) ──────────────────────
//
// RED phase: these tests capture the full acceptance criteria from #823.
// They fail until the email-confirmation feature is implemented in auth.rs.

/// AC1, AC3, AC4: Migration includes `email_confirmed_at`, `confirm_token_digest`,
/// and `confirm_token_expires_at` columns.
#[test]
fn generate_auth_confirmation_migration_has_new_columns() {
    let (_tmp, project) = fresh_project("auth-confirm-migration");
    run_autumn(&project, &["generate", "auth", "User"]);

    let migrations: Vec<_> = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| e.file_name().to_string_lossy().ends_with("_create_users"))
        .collect();
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();

    assert!(
        up.contains("email_confirmed_at"),
        "up.sql missing email_confirmed_at column"
    );
    assert!(
        up.contains("confirm_token_digest"),
        "up.sql missing confirm_token_digest column"
    );
    assert!(
        up.contains("confirm_token_expires_at"),
        "up.sql missing confirm_token_expires_at column"
    );
}

/// AC1, AC3: User model has confirmation fields; signup redirects to a
/// confirmation-pending page instead of logging the user in.
#[test]
fn generate_auth_confirmation_model_fields_and_signup_not_logged_in() {
    let (_tmp, project) = fresh_project("auth-confirm-signup");
    run_autumn(&project, &["generate", "auth", "User"]);

    let model = fs::read_to_string(project.join("src/models/user.rs")).unwrap();
    assert!(
        model.contains("pub email_confirmed_at: Option<chrono::NaiveDateTime>"),
        "model missing email_confirmed_at field"
    );
    assert!(
        model.contains("pub confirm_token_digest: Option<String>"),
        "model missing confirm_token_digest field"
    );
    assert!(
        model.contains("pub confirm_token_expires_at: Option<chrono::NaiveDateTime>"),
        "model missing confirm_token_expires_at field"
    );

    // Signup must NOT log the user in — redirect to a confirmation-pending page.
    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    assert!(
        routes.contains("confirm-email") || routes.contains("check-your-email"),
        "signup handler must redirect to a confirmation-pending page, not /account"
    );
}

/// AC2: Confirmation route `GET /auth/confirm/{token}` exists, stamps
/// `email_confirmed_at`, and invalidates the token.
#[test]
fn generate_auth_confirmation_route_marks_confirmed_and_invalidates_token() {
    let (_tmp, project) = fresh_project("auth-confirm-route");
    run_autumn(&project, &["generate", "auth", "User"]);

    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    assert!(
        routes.contains("pub async fn confirm_email"),
        "routes/auth.rs missing confirm_email handler"
    );
    assert!(
        routes.contains("/auth/confirm/"),
        "routes/auth.rs missing /auth/confirm/:token path"
    );
    assert!(
        routes.contains("email_confirmed_at"),
        "confirm_email handler must stamp email_confirmed_at"
    );
    // Token must be cleared after use.
    assert!(
        routes.contains("confirm_token_digest.eq(None::<String>)"),
        "confirm_email handler must invalidate token after use (set digest to NULL)"
    );
}

/// AC3: Only the SHA-256 digest of the confirmation token is stored in the DB.
#[test]
fn generate_auth_confirmation_only_digest_stored_in_db() {
    let (_tmp, project) = fresh_project("auth-confirm-digest");
    run_autumn(&project, &["generate", "auth", "User"]);

    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    // Digest must be stored (not raw token).
    let stores_digest = routes.contains("confirm_token_digest.eq(Some(&confirm_digest")
        || routes.contains("confirm_token_digest.eq(Some(&token_digest");
    assert!(
        stores_digest,
        "confirmation token digest (not raw token) must be stored"
    );
}

/// AC4: Confirmation tokens expire after 24 hours (default).
#[test]
fn generate_auth_confirmation_token_expires_24h() {
    let (_tmp, project) = fresh_project("auth-confirm-expiry");
    run_autumn(&project, &["generate", "auth", "User"]);

    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    assert!(
        routes.contains("hours(24)"),
        "confirmation token must default to 24-hour expiry"
    );
    assert!(
        routes.contains("confirm_token_expires_at.gt(now)"),
        "confirm handler must reject tokens past confirm_token_expires_at"
    );
}

/// AC5: Unconfirmed login is rejected; login page offers a "resend confirmation"
/// affordance.
#[test]
fn generate_auth_unconfirmed_login_rejected_with_resend_affordance() {
    let (_tmp, project) = fresh_project("auth-confirm-login-gate");
    run_autumn(&project, &["generate", "auth", "User"]);

    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    assert!(
        routes.contains("email_confirmed_at"),
        "login handler must check email_confirmed_at before granting session"
    );
    assert!(
        routes.contains("resend") || routes.contains("Resend"),
        "login form must offer a resend confirmation email affordance"
    );
}

/// AC6: Resend-confirmation handler exists and overwrites the old token.
#[test]
fn generate_auth_resend_confirmation_invalidates_old_token() {
    let (_tmp, project) = fresh_project("auth-confirm-resend");
    run_autumn(&project, &["generate", "auth", "User"]);

    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    assert!(
        routes.contains("pub async fn resend_confirmation"),
        "routes/auth.rs missing resend_confirmation handler"
    );
    assert!(
        routes.contains("confirm_token_digest"),
        "resend_confirmation must update confirm_token_digest"
    );
}

/// AC7: The generated account route or a helper function demonstrates a
/// confirmed-only gate (`email_confirmed_at` check).
#[test]
fn generate_auth_confirmed_gate_present() {
    let (_tmp, project) = fresh_project("auth-confirm-gate");
    run_autumn(&project, &["generate", "auth", "User"]);

    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    assert!(
        routes.contains("email_confirmed_at.is_some()")
            || routes.contains("email_confirmed_at.is_none()")
            || routes.contains("require_confirmed"),
        "routes must demonstrate an email-confirmed gate"
    );
}

/// AC8: Password-reset completion does NOT stamp `email_confirmed_at`.
#[test]
fn generate_auth_password_reset_does_not_confirm_email() {
    let (_tmp, project) = fresh_project("auth-confirm-reset-independence");
    run_autumn(&project, &["generate", "auth", "User"]);

    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();

    // Locate the reset_password handler body (between its `pub async fn` and the next one).
    let reset_start = routes
        .find("pub async fn reset_password(")
        .expect("reset_password handler must exist");
    let rest = &routes[reset_start..];
    // Everything up to the next `pub async fn` is the handler body.
    let reset_body_end = rest[1..]
        .find("pub async fn ")
        .map_or(rest.len(), |p| p + 1);
    let reset_body = &rest[..reset_body_end];

    assert!(
        !reset_body.contains("email_confirmed_at.eq("),
        "reset_password must NOT set email_confirmed_at (confirmation and credential recovery are independent)"
    );
}

/// AC10: The signup handler checks `mailer.is_disabled()` and returns a clear
/// error when mail is not configured — matching the forgot-password precedent.
#[test]
fn generate_auth_confirmation_signup_fails_clearly_when_mail_disabled() {
    let (_tmp, project) = fresh_project("auth-confirm-mail-check");
    run_autumn(&project, &["generate", "auth", "User"]);

    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    assert!(
        routes.contains("mailer.is_disabled()"),
        "signup must check mailer.is_disabled() and return a clear error message"
    );
}

/// AC11: Generated tests/auth.rs covers all confirmation-related flows.
#[test]
fn generate_auth_confirmation_tests_cover_required_flows() {
    let (_tmp, project) = fresh_project("auth-confirm-tests");
    run_autumn(&project, &["generate", "auth", "User"]);

    let tests = fs::read_to_string(project.join("tests/auth.rs")).unwrap();
    for flow in [
        "signup_without_confirm_cannot_login",
        "confirm_with_valid_token_can_login",
        "confirm_with_expired_token_fails",
        "confirm_with_replayed_token_fails",
        "resend_confirmation_rate_limit",
        // The old `email_change_reenters_unconfirmed` stub was replaced by the
        // #1396 account-flow tests: `email_change_confirm_invalid_token_fails`
        // guards the confirm endpoint, and `password_and_email_change_end_to_end`
        // exercises the full pending-email change (old address stays usable until
        // the new-address token is confirmed, then the new address signs in).
        "email_change_confirm_invalid_token_fails",
        "password_and_email_change_end_to_end",
    ] {
        assert!(tests.contains(flow), "tests/auth.rs missing test: {flow}");
    }
}

/// AC12: docs/guide/authentication.md gains a confirmation section covering
/// the threat model, digest storage, gate usage, and email-change behavior.
#[test]
fn generate_auth_confirmation_docs_section_present() {
    let (_tmp, project) = fresh_project("auth-confirm-docs");
    run_autumn(&project, &["generate", "auth", "User"]);

    let docs = fs::read_to_string(project.join("docs/guide/authentication.md")).unwrap();
    assert!(
        docs.contains("Email Confirmation") || docs.contains("email confirmation"),
        "docs missing Email Confirmation section"
    );
    assert!(
        docs.contains("digest") || docs.contains("SHA-256"),
        "docs must describe digest-only token storage rule"
    );
    assert!(
        docs.contains("email_confirmed_at"),
        "docs must reference the email_confirmed_at field"
    );
}

/// AC13: Docs include an opt-in migration path (ALTER TABLE SQL) for existing apps.
#[test]
fn generate_auth_confirmation_docs_migration_path_for_existing_apps() {
    let (_tmp, project) = fresh_project("auth-confirm-migration-path");
    run_autumn(&project, &["generate", "auth", "User"]);

    let docs = fs::read_to_string(project.join("docs/guide/authentication.md")).unwrap();
    assert!(
        docs.contains("email_confirmed_at") && docs.contains("confirm_token_digest"),
        "docs migration path must name both new columns"
    );
    assert!(
        docs.contains("ADD COLUMN") || docs.contains("ALTER TABLE"),
        "docs must include ALTER TABLE migration SQL for existing apps"
    );
}

/// main.rs registers the new confirmation routes.
#[test]
fn generate_auth_confirmation_routes_registered_in_main() {
    let (_tmp, project) = fresh_project("auth-confirm-main-rs");
    run_autumn(&project, &["generate", "auth", "User"]);

    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    assert!(
        main.contains("routes::auth::confirm_email"),
        "main.rs must register confirm_email route"
    );
    assert!(
        main.contains("routes::auth::resend_confirmation"),
        "main.rs must register resend_confirmation route"
    );
}

// ── Active session management (issue #819) ────────────────────────────────────
//
// `autumn generate auth` must emit first-class login-session tracking: a
// per-login session row (token digest, IP, parsed User-Agent, label), per-request
// validation with throttled `last_seen_at` updates, revocation APIs on the user
// model, an `/account/sessions` Maud+htmx page, auto-revocation on
// credential-changing events, integration tests, and privacy documentation.

/// AC1 — a session row is persisted per login with token digest, user id,
/// timestamps, IP, parsed User-Agent fields, and an optional device label.
#[test]
fn generate_auth_sessions_migration_schema_and_model() {
    let (_tmp, project) = fresh_project("auth-sess-app");
    run_autumn(&project, &["generate", "auth", "User"]);

    let migrations: Vec<_> = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| e.file_name().to_string_lossy().ends_with("_create_users"))
        .collect();
    assert_eq!(migrations.len(), 1, "expected one create_users migration");
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(
        up.contains("CREATE TABLE user_sessions"),
        "up.sql missing CREATE TABLE user_sessions:\n{up}"
    );
    for column in [
        "user_id BIGINT NOT NULL REFERENCES users",
        "token_digest TEXT NOT NULL UNIQUE",
        "ip TEXT NOT NULL",
        "user_agent TEXT NOT NULL",
        "ua_family TEXT NOT NULL",
        "ua_os TEXT NOT NULL",
        "ua_device TEXT NOT NULL",
        "label TEXT NULL",
        "last_seen_at TIMESTAMP NOT NULL",
    ] {
        assert!(up.contains(column), "up.sql missing column: {column}\n{up}");
    }
    let down = fs::read_to_string(migrations[0].path().join("down.sql")).unwrap();
    assert!(
        down.contains("DROP TABLE user_sessions"),
        "down.sql must drop user_sessions"
    );
    // Dependent table must drop before the referenced users table.
    assert!(
        down.find("DROP TABLE user_sessions").unwrap() < down.find("DROP TABLE users").unwrap(),
        "user_sessions must be dropped before users"
    );

    // schema.rs gains the table block.
    let schema = fs::read_to_string(project.join("src/schema.rs")).unwrap();
    assert!(
        schema.contains("user_sessions (id)"),
        "schema.rs missing user_sessions block"
    );
    assert!(
        schema.contains("token_digest -> Text"),
        "schema.rs missing token_digest column"
    );

    // Model file: session row + revocation APIs on the user model (AC3).
    let model = fs::read_to_string(project.join("src/models/user_session.rs")).unwrap();
    assert!(
        model.contains("pub struct UserSession"),
        "model missing UserSession struct"
    );
    for needle in [
        "pub token_digest: String",
        "pub last_seen_at: chrono::NaiveDateTime",
        "pub label: Option<String>",
        "pub async fn sessions(",
        "pub async fn revoke_session(",
        "pub async fn revoke_other_sessions(",
        "pub async fn revoke_all_sessions(",
    ] {
        assert!(model.contains(needle), "user_session.rs missing: {needle}");
    }
    // The raw session id must never be stored — only its digest.
    assert!(
        !model.contains("pub token: String"),
        "raw session token must not be stored"
    );

    let mod_rs = fs::read_to_string(project.join("src/models/mod.rs")).unwrap();
    assert!(
        mod_rs.contains("pub mod user_session;"),
        "models/mod.rs missing pub mod user_session"
    );
}

/// AC2 + AC4 + AC6 — routes record the session on login, validate it on
/// authenticated requests (with bounded `last_seen_at` writes), destroy
/// revoked sessions immediately, and serve the /account/sessions page.
#[test]
fn generate_auth_sessions_routes_and_page() {
    let (_tmp, project) = fresh_project("auth-sess-routes");
    run_autumn(&project, &["generate", "auth", "User"]);

    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();

    // Login + logout lifecycle.
    assert!(
        routes.contains("pub async fn record_login_session"),
        "routes missing record_login_session helper"
    );
    assert!(
        routes.contains("pub async fn session_token_digest"),
        "routes missing session_token_digest helper"
    );
    assert!(
        routes.contains("autumn_web::user_agent::parse_user_agent"),
        "login must parse the User-Agent via autumn_web::user_agent"
    );
    // The tracked-session gate: row lookup + throttled last_seen_at update.
    assert!(
        routes.contains("pub async fn require_tracked_session"),
        "routes missing require_tracked_session gate"
    );
    assert!(
        routes.contains("last_seen_update_secs"),
        "last_seen_at updates must be throttled via config"
    );
    // Revoked sessions are destroyed so a replayed cookie cannot resurrect them.
    assert!(
        routes.contains("session.destroy()"),
        "require_tracked_session must destroy revoked sessions"
    );

    // The sessions page + revocation handlers (AC6).
    for needle in [
        "pub async fn sessions_page",
        "pub async fn sessions_revoke",
        "pub async fn sessions_revoke_others",
        "pub async fn sessions_label",
        "#[get(\"/account/sessions\")]",
        "#[post(\"/account/sessions/{id}/revoke\")]",
        "#[post(\"/account/sessions/revoke-others\")]",
        "#[post(\"/account/sessions/{id}/label\")]",
    ] {
        assert!(routes.contains(needle), "routes/auth.rs missing: {needle}");
    }
    // htmx-powered page with a one-click "sign out everywhere else".
    assert!(
        routes.contains("hx-post"),
        "sessions page must use htmx for revocation"
    );
    assert!(
        routes.to_lowercase().contains("sign out everywhere else"),
        "sessions page must offer one-click bulk revocation"
    );

    // main.rs registers the new handlers.
    let main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    for entry in [
        "routes::auth::sessions_page",
        "routes::auth::sessions_revoke",
        "routes::auth::sessions_revoke_others",
        "routes::auth::sessions_label",
    ] {
        assert!(main.contains(entry), "main.rs missing route: {entry}");
    }
}

/// AC5 (password change) — resetting the password revokes existing sessions
/// by default, gated on the `[auth.sessions]` config flag.
#[test]
fn generate_auth_reset_password_revokes_sessions() {
    let (_tmp, project) = fresh_project("auth-sess-reset");
    run_autumn(&project, &["generate", "auth", "User"]);

    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    let reset_body = &routes[routes.find("pub async fn reset_password(").unwrap()..];
    let reset_body = &reset_body[..reset_body.find("\n// ──").unwrap_or(reset_body.len())];
    assert!(
        reset_body.contains("revoke_existing_sessions") || reset_body.contains("user_sessions"),
        "reset_password must revoke existing sessions"
    );
    assert!(
        reset_body.contains("revoke_on_credential_change"),
        "session revocation on password change must be configurable"
    );
    assert!(
        reset_body.contains("insert_into(user_sessions::table)"),
        "reset_password logs the user in and must record the new session in its transaction"
    );
}

/// AC5 (TOTP) — enrollment and disable revoke all *other* sessions by default.
#[test]
fn generate_auth_totp_changes_revoke_other_sessions() {
    let (_tmp, project) = fresh_project("auth-sess-totp");
    run_autumn(&project, &["generate", "auth", "User", "--totp"]);

    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();
    for handler in [
        "pub async fn two_factor_confirm",
        "pub async fn two_factor_disable",
    ] {
        let start = routes
            .find(handler)
            .unwrap_or_else(|| panic!("missing {handler}"));
        let body = &routes[start..];
        let body = &body[..body.find("\n/// `").unwrap_or(body.len())];
        assert!(
            body.contains("token_digest.ne(") || body.contains("revoke_other_sessions"),
            "{handler} must revoke other sessions"
        );
        assert!(
            body.contains("revoke_on_credential_change"),
            "{handler} revocation must be configurable"
        );
    }
    // Completing a TOTP login also records the session row.
    assert!(
        routes.contains("pub async fn login_verify"),
        "missing login_verify"
    );
    let verify = &routes[routes.find("pub async fn login_verify(").unwrap()..];
    assert!(
        verify.contains("record_login_session"),
        "login_verify completes a login and must record the session row"
    );
}

/// AC5 (`WebAuthn`) — passkey add/remove revoke all *other* sessions by default,
/// and passkey login records a session row.
#[test]
fn generate_auth_passkeys_changes_revoke_other_sessions() {
    let (_tmp, project) = fresh_project("auth-sess-passkeys");
    run_autumn(&project, &["generate", "auth", "User", "--passkeys"]);

    let routes = fs::read_to_string(project.join("src/routes/passkeys.rs")).unwrap();
    for handler in [
        "pub async fn passkey_register_finish",
        "pub async fn passkey_revoke",
    ] {
        let start = routes
            .find(handler)
            .unwrap_or_else(|| panic!("missing {handler}"));
        let body = &routes[start..];
        let body = &body[..body.find("\n/// `").unwrap_or(body.len())];
        assert!(
            body.contains("token_digest.ne(") || body.contains("revoke_other_sessions"),
            "{handler} must revoke other sessions"
        );
        assert!(
            body.contains("revoke_on_credential_change"),
            "{handler} revocation must be configurable"
        );
    }
    let login_finish = &routes[routes.find("pub async fn passkey_login_finish(").unwrap()..];
    assert!(
        login_finish.contains("record_login_session"),
        "passkey_login_finish completes a login and must record the session row"
    );
}

/// AC7 — the generated integration tests cover the two-client revocation flow.
#[test]
fn generate_auth_sessions_tests_emitted() {
    let (_tmp, project) = fresh_project("auth-sess-tests");
    run_autumn(&project, &["generate", "auth", "User"]);

    let tests = fs::read_to_string(project.join("tests/auth_sessions.rs")).unwrap();
    for needle in [
        "fn sessions_page_rejects_anonymous",
        "fn revoked_session_next_request_401s",
        "fn revoke_other_sessions_keeps_current_session_alive",
        "/account/sessions",
    ] {
        assert!(
            tests.contains(needle),
            "tests/auth_sessions.rs missing: {needle}"
        );
    }
}

/// AC8 — documentation covers privacy posture for stored IP/UA and how to
/// plug in a custom User-Agent parser.
#[test]
fn generate_auth_sessions_docs_emitted() {
    let (_tmp, project) = fresh_project("auth-sess-docs");
    run_autumn(&project, &["generate", "auth", "User"]);

    let docs = fs::read_to_string(project.join("docs/guide/session-management.md")).unwrap();
    for needle in [
        "## Privacy",
        "retention",
        "parse_user_agent",
        "revoke_on_credential_change",
        "/account/sessions",
        "CREATE TABLE user_sessions",
    ] {
        assert!(
            docs.contains(needle),
            "session-management.md missing: {needle}"
        );
    }
}

/// PR #1176 review hardening: reauth must re-point the tracked session row
/// after rotating the session id (otherwise step-up locks the user out),
/// every protected handler — including GET form pages — must go through the
/// tracked-session gate, and the revocation controls must work without
/// JavaScript (real forms, htmx as progressive enhancement).
#[test]
fn generate_auth_sessions_review_hardening() {
    let (_tmp, project) = fresh_project("auth-sess-hardening");
    run_autumn(&project, &["generate", "auth", "User"]);
    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();

    // P1: reauth rotates the session id and must rebind the tracked row to
    // the new digest, after the rotation.
    let reauth_start = routes
        .find("pub async fn reauth(")
        .expect("missing reauth handler");
    let reauth = &routes[reauth_start..];
    let reauth = &reauth[..reauth.find("\n// ──").unwrap_or(reauth.len())];
    let rotate_at = reauth
        .find("session.rotate_id()")
        .expect("reauth must rotate");
    let rebind_at = reauth
        .find("rebind_tracked_session")
        .expect("reauth must rebind the tracked session row after rotation");
    assert!(
        rotate_at < rebind_at,
        "reauth must rebind AFTER rotating the session id"
    );

    // P2: protected GET form pages validate the tracked row too, so a revoked
    // device's next request 401s no matter which authenticated route it hits.
    for handler in [
        "pub async fn data_export_form",
        "pub async fn delete_account_form",
        "pub async fn reauth_form",
    ] {
        let start = routes
            .find(handler)
            .unwrap_or_else(|| panic!("missing {handler}"));
        let body = &routes[start..];
        let body = &body[..body.find("\n/// `").unwrap_or(body.len())];
        assert!(
            body.contains("require_tracked_session"),
            "{handler} must validate the tracked session row"
        );
    }

    // P2: revocation controls are real POST forms (usable without JS), with
    // htmx attributes for in-place swaps when JS is available.
    assert!(
        routes.contains("form method=\"post\" action=\"/account/sessions/revoke-others\""),
        "bulk revoke must be a real form for non-JS fallback"
    );
    assert!(
        routes.contains("action={ \"/account/sessions/\" (s.id) \"/revoke\" }"),
        "per-session revoke must be a real form for non-JS fallback"
    );
    assert!(
        routes.contains("hx-post=\"/account/sessions/revoke-others\""),
        "bulk revoke keeps htmx enhancement"
    );
}

/// PR #1176 review hardening for `--passkeys`: the registration page and
/// challenge endpoint must also validate the tracked session row.
#[test]
fn generate_auth_passkeys_pages_gated_on_tracked_session() {
    let (_tmp, project) = fresh_project("auth-sess-pk-gate");
    run_autumn(&project, &["generate", "auth", "User", "--passkeys"]);
    let routes = fs::read_to_string(project.join("src/routes/passkeys.rs")).unwrap();

    for handler in [
        "pub async fn passkey_register_page",
        "pub async fn passkey_register_begin",
    ] {
        let start = routes
            .find(handler)
            .unwrap_or_else(|| panic!("missing {handler}"));
        let body = &routes[start..];
        let body = &body[..body.find("\n/// `").unwrap_or(body.len())];
        assert!(
            body.contains("require_tracked_session"),
            "{handler} must validate the tracked session row"
        );
    }
}

// ── AC#2: --live and --live-validation scaffold tests (Issue #1445) ─────────

/// `--live-validation` emits `hx-post`, `hx-trigger`, `hx-target`, `hx-swap`
/// attributes on validated form inputs plus a companion `<span id="…-error">`.
#[test]
fn live_validation_emits_hx_post_and_error_slot() {
    let (_tmp, project) = fresh_project("lv-hx-post");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "body:String",
            "--validate",
            "title=length:min=1,max=200",
            "--live-validation",
        ],
    );

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();

    // A validated text field on `--live-validation` renders via the
    // changeset-aware `text_input_htmx` helper (issue #1124), which wires up
    // its own hx-post/hx-trigger/hx-target/hx-swap and inline error block —
    // the generator no longer hand-rolls these attributes. `title` is
    // non-nullable, so it keeps `required`/`aria-required` via the
    // `required_text_input_htmx` variant.
    assert!(
        routes.contains(
            "autumn_web::form::required_text_input_htmx(&changeset, \"title\", \"Title\", &paths::validate_title())"
        ),
        "create form must render the validated title input via required_text_input_htmx with a typed path helper:\n{routes}"
    );
    // body field (not validated, but required) must use required_text_input.
    assert!(
        routes.contains("autumn_web::form::required_text_input(&changeset, \"body\", \"Body\")"),
        "unvalidated required body input must use required_text_input:\n{routes}"
    );
    assert!(
        !routes.contains("autumn_web::form::text_input_htmx(&changeset, \"body\""),
        "unvalidated body input must not use text_input_htmx:\n{routes}"
    );
}

/// `--live-validation` emits a `validate_{field}` route handler that decodes
/// the full form, validates through the same `{Pascal}Form`/`Changeset`
/// machinery as `create`/`update` (issue #1124 follow-up), and returns
/// `text_input_htmx`'s full field wrapper — never a bare error span, which
/// would delete the input on htmx's `hx-swap="outerHTML"`.
#[test]
fn live_validation_emits_validate_handler_with_real_rules() {
    let (_tmp, project) = fresh_project("lv-validate-handler");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "site:String",
            "email:String",
            "--validate",
            "title=length:min=1,max=200",
            "--validate",
            "site=url",
            "--validate",
            "email=email",
            "--live-validation",
        ],
    );

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();

    for field in ["title", "site", "email"] {
        assert!(
            routes.contains(&format!("pub async fn validate_{field}(")),
            "routes must contain a validate_{field} handler:\n{routes}"
        );
        // All three fields are non-nullable, so the required htmx variant
        // keeps the `required`/`aria-required` signal through the swap too.
        assert!(
            routes.contains(&format!(
                "autumn_web::form::required_text_input_htmx(&changeset, \"{field}\""
            )),
            "validate_{field} must return the full required_text_input_htmx wrapper, \
             not a bare error span:\n{routes}"
        );
    }
    // Each handler decodes the whole form (htmx posts the entire form via
    // `hx-include="closest form"`) and validates through the derived
    // `#[validate(...)]` rules on `PostForm` — one rule implementation, not a
    // hand-rolled duplicate per field.
    assert_eq!(
        routes
            .matches("let Ok(form) = decode_form(body) else")
            .count(),
        3,
        "every validate_{{field}} handler must decode via the shared decode_form:\n{routes}"
    );
    assert!(
        routes.contains("#[validate(length(min = 1, max = 200))]\n    pub title: String"),
        "PostForm must carry the length rule for validator::Validate to enforce:\n{routes}"
    );
}

/// Without `--live-validation` the routes file contains no validate handlers
/// and no hx-post attributes on form inputs.
#[test]
fn without_live_validation_no_hx_attrs() {
    let (_tmp, project) = fresh_project("no-lv");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "--validate",
            "title=length:min=1,max=200",
        ],
    );

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();

    assert!(
        !routes.contains("hx-post"),
        "routes without --live-validation must not have hx-post:\n{routes}"
    );
    assert!(
        !routes.contains("validate_title"),
        "routes without --live-validation must not have validate_title handler:\n{routes}"
    );
}

/// `--live-validation` without `--live` still loads the htmx script tag so
/// that validation requests can fire.
#[test]
fn live_validation_without_live_loads_htmx_script() {
    let (_tmp, project) = fresh_project("lv-no-live-htmx");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "--validate",
            "title=length:min=1,max=200",
            "--live-validation",
        ],
    );

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();

    assert!(
        routes.contains("HTMX_JS_PATH"),
        "layout must include htmx script when --live-validation is set:\n{routes}"
    );

    // Cargo.toml must have htmx + maud features even when --live is not set,
    // because the generated validate handlers return Markup and the layout
    // references HTMX_JS_PATH.
    let cargo = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(
        cargo.contains("\"htmx\"") || cargo.contains("htmx"),
        "Cargo.toml must include autumn-web htmx feature for --live-validation:\n{cargo}"
    );
    assert!(
        cargo.contains("\"maud\"") || cargo.contains("maud"),
        "Cargo.toml must include autumn-web maud feature for --live-validation:\n{cargo}"
    );
}

/// `--live` emits a `LiveFragment` impl for the model and a `broadcasts`
/// attribute on the repository.
#[test]
fn live_scaffold_emits_live_fragment_and_broadcasts() {
    let (_tmp, project) = fresh_project("live-frag");
    run_autumn(
        &project,
        &["generate", "scaffold", "Post", "title:String", "--live"],
    );

    let repo = fs::read_to_string(project.join("src/repositories/post.rs")).unwrap();
    assert!(
        repo.contains("broadcasts = true"),
        "repository must have broadcasts attribute under --live:\n{repo}"
    );
    // LiveFragment impl is co-located in the repository file next to the
    // `#[repository]` annotation that uses it.
    assert!(
        repo.contains("impl autumn_web::live::LiveFragment for Post"),
        "repository must contain LiveFragment impl under --live:\n{repo}"
    );
    // insert_swap must target the list container so new rows are appended
    // rather than replacing a non-existent element on remote clients.
    assert!(
        repo.contains("fn insert_swap()") && repo.contains("OobMethod::BeforeEnd"),
        "LiveFragment impl must override insert_swap() with BeforeEnd targeting the list container:\n{repo}"
    );
    // render_fragment must include a show-page link so live rows are navigable.
    // The URL goes through the routes module's typed path helper (issue #1133).
    assert!(
        repo.contains("a href=(crate::routes::posts::paths::show(self.id))"),
        "render_fragment must include a show link href via the typed path helper:\n{repo}"
    );
}

/// `--live` wires the index list container to an SSE stream so the list
/// updates via push events.
#[test]
fn live_scaffold_index_uses_sse_list_and_stream_route() {
    let (_tmp, project) = fresh_project("live-sse");
    run_autumn(
        &project,
        &["generate", "scaffold", "Post", "title:String", "--live"],
    );

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();

    assert!(
        routes.contains("hx-ext=\"sse\""),
        "index list must have hx-ext=\"sse\" under --live:\n{routes}"
    );
    assert!(
        routes.contains("sse-connect=(paths::events())"),
        "index list must connect to the SSE stream endpoint via the typed path helper:\n{routes}"
    );
    assert!(
        routes.contains("pub async fn events"),
        "routes must contain the stream handler:\n{routes}"
    );
}

/// `--live` layout must include the idiomorph script, enable morph on the
/// body, and wire the SSE container with hx-swap="none" so that OOB fragments
/// are processed without the in-band innerHTML swap clearing the list.
#[test]
fn live_layout_references_idiomorph_and_morph() {
    let (_tmp, project) = fresh_project("live-morph");
    run_autumn(
        &project,
        &["generate", "scaffold", "Post", "title:String", "--live"],
    );

    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();

    assert!(
        routes.contains("IDIOMORPH_JS_PATH"),
        "layout <head> must include the idiomorph script under --live:\n{routes}"
    );
    assert!(
        routes.contains(r#"body hx-ext="morph""#),
        "layout <body> must carry hx-ext=\"morph\" under --live:\n{routes}"
    );
    assert!(
        routes.contains(r#"hx-swap="none""#),
        "SSE list container must use hx-swap=\"none\" under --live:\n{routes}"
    );
}

/// `--api --live` emits the SSE stream handler inside the repository file
/// (there is no routes file for API scaffolds) and renders fragment items as
/// plain ids rather than links (no HTML show page exists).
#[test]
fn live_api_scaffold_emits_stream_handler_in_repository() {
    let (_tmp, project) = fresh_project("live-api");
    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "--api",
            "--live",
        ],
    );

    // API scaffolds produce no routes file — the stream handler lives in the
    // repository instead.
    assert!(
        !project.join("src/routes/posts.rs").is_file(),
        "--api scaffold must not create a routes file"
    );

    let repo = fs::read_to_string(project.join("src/repositories/post.rs")).unwrap();

    // The stream handler must be appended to the repository file.
    assert!(
        repo.contains("pub async fn stream("),
        "repository must contain stream handler under --api --live:\n{repo}"
    );
    assert!(
        repo.contains("GET /posts/stream"),
        "repository must document the stream route path:\n{repo}"
    );
    assert!(
        repo.contains("autumn_web::sse::stream(&state, \"posts\")"),
        "stream handler must delegate to sse::stream:\n{repo}"
    );

    // LiveFragment impl is still present but renders plain ids (no show link).
    assert!(
        repo.contains("impl autumn_web::live::LiveFragment for Post"),
        "repository must contain LiveFragment impl under --api --live:\n{repo}"
    );
    assert!(
        !repo.contains("a href=(format!(\"/posts/"),
        "API LiveFragment must NOT emit a show-page link (no HTML routes):\n{repo}"
    );
    assert!(
        repo.contains("(self.id)"),
        "API LiveFragment render_fragment must emit plain id:\n{repo}"
    );
}

/// PR #1176 Codex round 2: login flows must delete the consumed session's
/// tracked row before rotating (no phantom devices), the password-reset
/// commit must be atomic with its session revocation (no consumed-token 500
/// limbo), and the TOTP reset-commit path gets the same treatment.
#[test]
fn generate_auth_sessions_codex_round2() {
    let (_tmp, project) = fresh_project("auth-sess-codex2");
    run_autumn(&project, &["generate", "auth", "User"]);
    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();

    let body_of = |handler: &str| {
        let start = routes
            .find(handler)
            .unwrap_or_else(|| panic!("missing {handler}"));
        let body = &routes[start..];
        &body[..body.find("\n/// `").unwrap_or(body.len())]
    };

    // Re-login from an already-tracked browser: the old row must be removed
    // BEFORE the rotation that destroys its session id.
    let login = body_of("pub async fn login(");
    let untrack_at = login
        .find("untrack_current_session")
        .expect("login must untrack the consumed session row");
    let rotate_at = login
        .find("session.rotate_id()")
        .expect("login must rotate");
    assert!(
        untrack_at < rotate_at,
        "login must untrack BEFORE rotating the session id"
    );
    for handler in [
        "pub async fn confirm_email(",
        "pub async fn reset_password(",
    ] {
        assert!(
            body_of(handler).contains("untrack_current_session"),
            "{handler} rotates while logging in and must untrack the old row"
        );
    }
    assert!(
        body_of("pub async fn logout(").contains("untrack_current_session"),
        "logout shares the untrack helper"
    );

    // Password change + session revocation + token consumption are one
    // transaction: a failure rolls everything back so the reset link
    // remains usable, and no path leaves sessions unrevoked after the
    // password actually changed.
    let reset = body_of("pub async fn reset_password(");
    assert!(
        reset.contains(".transaction"),
        "reset_password must commit password + revocation atomically"
    );
    assert!(
        reset.contains("revoke_on_credential_change") && reset.contains("user_sessions"),
        "reset_password revocation must stay config-gated and target user_sessions"
    );
}

/// PR #1176 Codex round 2 (`--totp`): the post-enrollment/disable revocation
/// happens inside the existing transactions so a revocation failure can
/// never 500 after the credential change committed (which would hide the
/// one-time recovery codes), and the deferred-reset commit in `login_verify`
/// is atomic with its revocation.
#[test]
fn generate_auth_totp_revocation_is_atomic() {
    let (_tmp, project) = fresh_project("auth-sess-totp-atomic");
    run_autumn(&project, &["generate", "auth", "User", "--totp"]);
    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();

    let body_of = |handler: &str| {
        let start = routes
            .find(handler)
            .unwrap_or_else(|| panic!("missing {handler}"));
        let body = &routes[start..];
        &body[..body.find("\n/// `").unwrap_or(body.len())]
    };

    for handler in [
        "pub async fn two_factor_confirm(",
        "pub async fn two_factor_disable(",
    ] {
        let body = body_of(handler);
        assert!(
            body.contains("revoke_on_credential_change"),
            "{handler} revocation must stay config-gated"
        );
        // The other-sessions delete lives inside the credential txn.
        assert!(
            body.contains("token_digest.ne("),
            "{handler} must revoke other sessions inside its transaction"
        );
        assert!(
            !body.contains("revoke_other_sessions(&mut *db"),
            "{handler} must not revoke outside the transaction (a post-commit \
             failure would 500 after the credential change)"
        );
    }

    let verify = body_of("pub async fn login_verify(");
    assert!(
        verify.contains(".transaction"),
        "login_verify's deferred password-reset commit must be atomic with revocation"
    );
}

/// PR #1176 Codex round 3: signup must survive an already-authenticated
/// browser (rebind the tracked row across its rotation), the password-reset
/// transaction must include the new session-row insert (no 500 after the
/// reset link is consumed), and passkey changes must revoke other sessions
/// in the same transaction as the credential change.
#[test]
fn generate_auth_sessions_codex_round3() {
    let (_tmp, project) = fresh_project("auth-sess-codex3");
    run_autumn(&project, &["generate", "auth", "User"]);
    let routes = fs::read_to_string(project.join("src/routes/auth.rs")).unwrap();

    let body_of = |handler: &str| {
        let start = routes
            .find(handler)
            .unwrap_or_else(|| panic!("missing {handler}"));
        let body = &routes[start..];
        &body[..body.find("\n/// `").unwrap_or(body.len())]
    };

    // signup: rotation preserves a previous login's keys, so the tracked row
    // must be re-pointed at the new session id.
    let signup = body_of("pub async fn signup(");
    let rotate_at = signup
        .find("session.rotate_id()")
        .expect("signup must rotate");
    let rebind_at = signup
        .find("rebind_tracked_session")
        .expect("signup must rebind the tracked row across its rotation");
    assert!(
        rotate_at < rebind_at,
        "signup must rebind AFTER rotating the session id"
    );

    // reset_password: the new session row is inserted inside the same
    // transaction as the password change + token consumption, so a failure
    // rolls everything back and the link stays usable.
    let reset = body_of("pub async fn reset_password(");
    assert!(
        reset.contains("insert_into(user_sessions::table)"),
        "reset_password must insert the new session row inside its transaction"
    );
    assert!(
        !reset.contains("record_login_session"),
        "reset_password must not record the session outside the transaction"
    );

    // The UA parse stays funneled through one documented helper.
    assert!(
        routes.contains("pub async fn build_session_row"),
        "session-row construction must be a shared helper"
    );
}

/// PR #1176 Codex round 3 (`--passkeys`): the credential change and the
/// other-sessions revocation commit atomically — the documented
/// revoke-on-credential-change guarantee can never be silently skipped, and
/// a failure rolls back the credential change instead of 500ing after it.
#[test]
fn generate_auth_passkeys_revocation_is_atomic() {
    let (_tmp, project) = fresh_project("auth-sess-pk-atomic");
    run_autumn(&project, &["generate", "auth", "User", "--passkeys"]);
    let routes = fs::read_to_string(project.join("src/routes/passkeys.rs")).unwrap();

    let body_of = |handler: &str| {
        let start = routes
            .find(handler)
            .unwrap_or_else(|| panic!("missing {handler}"));
        let body = &routes[start..];
        &body[..body.find("\n/// `").unwrap_or(body.len())]
    };

    for handler in [
        "pub async fn passkey_register_finish(",
        "pub async fn passkey_revoke(",
    ] {
        let body = body_of(handler);
        assert!(
            body.contains(".transaction"),
            "{handler} must commit the credential change and revocation atomically"
        );
        assert!(
            body.contains("token_digest.ne("),
            "{handler} must revoke other sessions inside the transaction"
        );
        assert!(
            body.contains("revoke_on_credential_change"),
            "{handler} revocation must stay config-gated"
        );
    }
}

// ── autumn generate wizard (issue #832) ──────────────────────────────────────

#[test]
#[allow(clippy::too_many_lines)]
fn generate_wizard_creates_expected_files() {
    let (_tmp, project) = fresh_project("wizard-app");
    run_autumn(
        &project,
        &[
            "generate", "wizard", "checkout", "shipping", "payment", "review",
        ],
    );

    // ── main wizard file ──────────────────────────────────────────────
    let wizard = fs::read_to_string(project.join("src/wizards/checkout.rs")).unwrap();

    // Wizard configuration constants
    assert!(
        wizard.contains("pub const WIZARD_NAME: &str = \"checkout\";"),
        "wizard file missing WIZARD_NAME constant"
    );
    assert!(
        wizard.contains("pub const STEPS: &[&str] = &[\"shipping\", \"payment\", \"review\"];"),
        "wizard file missing STEPS constant with all step names"
    );
    assert!(
        wizard.contains("pub fn wizard_context(session: Session) -> WizardContext"),
        "wizard file missing wizard_context helper"
    );

    // Step structs
    for (pascal_struct, snake_step) in [
        ("ShippingForm", "shipping"),
        ("PaymentForm", "payment"),
        ("ReviewForm", "review"),
    ] {
        assert!(
            wizard.contains(&format!("pub struct {pascal_struct}")),
            "wizard file missing step struct: {pascal_struct}"
        );
        assert!(
            wizard.contains("Serialize, Deserialize"),
            "step struct for {snake_step} must derive Serialize and Deserialize"
        );
    }

    // GET + POST handlers for every step
    for step in ["shipping", "payment", "review"] {
        assert!(
            wizard.contains(&format!("#[get(\"/checkout/{step}\")]")),
            "wizard file missing GET route attribute for step: {step}"
        );
        assert!(
            wizard.contains(&format!("pub async fn show_{step}(")),
            "wizard file missing show_{step} handler"
        );
        assert!(
            wizard.contains(&format!("#[post(\"/checkout/{step}\")]")),
            "wizard file missing POST route attribute for step: {step}"
        );
        assert!(
            wizard.contains(&format!("pub async fn submit_{step}(")),
            "wizard file missing submit_{step} handler"
        );
    }

    // Confirm is a GET (summary before final commit)
    assert!(
        wizard.contains("#[get(\"/checkout/confirm\")]"),
        "wizard file missing GET /checkout/confirm route"
    );
    assert!(
        wizard.contains("pub async fn show_confirm("),
        "wizard file missing show_confirm handler"
    );

    // Commit and cancel are POST-only
    assert!(
        wizard.contains("#[post(\"/checkout/commit\")]"),
        "commit must be POST, not GET"
    );
    assert!(
        wizard.contains("pub async fn commit("),
        "wizard file missing commit handler"
    );
    assert!(
        wizard.contains("#[post(\"/checkout/cancel\")]"),
        "cancel must be POST, not GET"
    );
    assert!(
        wizard.contains("pub async fn cancel("),
        "wizard file missing cancel handler"
    );

    // Guard and progress rendering
    assert!(
        wizard.contains("wizard.guard_step("),
        "step handlers must call guard_step"
    );
    assert!(
        wizard.contains("wizard_progress("),
        "step handlers must render wizard_progress"
    );

    // CSRF uses optional extractors
    assert!(
        wizard.contains("csrf: Option<CsrfToken>"),
        "GET step handlers must use optional CsrfToken"
    );
    assert!(
        wizard.contains("csrf_field: Option<CsrfFormField>"),
        "GET step handlers must use optional CsrfFormField"
    );

    // ChangesetForm used for step submission
    assert!(
        wizard.contains("use autumn_web::form::ChangesetForm;"),
        "wizard file must import ChangesetForm"
    );

    // 422 on invalid data
    assert!(
        wizard.contains("StatusCode::UNPROCESSABLE_ENTITY"),
        "submit handlers must return 422 on validation failure"
    );

    // wizard.clear() called on both commit and cancel
    assert_eq!(
        wizard.matches("wizard.clear()").count(),
        2,
        "wizard.clear() must be called in both commit and cancel handlers"
    );

    // ── mod.rs ────────────────────────────────────────────────────────
    let mod_rs = fs::read_to_string(project.join("src/wizards/mod.rs")).unwrap();
    assert!(
        mod_rs.contains("pub mod checkout;"),
        "src/wizards/mod.rs missing pub mod checkout"
    );

    // ── integration test skeleton ─────────────────────────────────────
    let test = fs::read_to_string(project.join("tests/checkout_wizard.rs")).unwrap();
    assert!(
        test.contains("checkout_wizard_happy_path"),
        "test file missing checkout_wizard_happy_path test"
    );
    assert!(
        test.contains("checkout_step2_invalid_rerender_with_errors"),
        "test file missing step2 invalid-data test"
    );
    assert!(
        test.contains("checkout_cancel_clears_session_state"),
        "test file missing cancel test"
    );
    assert!(
        test.contains(".wizard-progress"),
        "test file must reference the .wizard-progress CSS selector"
    );
    assert!(
        test.contains("#[ignore"),
        "generated tests must be #[ignore] until the user fills them in"
    );
}

#[test]
fn generate_wizard_dry_run_writes_nothing() {
    let (_tmp, project) = fresh_project("wizard-dry-app");
    let (stdout, _) = run_autumn(
        &project,
        &[
            "generate",
            "wizard",
            "checkout",
            "shipping",
            "payment",
            "--dry-run",
        ],
    );
    assert!(
        stdout.contains("Dry run"),
        "expected Dry run header; got: {stdout}"
    );
    assert!(
        !project.join("src/wizards/checkout.rs").exists(),
        "dry run must not create the wizard file"
    );
    assert!(
        !project.join("src/wizards/mod.rs").exists(),
        "dry run must not create mod.rs"
    );
    assert!(
        !project.join("tests/checkout_wizard.rs").exists(),
        "dry run must not create the test file"
    );
}

#[test]
fn generate_wizard_collision_without_force_fails() {
    let (_tmp, project) = fresh_project("wizard-collide-app");
    run_autumn(
        &project,
        &["generate", "wizard", "checkout", "shipping", "payment"],
    );
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &["generate", "wizard", "checkout", "shipping", "payment"],
    );
    assert_eq!(code, Some(1), "re-run without --force must exit 1");
    assert!(
        stderr.contains("would overwrite") || stderr.contains("checkout.rs"),
        "must report collision; got stderr: {stderr}"
    );
}

#[test]
fn generate_wizard_force_overwrites() {
    let (_tmp, project) = fresh_project("wizard-force-app");
    run_autumn(
        &project,
        &["generate", "wizard", "checkout", "shipping", "payment"],
    );
    let wizard_path = project.join("src/wizards/checkout.rs");
    let original = fs::read_to_string(&wizard_path).unwrap();
    fs::write(&wizard_path, "// corrupted").unwrap();
    run_autumn(
        &project,
        &[
            "generate", "wizard", "checkout", "shipping", "payment", "--force",
        ],
    );
    let regenerated = fs::read_to_string(&wizard_path).unwrap();
    assert_eq!(
        regenerated, original,
        "--force must restore original content"
    );
}

#[test]
fn generate_wizard_mod_rs_is_idempotent() {
    let (_tmp, project) = fresh_project("wizard-idempotent-app");
    run_autumn(
        &project,
        &[
            "generate", "wizard", "checkout", "shipping", "payment", "--force",
        ],
    );
    run_autumn(
        &project,
        &[
            "generate", "wizard", "checkout", "shipping", "payment", "--force",
        ],
    );
    let mod_rs = fs::read_to_string(project.join("src/wizards/mod.rs")).unwrap();
    assert_eq!(
        mod_rs.matches("pub mod checkout;").count(),
        1,
        "mod.rs must not gain duplicate pub mod declarations on re-run"
    );
}

#[test]
fn generate_wizard_rejects_fewer_than_two_steps() {
    let (_tmp, project) = fresh_project("wizard-toofew-app");
    let (_, stderr, code) =
        run_autumn_failing(&project, &["generate", "wizard", "checkout", "shipping"]);
    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("at least") || stderr.contains('2'),
        "error must mention the minimum step requirement; got: {stderr}"
    );
}

#[test]
fn generate_wizard_rejects_reserved_step_names() {
    let (_tmp, project) = fresh_project("wizard-reserved-app");
    for reserved in ["confirm", "commit", "cancel"] {
        let (_, stderr, code) = run_autumn_failing(
            &project,
            &["generate", "wizard", "checkout", reserved, "payment"],
        );
        assert_eq!(
            code,
            Some(1),
            "reserved step name '{reserved}' must be rejected"
        );
        assert!(
            stderr.contains(reserved) || stderr.contains("reserved"),
            "error must mention the reserved name '{reserved}'; got: {stderr}"
        );
    }
}

#[test]
fn generate_wizard_rejects_step_name_with_hyphen() {
    let (_tmp, project) = fresh_project("wizard-hyphen-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &["generate", "wizard", "checkout", "ship-ping", "payment"],
    );
    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("ship-ping") || stderr.contains("only ASCII"),
        "error must mention the invalid step name; got: {stderr}"
    );
}

#[test]
fn generate_wizard_rejects_duplicate_step_names() {
    let (_tmp, project) = fresh_project("wizard-dupe-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &["generate", "wizard", "checkout", "shipping", "shipping"],
    );
    assert_eq!(code, Some(1));
    assert!(
        stderr.contains("shipping") || stderr.contains("duplicate"),
        "error must mention the duplicate step name; got: {stderr}"
    );
}

#[test]
fn generate_wizard_rejects_rust_keyword_as_name() {
    let (_tmp, project) = fresh_project("wizard-keyword-app");
    // "type" normalizes to the Rust keyword `type`; `pub mod type;` is invalid Rust.
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &["generate", "wizard", "type", "shipping", "payment"],
    );
    assert_eq!(code, Some(1), "Rust keyword wizard name must be rejected");
    assert!(
        stderr.contains("keyword") || stderr.contains("type"),
        "error must mention the keyword issue; got: {stderr}"
    );
}

#[test]
fn generate_wizard_rejects_rust_keyword_as_step_name() {
    let (_tmp, project) = fresh_project("wizard-keyword-step-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &["generate", "wizard", "checkout", "mod", "payment"],
    );
    assert_eq!(code, Some(1), "Rust keyword step name must be rejected");
    assert!(
        stderr.contains("keyword") || stderr.contains("mod"),
        "error must mention the keyword issue; got: {stderr}"
    );
}

#[test]
fn generate_wizard_rejects_underscore_only_name() {
    let (_tmp, project) = fresh_project("wizard-underscore-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &["generate", "wizard", "_", "shipping", "payment"],
    );
    assert_eq!(
        code,
        Some(1),
        "underscore-only wizard name must be rejected"
    );
    assert!(
        stderr.contains('_') || stderr.contains("letter") || stderr.contains("digit"),
        "error must mention the invalid name; got: {stderr}"
    );
}

#[test]
fn generate_wizard_rejects_gen_keyword() {
    let (_tmp, project) = fresh_project("wizard-gen-app");
    let (_, stderr, code) = run_autumn_failing(
        &project,
        &["generate", "wizard", "gen", "shipping", "payment"],
    );
    assert_eq!(
        code,
        Some(1),
        "'gen' (Rust 2024 reserved keyword) must be rejected"
    );
    assert!(
        stderr.contains("keyword") || stderr.contains("gen"),
        "error must mention the keyword issue; got: {stderr}"
    );
}

// ── autumn generate scaffold --sharded integration tests ─────────────────────

#[test]
fn generate_sharded_scaffold_in_fresh_project() {
    let (_tmp, project) = fresh_project("sharded-scaffold-app");

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Account",
            "shard_id:i64",
            "name:String",
            "--sharded",
        ],
    );

    // Model file: must have #[shard_key = "tenant_id"] or #[shard_key = "shard_id"]
    // (shard_id present, tenant_id absent → fallback to id; but shard_id is not tenant_id,
    //  so no tenant_id field → default key is "id")
    // With shard_id but no tenant_id field, default key is "id"
    let model = fs::read_to_string(project.join("src/models/account.rs")).unwrap();
    assert!(
        model.contains("#[shard_key = \"id\"]"),
        "model must have #[shard_key = \"id\"] (default when no tenant_id field):\n{model}"
    );
    assert!(
        model.contains("#[autumn_web::model]"),
        "model must have #[autumn_web::model] attr:\n{model}"
    );

    // Routes file: must use ShardedDb not Db
    let routes = fs::read_to_string(project.join("src/routes/accounts.rs")).unwrap();
    assert!(
        routes.contains("use autumn_web::sharding::ShardedDb"),
        "routes must import ShardedDb:\n{routes}"
    );
    assert!(
        routes.contains("mut db: ShardedDb"),
        "routes must use ShardedDb in handler signatures:\n{routes}"
    );
    assert!(
        routes.contains("from_shard(&db)"),
        "routes index must use from_shard(&db):\n{routes}"
    );
    assert!(
        !routes.contains("mut db: Db"),
        "routes must not use bare Db extractor when sharded:\n{routes}"
    );

    // Repository file: must have shard-aware doc note
    let repo = fs::read_to_string(project.join("src/repositories/account.rs")).unwrap();
    assert!(
        repo.contains("from_shard"),
        "repository must mention from_shard in doc comment:\n{repo}"
    );

    // Migration: must have shard target comment
    let migrations: Vec<_> = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_create_accounts")
        })
        .collect();
    assert_eq!(
        migrations.len(),
        1,
        "expected one create_accounts migration"
    );
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(
        up.contains("autumn migrate --shard"),
        "up.sql must mention `autumn migrate --shard`:\n{up}"
    );
}

#[test]
fn generate_sharded_scaffold_with_tenant_id_field_uses_tenant_id_as_default_key() {
    let (_tmp, project) = fresh_project("sharded-tenant-app");

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Booking",
            "tenant_id:i64",
            "title:String",
            "--sharded",
        ],
    );

    let model = fs::read_to_string(project.join("src/models/booking.rs")).unwrap();
    assert!(
        model.contains("#[shard_key = \"tenant_id\"]"),
        "model must default shard_key to tenant_id when that field is present:\n{model}"
    );
}

#[test]
fn generate_sharded_scaffold_with_explicit_shard_key() {
    let (_tmp, project) = fresh_project("sharded-explicit-app");

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Widget",
            "org_id:i64",
            "label:String",
            "--sharded",
            "--shard-key",
            "org_id",
        ],
    );

    let model = fs::read_to_string(project.join("src/models/widget.rs")).unwrap();
    assert!(
        model.contains("#[shard_key = \"org_id\"]"),
        "model must use explicitly supplied --shard-key:\n{model}"
    );
}

#[test]
fn generate_sharded_scaffold_rejects_bogus_shard_key() {
    let (_tmp, project) = fresh_project("sharded-bogus-app");

    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "Widget",
            "label:String",
            "--sharded",
            "--shard-key",
            "bogus",
        ],
    );
    assert_eq!(
        code,
        Some(1),
        "--shard-key with non-existent field must fail"
    );
    assert!(
        stderr.contains("bogus"),
        "error must mention the invalid field name; got: {stderr}"
    );
}

/// Slow end-to-end check: scaffold a sharded project, patch Cargo.toml to the
/// local autumn-web, and `cargo check --tests` the result. Verifies that
/// `use autumn_web::sharding::ShardedDb` resolves, `#[shard_key]` compiles
/// (requires Track A), and `from_shard` typechecks.
///
/// Requires Track A (`#[shard_key]` in `#[model]` macro) to be merged first.
/// Run with: `cargo test -p autumn-cli -- --ignored generated_sharded_scaffold_cargo_checks`
#[test]
#[ignore = "slow: cargo-checks a fresh sharded project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_sharded_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("sharded-build");

    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Account",
            "shard_id:i64",
            "name:String",
            "--sharded",
        ],
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated sharded scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Slow end-to-end check: scaffold a `--searchable` (full-text search) project,
/// patch Cargo.toml to the local autumn-web, and `cargo check --tests` the
/// result. Verifies that the merged FTS codegen (issue #1319/#1825) compiles:
/// the `#[searchable]` model attributes, the `searchable` repository option,
/// the generated `{Model}SearchQuery` extractor type, and the `search_vector`
/// migration all typecheck against this workspace's `autumn-web`.
///
/// Uses a plain searchable model (no owner scoping). The owner-scoped +
/// searchable combination is covered separately by
/// [`generated_owner_searchable_scaffold_cargo_checks`] (issue #1841).
///
/// Run with: `cargo test -p autumn-cli -- --ignored generated_searchable_scaffold_cargo_checks`
#[test]
#[ignore = "slow: cargo-checks a fresh searchable project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_searchable_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("searchable-build");

    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "body:Text",
            "--searchable",
            "title,body",
        ],
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated searchable scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Issue #1841: the critical proof that lifting the owner-scoped `--searchable`
/// rejection produces a COMPILING app whose search/index are safely owner-scoped.
///
/// Scaffolds `Post title:String body:Text author_id:i64 --searchable` — an owner
/// column (`author_id`) AND full-text search, the exact combination the
/// generator REJECTED before #1841. The repository macro now emits owner-filtered
/// `list_scoped` / `search_page_scoped`, and the generated owner-scoped index +
/// `/search` handlers call ONLY those scoped methods. `cargo check --tests`
/// proves the whole owner-scoped FTS codegen (the macro's three-phase
/// owner-filtered `search_page_scoped`, `list_scoped`, and the scoped handlers)
/// type-checks against this workspace's `autumn-web`.
///
/// The security invariant — the owner branch never calls the unscoped
/// `repo.search_page`/`repo.page` — is asserted directly on the generated source
/// here and in the `scaffold.rs` unit tests; this test proves it also COMPILES.
///
/// Run with:
/// `cargo test -p autumn-cli --test generate generated_owner_searchable_scaffold_cargo_checks -- --ignored --exact`
#[test]
#[ignore = "slow: cargo-checks a fresh owner-scoped searchable project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_owner_searchable_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("owner-searchable-build");

    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "body:Text",
            "author_id:i64",
            "--searchable",
            "title,body",
        ],
    );

    // The repository carries `owner = author_id` (→ the macro's scoped codegen).
    let repo = fs::read_to_string(project.join("src/repositories/post.rs")).unwrap();
    assert!(
        repo.contains(", owner = author_id)"),
        "owner-scoped searchable repository must carry `owner = author_id`:\n{repo}"
    );

    // The owner-scoped /search + index call ONLY the scoped methods — never the
    // unscoped `repo.search_page(`/`repo.page(` (the cross-user leak guard).
    let routes = fs::read_to_string(project.join("src/routes/posts.rs")).unwrap();
    assert!(
        routes.contains("repo.search_page_scoped(owner_id, q, &page_req)")
            && routes.contains("repo.list_scoped(owner_id, &list_query, &page_req)"),
        "owner-scoped search/index must call the scoped repository methods:\n{routes}"
    );
    assert!(
        !routes.contains("repo.search_page(") && !routes.contains("repo.page("),
        "SECURITY: owner-scoped searchable routes must NEVER call the unscoped \
         repo.search_page(/repo.page( (cross-user leak):\n{routes}"
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated owner-scoped searchable scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Issue #1841 companion proving the *nullable* owner-column + searchable path
/// compiles: a `user:references?` owner is `Option<i64>`, so the macro's scoped
/// `.eq(owner_id)` filter (typed hydration) and the raw-SQL owner bind must
/// compile against a `Nullable<BigInt>` column. A nullable owner never matches
/// NULL (unowned) rows — semantically correct (unowned rows stay hidden).
///
/// Run with:
/// `cargo test -p autumn-cli --test generate generated_nullable_owner_searchable_scaffold_cargo_checks -- --ignored --exact`
#[test]
#[ignore = "slow: cargo-checks a fresh nullable-owner searchable project — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_nullable_owner_searchable_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("nullable-owner-searchable-build");

    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Note",
            "title:String",
            "body:Text",
            "user:references?",
            "--searchable",
            "title,body",
        ],
    );

    let repo = fs::read_to_string(project.join("src/repositories/note.rs")).unwrap();
    assert!(
        repo.contains(", owner = user_id)"),
        "nullable-owner searchable repository must carry `owner = user_id`:\n{repo}"
    );
    let routes = fs::read_to_string(project.join("src/routes/notes.rs")).unwrap();
    assert!(
        !routes.contains("repo.search_page(") && !routes.contains("repo.page("),
        "SECURITY: nullable-owner searchable routes must NEVER call the unscoped \
         repo.search_page(/repo.page(:\n{routes}"
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated nullable-owner searchable scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Slow end-to-end check: scaffold a `--live` project, patch Cargo.toml to the
/// local autumn-web, and `cargo check --tests` the result. Regression coverage
/// for issue #1853: `--live` sets `broadcasts = true` on the `#[repository]`,
/// which makes the macro synthesize internal hooks whose generated `update`
/// body expands an unqualified `{Pascal}DraftExt::from_patch(...)`. The
/// generated repository file must import `{Pascal}DraftExt` alongside the other
/// model types, or the scaffold fails to compile with
/// `error[E0405]: cannot find trait PostDraftExt in this scope`.
///
/// Run with: `cargo test -p autumn-cli -- --ignored generated_live_scaffold_cargo_checks`
#[test]
#[ignore = "slow: cargo-checks a fresh live scaffold — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_live_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("live-build");

    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "body:Text",
            "--live",
        ],
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated live scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

/// Slow end-to-end check: scaffold a `--soft-delete` project, patch Cargo.toml
/// to the local autumn-web, and `cargo check --tests` the result. Regression
/// coverage for a bug where the generated model's `deleted_at` field lacked
/// `#[default]` (so `NewX`/`UpdateX` required it, but no handler populated
/// it) and was declared in the wrong position relative to `created_at`
/// (mismatching the migration/schema.rs column order the `#[repository]`
/// macro's positional insert-`RETURNING` query relies on).
///
/// Run with: `cargo test -p autumn-cli -- --ignored generated_soft_delete_scaffold_cargo_checks`
#[test]
#[ignore = "slow: cargo-checks a fresh soft-delete scaffold — run with `cargo test -p autumn-cli -- --ignored`"]
fn generated_soft_delete_scaffold_cargo_checks() {
    let (_tmp, project) = fresh_project("soft-delete-build");

    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "body:Text",
            "--soft-delete",
        ],
    );

    let check = Command::new("cargo")
        .args(["check", "--tests"])
        .current_dir(&project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on generated soft-delete scaffold failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
}

// ── UUID primary-key option (issue #1400) ──────────────────────────────────

/// AC1 + AC4: `--id uuid` generates UUID PK in model and migration;
/// default (no flag) still generates BIGSERIAL/i64 byte-for-byte.
#[test]
fn generate_model_uuid_id() {
    let (_tmp, project) = fresh_project("uuid-model-app");

    run_autumn(
        &project,
        &["generate", "model", "Post", "title:String", "--id", "uuid"],
    );

    // AC1: model struct uses uuid::Uuid
    let model = fs::read_to_string(project.join("src/models/post.rs")).unwrap();
    assert!(
        model.contains("pub id: uuid::Uuid,"),
        "model should have `pub id: uuid::Uuid`; got:\n{model}"
    );
    assert!(
        !model.contains("pub id: i64,"),
        "model must not have i64 id with --id uuid; got:\n{model}"
    );

    // AC1: schema.rs uses Uuid type token
    let schema = fs::read_to_string(project.join("src/schema.rs")).unwrap();
    assert!(
        schema.contains("id -> Uuid,"),
        "schema should have `id -> Uuid`; got:\n{schema}"
    );
    assert!(
        !schema.contains("id -> Int8,"),
        "schema must not have Int8 with --id uuid; got:\n{schema}"
    );

    // AC1: migration uses UUID PRIMARY KEY DEFAULT gen_random_uuid()
    let migrations: Vec<_> = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| e.file_name().to_string_lossy().ends_with("_create_posts"))
        .collect();
    assert_eq!(migrations.len(), 1, "expected 1 migration directory");
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(
        up.contains("id UUID PRIMARY KEY DEFAULT gen_random_uuid()"),
        "migration should have UUID PK; got:\n{up}"
    );
    assert!(
        !up.contains("BIGSERIAL"),
        "migration must not have BIGSERIAL with --id uuid; got:\n{up}"
    );
    // migration comment about UUIDv7 trade-off should be present
    assert!(
        up.contains("gen_random_uuid()"),
        "migration should include UUID default; got:\n{up}"
    );
}

/// AC4: default (no `--id`) still generates BIGSERIAL and i64.
#[test]
fn generate_model_default_id_is_bigserial() {
    let (_tmp, project) = fresh_project("default-id-app");

    run_autumn(&project, &["generate", "model", "Post", "title:String"]);

    let model = fs::read_to_string(project.join("src/models/post.rs")).unwrap();
    assert!(
        model.contains("pub id: i64,"),
        "default model should have `pub id: i64`; got:\n{model}"
    );

    let schema = fs::read_to_string(project.join("src/schema.rs")).unwrap();
    assert!(
        schema.contains("id -> Int8,"),
        "default schema should have `id -> Int8`; got:\n{schema}"
    );

    let migrations: Vec<_> = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| e.file_name().to_string_lossy().ends_with("_create_posts"))
        .collect();
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(
        up.contains("id BIGSERIAL PRIMARY KEY"),
        "default migration should have BIGSERIAL; got:\n{up}"
    );
    assert!(
        !up.contains("UUID"),
        "default migration must not have UUID; got:\n{up}"
    );
}

/// `--id uuid` is gated for `generate scaffold`: the generated `#[repository]`
/// REST API is hard-coded to i64 primary keys, so a UUID-keyed scaffold would
/// not compile. The command must reject it up-front with a clear, actionable
/// error and write nothing — pointing users to `generate model --id uuid`.
#[test]
fn generate_scaffold_uuid_id_is_rejected() {
    let (_tmp, project) = fresh_project("uuid-scaffold-app");

    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "--id",
            "uuid",
        ],
    );
    assert_eq!(code, Some(1), "scaffold --id uuid must fail with exit 1");
    assert!(
        stderr.contains("not yet supported") && stderr.contains("generate model"),
        "error must explain the limitation and point to `generate model`; got:\n{stderr}"
    );

    // Nothing should have been written.
    assert!(
        !project.join("src/models/post.rs").exists(),
        "rejected scaffold must not write a model file"
    );
    assert!(
        !project.join("src/repositories/post.rs").exists(),
        "rejected scaffold must not write a repository file"
    );
}

/// AC7: `--id` with an unknown value exits non-zero and lists accepted values.
#[test]
fn generate_model_bad_id_type_errors() {
    let (_tmp, project) = fresh_project("bad-id-app");

    let (_, stderr, code) =
        run_autumn_failing(&project, &["generate", "model", "Post", "--id", "guid"]);
    assert_eq!(code, Some(1), "--id guid must fail with exit 1");
    assert!(
        stderr.contains("guid") && stderr.contains("uuid") && stderr.contains("bigint"),
        "error must list the bad value and accepted values; got: {stderr}"
    );
}

/// AC7: scaffold `--id` with an unknown value exits non-zero.
#[test]
fn generate_scaffold_bad_id_type_errors() {
    let (_tmp, project) = fresh_project("bad-id-scaffold-app");

    let (_, stderr, code) = run_autumn_failing(
        &project,
        &["generate", "scaffold", "Post", "--id", "serial4"],
    );
    assert_eq!(code, Some(1), "--id serial4 must fail with exit 1");
    assert!(
        stderr.contains("serial4") && stderr.contains("uuid") && stderr.contains("bigint"),
        "error must list the bad value and accepted values; got: {stderr}"
    );
}

/// AC6 (Finding #3 fix): `[generate] id` propagates via `--config` even when
/// there is no `[scaffold.Post]` section. Since the resolved type is `uuid`,
/// the scaffold gate then rejects it — proving the project default reaches the
/// scaffold path (rather than being silently dropped or erroring on the missing
/// section).
#[test]
fn generate_scaffold_project_default_uuid_config_only_is_rejected() {
    let (_tmp, project) = fresh_project("project-default-uuid-config-app");

    // No [scaffold.Post] section — only the project-level [generate] default.
    fs::write(
        project.join("autumn.generate.toml"),
        "[generate]\nid = \"uuid\"\n",
    )
    .unwrap();

    let (_, stderr, code) = run_autumn_failing(
        &project,
        &[
            "generate",
            "scaffold",
            "Post",
            "title:String",
            "--config",
            "autumn.generate.toml",
        ],
    );
    assert_eq!(
        code,
        Some(1),
        "scaffold resolving to uuid must fail with exit 1"
    );
    assert!(
        stderr.contains("not yet supported") && stderr.contains("generate model"),
        "error must come from the UUID scaffold gate (proving the [generate] \
         default reached the scaffold path); got:\n{stderr}"
    );
}

/// AC6: `[generate] id = "uuid"` in autumn.generate.toml is auto-discovered
/// (no --config flag needed) and applies to both scaffold and model generation.
#[test]
fn generate_model_project_default_uuid_auto_discovered() {
    let (_tmp, project) = fresh_project("project-default-uuid-auto-app");

    // Write the project-level default without --config; the generator should
    // discover autumn.generate.toml automatically.
    fs::write(
        project.join("autumn.generate.toml"),
        "[generate]\nid = \"uuid\"\n",
    )
    .unwrap();

    // generate model (no --id flag, no --config)
    run_autumn(&project, &["generate", "model", "Post", "title:String"]);

    let model = fs::read_to_string(project.join("src/models/post.rs")).unwrap();
    assert!(
        model.contains("pub id: uuid::Uuid,"),
        "auto-discovered [generate] id=uuid should emit uuid::Uuid; got:\n{model}"
    );

    let migrations: Vec<_> = fs::read_dir(project.join("migrations"))
        .unwrap()
        .filter_map(Result::ok)
        .filter(|e| e.file_name().to_string_lossy().ends_with("_create_posts"))
        .collect();
    let up = fs::read_to_string(migrations[0].path().join("up.sql")).unwrap();
    assert!(
        up.contains("id UUID PRIMARY KEY DEFAULT gen_random_uuid()"),
        "auto-discovered project default migration should have UUID PK; got:\n{up}"
    );
}

/// Codex P2: a defaults-only read (`generate model`, no --config) must parse
/// only `[generate]` and ignore `[scaffold.*]` recipes — so an unrelated
/// checked-in recipe with a typo'd/unsupported key does not break it.
#[test]
fn generate_model_tolerates_malformed_scaffold_recipe_in_config() {
    let (_tmp, project) = fresh_project("malformed-recipe-model-app");

    // [scaffold.Other] uses `index` (unsupported; the key is `indexes`). A full
    // parse would reject it, but `generate model` only reads [generate].
    fs::write(
        project.join("autumn.generate.toml"),
        "[generate]\nid = \"bigint\"\n\n[scaffold.Other]\nfields = [\"x:String\"]\nindex = [\"x\"]\n",
    )
    .unwrap();

    // Must succeed despite the malformed [scaffold.Other] recipe.
    run_autumn(&project, &["generate", "model", "Post", "title:String"]);

    let model = fs::read_to_string(project.join("src/models/post.rs")).unwrap();
    assert!(
        model.contains("pub id: i64,"),
        "[generate] id=bigint should produce an i64 PK; got:\n{model}"
    );
}

/// AC6 + scaffold UUID gate: an auto-discovered `[generate] id = "uuid"` flows
/// into `generate scaffold`, where it is rejected (UUID scaffolds are gated).
/// The project-wide default must not silently produce a broken scaffold.
#[test]
fn generate_scaffold_project_default_uuid_is_rejected() {
    let (_tmp, project) = fresh_project("project-default-uuid-scaffold-auto-app");

    fs::write(
        project.join("autumn.generate.toml"),
        "[generate]\nid = \"uuid\"\n",
    )
    .unwrap();

    // generate scaffold (no --id flag, no --config) — auto-discovers the default.
    let (_, stderr, code) =
        run_autumn_failing(&project, &["generate", "scaffold", "Post", "title:String"]);
    assert_eq!(
        code,
        Some(1),
        "scaffold resolving to uuid must fail with exit 1"
    );
    assert!(
        stderr.contains("not yet supported") && stderr.contains("generate model"),
        "error must explain the limitation and point to `generate model`; got:\n{stderr}"
    );
    assert!(
        !project.join("src/models/post.rs").exists(),
        "rejected scaffold must not write a model file"
    );
}

/// Codex P2: an auto-discovered `autumn.generate.toml` must contribute ONLY the
/// project-level `[generate]` defaults — a checked-in `[scaffold.Post]` recipe
/// must NOT silently apply to an ordinary `generate scaffold` run without
/// `--config`. Here the recipe sets `api = true`; without --config the scaffold
/// must remain a full HTML scaffold (i.e. the recipe is ignored).
#[test]
fn generate_scaffold_auto_discovery_ignores_per_resource_recipe() {
    let (_tmp, project) = fresh_project("auto-discovery-recipe-app");

    // A checked-in per-resource recipe with api = true (TOML-only option).
    fs::write(
        project.join("autumn.generate.toml"),
        "[scaffold.Post]\nfields = [\"name:String\"]\napi = true\n",
    )
    .unwrap();

    // No --config: the [scaffold.Post] recipe must be ignored.
    run_autumn(&project, &["generate", "scaffold", "Post", "title:String"]);

    // A full (non-api) scaffold generates the HTML routes file; an api scaffold
    // does not. Its presence proves api = true was NOT inherited.
    assert!(
        project.join("src/routes/posts.rs").is_file(),
        "auto-discovery must not apply the recipe's api=true (HTML routes expected)"
    );
    // CLI fields win; the recipe's `name` field must not appear.
    let model = fs::read_to_string(project.join("src/models/post.rs")).unwrap();
    assert!(
        model.contains("pub title: String,") && !model.contains("pub name: String,"),
        "CLI fields must be used, not the recipe's fields; got:\n{model}"
    );
}

// ── autumn generate tauri ─────────────────────────────────────────────────────

#[test]
fn generate_tauri_scaffolds_expected_files() {
    let (_tmp, project) = fresh_project("tauri-scaffold-app");
    run_autumn(&project, &["generate", "tauri"]);

    // Core Tauri project files must exist
    assert!(
        project.join("src-tauri/tauri.conf.json").is_file(),
        "src-tauri/tauri.conf.json must be created"
    );
    assert!(
        project.join("src-tauri/Cargo.toml").is_file(),
        "src-tauri/Cargo.toml must be created"
    );
    assert!(
        project.join("src-tauri/build.rs").is_file(),
        "src-tauri/build.rs must be created"
    );
    assert!(
        project.join("src-tauri/src/main.rs").is_file(),
        "src-tauri/src/main.rs must be created"
    );
    assert!(
        project.join("src-tauri/src/lib.rs").is_file(),
        "src-tauri/src/lib.rs must be created"
    );

    // Platform-specific Tauri config overlays (beforeBuildCommand/beforeDevCommand)
    assert!(
        project.join("src-tauri/tauri.linux.conf.json").is_file(),
        "tauri.linux.conf.json must be created"
    );
    assert!(
        project.join("src-tauri/tauri.macos.conf.json").is_file(),
        "tauri.macos.conf.json must be created"
    );
    assert!(
        project.join("src-tauri/tauri.windows.conf.json").is_file(),
        "tauri.windows.conf.json must be created"
    );

    // Staging scripts
    assert!(
        project.join("src-tauri/stage-sidecar.sh").is_file(),
        "stage-sidecar.sh must be created"
    );
    assert!(
        project.join("src-tauri/stage-sidecar.ps1").is_file(),
        "stage-sidecar.ps1 must be created"
    );

    // Icons
    assert!(
        project.join("src-tauri/icons/icon.svg").is_file(),
        "icons/icon.svg must be created"
    );
    for name in &["32x32.png", "128x128.png", "128x128@2x.png", "icon.png"] {
        assert!(
            project.join("src-tauri/icons").join(name).is_file(),
            "icons/{name} must be created"
        );
    }
    assert!(
        project.join("src-tauri/icons/icon.ico").is_file(),
        "icons/icon.ico must be created"
    );
    assert!(
        project.join("src-tauri/icons/icon.icns").is_file(),
        "icons/icon.icns must be created"
    );

    // .gitignore
    assert!(
        project.join("src-tauri/.gitignore").is_file(),
        "src-tauri/.gitignore must be created"
    );
}

#[test]
fn generate_tauri_conf_is_valid_json_with_required_fields() {
    let (_tmp, project) = fresh_project("tauri-conf-app");
    run_autumn(&project, &["generate", "tauri"]);

    let conf = fs::read_to_string(project.join("src-tauri/tauri.conf.json")).unwrap();
    let parsed: serde_json::Value =
        serde_json::from_str(&conf).expect("tauri.conf.json must be valid JSON");

    assert!(parsed["identifier"].is_string(), "must have identifier");
    assert!(parsed["productName"].is_string(), "must have productName");
    assert!(
        parsed["bundle"]["externalBin"].is_array(),
        "must have bundle.externalBin"
    );
    assert!(
        !parsed["bundle"]["externalBin"]
            .as_array()
            .unwrap()
            .is_empty(),
        "externalBin must not be empty"
    );
    assert!(parsed["bundle"]["icon"].is_array(), "must have bundle.icon");
    // beforeBuildCommand lives in platform-specific overlay files, not the main conf.
    assert!(
        parsed["build"]["beforeBuildCommand"].is_null(),
        "beforeBuildCommand must be absent from tauri.conf.json (lives in platform overlays)"
    );
    // The externalBin must reference the app name
    let bins = parsed["bundle"]["externalBin"].as_array().unwrap();
    assert!(
        bins.iter()
            .any(|b| b.as_str().unwrap_or("").contains("tauri-conf-app")),
        "externalBin must reference the app package name"
    );
}

#[test]
fn generate_tauri_shell_cargo_toml_has_own_workspace() {
    let (_tmp, project) = fresh_project("tauri-ws-app");
    run_autumn(&project, &["generate", "tauri"]);

    let cargo = fs::read_to_string(project.join("src-tauri/Cargo.toml")).unwrap();
    assert!(
        cargo.contains("[workspace]"),
        "src-tauri/Cargo.toml must have its own [workspace] so it is independent"
    );
    assert!(cargo.contains("tauri"), "must depend on tauri");
    assert!(
        cargo.contains("tauri-plugin-shell"),
        "must depend on tauri-plugin-shell"
    );
}

#[test]
fn generate_tauri_lib_rs_has_sidecar_lifecycle() {
    let (_tmp, project) = fresh_project("tauri-lifecycle-app");
    run_autumn(&project, &["generate", "tauri"]);

    let lib = fs::read_to_string(project.join("src-tauri/src/lib.rs")).unwrap();
    assert!(
        lib.contains("127.0.0.1:0"),
        "must bind ephemeral loopback port"
    );
    assert!(
        lib.contains("AUTUMN_SERVER__PORT"),
        "must pass port env to sidecar"
    );
    assert!(
        lib.contains("AUTUMN_MANAGED_PG_DATA_DIR"),
        "must pass DB dir env (#1119)"
    );
    assert!(lib.contains(".sidecar("), "must spawn sidecar");
    assert!(lib.contains("/health"), "must poll /health for readiness");
    assert!(lib.contains(".kill()"), "must kill sidecar on window close");
    assert!(
        lib.contains("Destroyed"),
        "must handle WindowEvent::Destroyed"
    );
}

#[test]
fn generate_tauri_prints_prerequisites() {
    let (_tmp, project) = fresh_project("tauri-prereq-app");
    let (stdout, _stderr) = run_autumn(&project, &["generate", "tauri"]);
    assert!(
        stdout.contains("tauri-cli") || stdout.contains("cargo tauri"),
        "must print Tauri CLI prerequisite; got:\n{stdout}"
    );
    assert!(
        stdout.contains("embed-assets"),
        "must mention embed-assets (#1004); got:\n{stdout}"
    );
    assert!(
        stdout.contains("managed-pg"),
        "must mention managed-pg (#1119); got:\n{stdout}"
    );
}

#[test]
fn generate_tauri_is_additive_no_app_files_modified() {
    let (_tmp, project) = fresh_project("tauri-additive-app");
    let original_main = fs::read_to_string(project.join("src/main.rs")).unwrap();
    let original_cargo = fs::read_to_string(project.join("Cargo.toml")).unwrap();

    run_autumn(&project, &["generate", "tauri"]);

    assert_eq!(
        original_main,
        fs::read_to_string(project.join("src/main.rs")).unwrap(),
        "src/main.rs must be unchanged after generate tauri"
    );
    assert_eq!(
        original_cargo,
        fs::read_to_string(project.join("Cargo.toml")).unwrap(),
        "root Cargo.toml must be unchanged after generate tauri"
    );
}

#[test]
fn generate_tauri_dry_run_writes_nothing() {
    let (_tmp, project) = fresh_project("tauri-dry-run-app");
    let (stdout, _stderr) = run_autumn(&project, &["generate", "tauri", "--dry-run"]);
    assert!(
        !project.join("src-tauri").exists(),
        "dry-run must not create src-tauri/; got stdout:\n{stdout}"
    );
    assert!(
        stdout.contains("tauri.conf.json") || stdout.contains("Would create"),
        "dry-run must print the file plan; got:\n{stdout}"
    );
}

#[test]
fn generate_tauri_collision_without_force_exits_nonzero() {
    let (_tmp, project) = fresh_project("tauri-collision-app");
    run_autumn(&project, &["generate", "tauri"]);

    let (_, stderr, code) = run_autumn_failing(&project, &["generate", "tauri"]);
    assert_eq!(code, Some(1), "re-running without --force must exit 1");
    assert!(
        stderr.contains("would overwrite") || stderr.contains("already exists"),
        "must explain collision; got stderr:\n{stderr}"
    );
}

#[test]
fn generate_tauri_force_is_idempotent() {
    let (_tmp, project) = fresh_project("tauri-force-app");
    run_autumn(&project, &["generate", "tauri"]);
    run_autumn(&project, &["generate", "tauri", "--force"]);

    // After --force, the JSON must still be valid
    let conf = fs::read_to_string(project.join("src-tauri/tauri.conf.json")).unwrap();
    let _: serde_json::Value =
        serde_json::from_str(&conf).expect("tauri.conf.json must still be valid after --force");
}

#[test]
fn generate_tauri_reuses_pwa_icon() {
    let (_tmp, project) = fresh_project("tauri-pwa-icon-app");
    // Simulate PWA generator having run
    run_autumn(&project, &["generate", "pwa"]);

    // Read the PWA icon before running the Tauri generator
    let pwa_icon =
        fs::read_to_string(project.join("static/icons/icon.svg")).expect("PWA icon must exist");

    run_autumn(&project, &["generate", "tauri"]);

    // The Tauri icon.svg must contain the same content as the PWA icon
    let tauri_icon = fs::read_to_string(project.join("src-tauri/icons/icon.svg"))
        .expect("src-tauri/icons/icon.svg must be created");
    assert_eq!(
        pwa_icon, tauri_icon,
        "src-tauri/icons/icon.svg must contain the same content as the PWA icon"
    );
    // Original PWA icon must be untouched
    assert!(
        project.join("static/icons/icon.svg").is_file(),
        "PWA icon must still exist"
    );
}

// ── generate controller (issue #1050) ──────────────────────────────────────

/// Re-running `generate controller` against an existing controller must fail
/// (non-zero exit) and leave the first file byte-for-byte intact. Fast — no
/// compile needed.
#[test]
fn controller_rerun_without_force_fails() {
    let (_tmp, project) = fresh_project("controller-rerun-app");
    run_autumn(
        &project,
        &["generate", "controller", "pages", "home", "about"],
    );
    let original = fs::read_to_string(project.join("src/routes/pages.rs")).unwrap();

    let (_out, _err, code) = run_autumn_failing(
        &project,
        &["generate", "controller", "pages", "home", "contact"],
    );
    assert_eq!(code, Some(1), "second run must exit non-zero");
    let after = fs::read_to_string(project.join("src/routes/pages.rs")).unwrap();
    assert_eq!(
        original, after,
        "existing controller file must be untouched"
    );
}

/// Slow end-to-end check: a fresh project + `generate controller` (HTML) must
/// compile with zero edits, and `autumn routes` must list every generated
/// route.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-builds a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn controller_generates_compiles_and_lists_routes() {
    let (_tmp, project) = fresh_project("controller-html-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &[
            "generate",
            "controller",
            "pages",
            "home",
            "about",
            "contact",
        ],
    );

    let build = Command::new("cargo")
        .args(["build"])
        .current_dir(&project)
        .output()
        .expect("failed to run cargo build");
    assert!(
        build.status.success(),
        "cargo build failed on generated controller:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&build.stdout),
        String::from_utf8_lossy(&build.stderr),
    );

    let (stdout, _stderr) = run_autumn(&project, &["routes"]);
    for path in ["/pages/home", "/pages/about", "/pages/contact"] {
        assert!(
            stdout.contains(path),
            "autumn routes must list {path}:\n{stdout}"
        );
    }

    // --force regeneration with a CHANGED action set must prune the stale
    // route entries (`about`) from main.rs, not just append the new one
    // (`services`) — otherwise `routes::pages::about` would reference a
    // handler the overwritten file no longer defines and break the build.
    run_autumn(
        &project,
        &[
            "generate",
            "controller",
            "pages",
            "home",
            "contact",
            "services",
            "--force",
        ],
    );

    let rebuild = Command::new("cargo")
        .args(["build"])
        .current_dir(&project)
        .output()
        .expect("failed to run cargo build after --force regen");
    assert!(
        rebuild.status.success(),
        "cargo build failed after --force regen (stale route entry not pruned?):\n\
         stdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&rebuild.stdout),
        String::from_utf8_lossy(&rebuild.stderr),
    );

    let (stdout2, _stderr2) = run_autumn(&project, &["routes"]);
    for path in ["/pages/home", "/pages/contact", "/pages/services"] {
        assert!(
            stdout2.contains(path),
            "autumn routes must list {path} after regen:\n{stdout2}"
        );
    }
    assert!(
        !stdout2.contains("/pages/about"),
        "the dropped action /pages/about must no longer be listed:\n{stdout2}"
    );
}

/// Slow end-to-end check: `generate controller --api` must compile and list its
/// JSON routes under `/api/<controller>`.
///
/// Ignored by default; run with `cargo test -p autumn-cli -- --ignored`.
#[test]
#[ignore = "slow: cargo-builds a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn controller_api_generates_json() {
    let (_tmp, project) = fresh_project("controller-api-build");
    patch_generated_cargo_toml(&project);

    run_autumn(
        &project,
        &["generate", "controller", "pages", "index", "stats", "--api"],
    );

    let file = fs::read_to_string(project.join("src/routes/pages.rs")).unwrap();
    assert!(
        file.contains("AutumnResult<Json<serde_json::Value>>"),
        "--api controller must return JSON:\n{file}"
    );

    let build = Command::new("cargo")
        .args(["build"])
        .current_dir(&project)
        .output()
        .expect("failed to run cargo build");
    assert!(
        build.status.success(),
        "cargo build failed on generated --api controller:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&build.stdout),
        String::from_utf8_lossy(&build.stderr),
    );

    let (stdout, _stderr) = run_autumn(&project, &["routes"]);
    for path in ["/api/pages", "/api/pages/stats"] {
        assert!(
            stdout.contains(path),
            "autumn routes must list {path}:\n{stdout}"
        );
    }
}