autumn-admin-plugin 0.9.0

Out-of-the-box admin panel plugin for autumn-web applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
//! Route handlers for the admin panel.
//!
//! All handlers return [`AutumnResult<Response>`] so the framework's
//! error-page filter can render 401/403/404/500 as branded HTML for browser
//! clients and JSON for API clients — no hand-rolled error HTML here.

use std::sync::Arc;

use autumn_web::runtime_config::RuntimeConfigService;
use std::collections::HashMap;
use std::convert::Infallible;

use autumn_web::extract::Multipart;
use autumn_web::flash::{Flash, FlashLevel, FlashMessage};
use autumn_web::job::{JobAdminQuery, JobAdminSnapshot, JobScheduleSummary, job_admin_backend};
use autumn_web::prelude::{HxRequest, HxResponseExt};
use autumn_web::security::{CsrfFormField, CsrfToken, CsrfTokenHeader};
use autumn_web::{AppState, AutumnError, AutumnResult};
use axum::extract::rejection::ExtensionRejection;
use axum::extract::{FromRequestParts, Path, Query, State};
use axum::http::request::Parts;
use axum::http::{StatusCode, header};
use axum::middleware::from_fn;
use axum::response::{Html, IntoResponse, Redirect, Response};
use axum::routing;
use diesel_async::pooled_connection::deadpool::Pool;
use futures::future::join_all;
use serde::Deserialize;
use serde_json::Value;

use crate::auth::{check_role, publish_current_actor};
use crate::impersonation::AdminImpersonation;
use crate::registry::AdminRegistry;
use crate::templates;
use crate::traits::{
    AdminError, AdminField, AdminFieldKind, AdminImportError, AdminImportReport,
    AdminImportRowResult, AdminModel, CsvImportMode, ListParams, SortDirection, record_id,
};

/// Admin-owned CSRF extractor that tolerates a missing `CsrfLayer`.
///
/// Autumn enables CSRF only for the `prod` profile by default, so a plain
/// `CsrfToken` extractor would crash every admin page in dev/test with a
/// 500. This wrapper reads the same request extension and falls back to an
/// empty token when the layer isn't installed — the rendered CSRF
/// hidden input and `<meta>` are then harmless because the middleware
/// that would validate them isn't running either.
#[derive(Debug, Clone, Default)]
pub struct AdminCsrf {
    token: String,
    form_field: String,
    token_header: String,
}

impl AdminCsrf {
    /// The CSRF token, or `""` if `CsrfLayer` is not installed.
    #[must_use]
    pub fn token(&self) -> &str {
        &self.token
    }

    /// The configured form field name, or Autumn's default when CSRF is absent.
    #[must_use]
    pub fn form_field(&self) -> &str {
        if self.form_field.is_empty() {
            "_csrf"
        } else {
            &self.form_field
        }
    }

    /// The configured CSRF token header name, or `"X-CSRF-Token"` when CSRF is absent.
    #[must_use]
    pub fn token_header(&self) -> &str {
        if self.token_header.is_empty() {
            "X-CSRF-Token"
        } else {
            &self.token_header
        }
    }
}

impl<S: Send + Sync> FromRequestParts<S> for AdminCsrf {
    type Rejection = Infallible;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let token = parts
            .extensions
            .get::<CsrfToken>()
            .map(|t| t.token().to_owned())
            .unwrap_or_default();
        let form_field = parts
            .extensions
            .get::<CsrfFormField>()
            .map_or_else(|| "_csrf".to_owned(), |field| field.0.clone());
        let token_header = parts
            .extensions
            .get::<CsrfTokenHeader>()
            .map_or_else(|| "X-CSRF-Token".to_owned(), |h| h.0.clone());
        Ok(Self {
            token,
            form_field,
            token_header,
        })
    }
}

/// Per-request values shared by every admin page handler.
///
/// One extractor replaces the registry, prefix, CSRF and impersonation
/// extractors each handler used to repeat. It builds the impersonation banner
/// once. [`AdminPageCtx::chrome`] turns it into the layout input.
pub struct AdminPageCtx {
    registry: Arc<AdminRegistry>,
    prefix: String,
    actuator_prefix: String,
    show_config: bool,
    csrf: AdminCsrf,
    banner: Option<templates::ImpersonationBanner>,
}

impl AdminPageCtx {
    /// Layout input for a page that shows `messages`.
    fn chrome<'a>(&'a self, messages: &'a [FlashMessage]) -> templates::AdminChrome<'a> {
        templates::AdminChrome {
            registry: &self.registry,
            prefix: &self.prefix,
            actuator_prefix: &self.actuator_prefix,
            csrf_token: self.csrf.token(),
            csrf_form_field: self.csrf.form_field(),
            csrf_token_header: self.csrf.token_header(),
            messages,
            show_config: self.show_config,
            impersonation: self.banner.as_ref(),
        }
    }
}

impl FromRequestParts<AppState> for AdminPageCtx {
    type Rejection = ExtensionRejection;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AppState,
    ) -> Result<Self, Self::Rejection> {
        let axum::Extension(registry) =
            axum::Extension::<Arc<AdminRegistry>>::from_request_parts(parts, state).await?;
        let axum::Extension(AdminPrefix(prefix)) =
            axum::Extension::<AdminPrefix>::from_request_parts(parts, state).await?;
        let axum::Extension(ActuatorPrefix(actuator_prefix)) =
            axum::Extension::<ActuatorPrefix>::from_request_parts(parts, state).await?;
        let axum::Extension(HasRuntimeConfig(show_config)) =
            axum::Extension::<HasRuntimeConfig>::from_request_parts(parts, state).await?;
        let Ok(csrf) = AdminCsrf::from_request_parts(parts, state).await;
        let Ok(imp) = AdminImpersonation::from_request_parts(parts, state).await;
        let banner = imp.banner(&prefix, csrf.token(), csrf.form_field());
        Ok(Self {
            registry,
            prefix,
            actuator_prefix,
            show_config,
            csrf,
            banner,
        })
    }
}

/// Plugin-owned JS, served as an external file (not inline) so it works
/// under the default CSP `script-src 'self'`. Installed with
/// `AppBuilder::plugin_assets`, which gives it a content-hashed URL under
/// `/static/_plugins/autumn-admin/` cached `immutable` for a year: changing
/// the JS changes the URL, so cached client JS never outlives the server
/// templates that call it.
pub static ASSETS: autumn_web::assets::PluginAssets = autumn_web::assets::PluginAssets::from_files(
    "autumn-admin",
    &[("admin.js", include_bytes!("admin.js"))],
);

// ── Router construction ─────────────────────────────────────────────

/// Access-control settings for [`admin_router`].
pub struct AdminGuards {
    /// Session key that holds the signed-in user.
    pub auth_session_key: String,
    /// Role a user needs to reach the admin panel, if any.
    pub require_role: Option<String>,
    /// Whether mutations need a recent step-up check.
    pub step_up_mutations: bool,
    /// Maximum age of a step-up check, in seconds.
    pub step_up_max_age_secs: u64,
}

pub fn admin_router(
    registry: Arc<AdminRegistry>,
    prefix: &str,
    actuator_prefix: String,
    guards: AdminGuards,
    config_svc: Option<Arc<RuntimeConfigService>>,
    impersonation_enabled: bool,
) -> axum::Router<AppState> {
    let AdminGuards {
        auth_session_key,
        require_role,
        step_up_mutations,
        step_up_max_age_secs,
    } = guards;
    let has_config = config_svc.is_some();
    // Cloned up front: the role-check closure below takes ownership of
    // `auth_session_key`, but the actor layer needs it too.
    let actor_session_key = auth_session_key.clone();

    let mut router = axum::Router::new()
        // Dashboard
        .route("/", routing::get(dashboard))
        .route("/jobs", routing::get(jobs_dashboard))
        .route("/jobs/counters", routing::get(jobs_counters))
        .route("/jobs/{id}/retry", routing::post(job_retry))
        .route("/jobs/{id}/discard", routing::post(job_discard))
        .route("/jobs/{id}/cancel", routing::post(job_cancel));

    // Runtime config routes — registered before /{slug} so the literal
    // "/config" path wins over the parameterized catch-all.
    if let Some(svc) = config_svc {
        router = router
            .route("/config", routing::get(config_list))
            .route("/config/{key}/set", routing::post(config_set))
            .route("/config/{key}/unset", routing::post(config_unset))
            .route("/config/{key}/history", routing::get(config_key_history))
            .layer(axum::Extension(AdminAuthSessionKey(
                auth_session_key.clone(),
            )))
            .layer(axum::Extension(svc));
    }

    // Begin-impersonation route (#1394). Registered before the `/{slug}`
    // catch-all and *inside* the role + step-up guards; the framework's
    // `ImpersonationGate` then gates it again (default-deny), so holding the
    // admin role is never sufficient on its own.
    if impersonation_enabled {
        router = router.route(
            "/impersonate",
            routing::post(crate::impersonation::impersonate_begin),
        );
    }

    router = router
        // Model routes (dynamic dispatch via slug)
        .route("/{slug}", routing::get(model_list).post(model_create))
        .route("/{slug}/new", routing::get(model_new_form))
        .route(
            "/{slug}/{id}",
            routing::get(model_detail)
                .post(model_update)
                .delete(model_delete),
        )
        // Version history pane (only reachable when model.has_history() is true)
        .route("/{slug}/{id}/history", routing::get(model_history))
        .route("/{slug}/{id}/edit", routing::get(model_edit_form))
        // Bulk-action endpoint. Receives selected `ids[]` and an `action`
        // name from the list-view form; dispatches to
        // `AdminModel::execute_action`.
        .route("/{slug}/actions", routing::post(model_action))
        // CSV export (GET) and import (POST)
        .route("/{slug}/export.csv", routing::get(model_export_csv))
        .route(
            "/{slug}/import",
            routing::get(model_import_form).post(model_import_csv),
        )
        .layer(axum::Extension(HasRuntimeConfig(has_config)))
        .layer(axum::Extension(AdminPrefix(prefix.to_owned())))
        .layer(axum::Extension(ActuatorPrefix(actuator_prefix)))
        .layer(axum::Extension(registry));

    // Apply step-up mutation guard before the role check so that a hijacked
    // admin session cannot exercise destructive admin actions.
    let router = if step_up_mutations {
        router.layer(from_fn(move |req, next| {
            crate::auth::check_step_up_mutations(step_up_max_age_secs, req, next)
        }))
    } else {
        router
    };

    let router = match require_role {
        Some(role) => router.layer(from_fn(move |req, next| {
            check_role(role.clone(), auth_session_key.clone(), req, next)
        })),
        None => router,
    };

    if !impersonation_enabled {
        return router.layer(from_fn(move |req, next| {
            publish_current_actor(actor_session_key.clone(), req, next)
        }));
    }

    // The revert route is merged *after* the role and step-up layers, so it is
    // deliberately outside both. While impersonating, the session carries the
    // target's role (usually none) — a gated revert would trap the operator in
    // the target's identity with no way back. The route is self-gating: a
    // session that is not impersonating gets a 400 and nothing changes.
    router
        .merge(
            axum::Router::new()
                .route(
                    "/impersonate/stop",
                    routing::post(crate::impersonation::impersonate_stop),
                )
                .layer(axum::Extension(AdminPrefix(prefix.to_owned()))),
        )
        // Outermost, and applied after the merge so it covers the ungated
        // revert route too. Attribution must not depend on the *optional* role
        // check, so this is its own layer rather than part of `check_role`.
        .layer(from_fn(move |req, next| {
            publish_current_actor(actor_session_key.clone(), req, next)
        }))
}

/// Typed Extension carrying the admin URL prefix so handlers can build links.
#[derive(Clone)]
pub struct AdminPrefix(pub String);

/// Typed Extension signalling whether the runtime config service is mounted.
#[derive(Clone)]
struct HasRuntimeConfig(bool);

/// Typed Extension carrying the actuator URL prefix (the value of
/// `config.actuator.prefix`), used for dashboard links and HTMX polling.
#[derive(Clone)]
struct ActuatorPrefix(String);

/// Typed Extension carrying the session key used to look up the authenticated
/// user's identity, so config-mutation handlers can record a real actor.
#[derive(Clone)]
struct AdminAuthSessionKey(String);

// ── Query params ────────────────────────────────────────────────────

#[derive(Debug, Deserialize, Default)]
struct ListQuery {
    #[serde(default = "default_page")]
    page: u64,
    #[serde(default)]
    q: String,
    #[serde(default)]
    sort: Option<String>,
    #[serde(default)]
    dir: SortDirection,
}

#[derive(Debug, Deserialize)]
struct JobsQuery {
    #[serde(default = "default_page", rename = "enqueued_page")]
    enqueued: u64,
    #[serde(default = "default_page", rename = "scheduled_page")]
    scheduled: u64,
    #[serde(default = "default_page", rename = "running_page")]
    running: u64,
    #[serde(default = "default_page", rename = "completed_page")]
    completed: u64,
    #[serde(default = "default_page", rename = "failed_page")]
    failed: u64,
    #[serde(default = "default_jobs_per_page", rename = "per_page")]
    per: u64,
}

impl From<JobsQuery> for JobAdminQuery {
    fn from(query: JobsQuery) -> Self {
        Self {
            enqueued_page: query.enqueued.max(1),
            scheduled_page: query.scheduled.max(1),
            running_page: query.running.max(1),
            completed_page: query.completed.max(1),
            failed_page: query.failed.max(1),
            per_page: query.per.clamp(1, 100),
        }
    }
}

const fn default_page() -> u64 {
    1
}

const fn default_jobs_per_page() -> u64 {
    25
}

// ── Shared resolution ───────────────────────────────────────────────

/// Resolve the DB pool + model for a slug, translating missing state into
/// `AutumnError` so handlers can use `?`.
fn resolve<'r>(
    state: &AppState,
    registry: &'r AdminRegistry,
    slug: &str,
) -> AutumnResult<(Pool<::autumn_web::RuntimeConnection>, &'r dyn AdminModel)> {
    // `Pool` is Arc-backed inside deadpool; cloning is cheap.
    let pool = state
        .pool()
        .cloned()
        .ok_or_else(|| AutumnError::service_unavailable_msg("No database pool configured"))?;
    let model = registry
        .get(slug)
        .ok_or_else(|| AutumnError::not_found_msg(format!("Model '{slug}' not found")))?;
    Ok((pool, model))
}

/// Filter a user-supplied sort key down to fields the model declared as
/// both sortable and list-displayed, AND that aren't of a sensitive kind
/// (`Password`/`Hidden`). A `None` (or unrecognised key) means "no sort"
/// — never forward arbitrary identifiers to the model.
///
/// The Hidden/Password exclusion mirrors the template-level filter on
/// `list_fields`: those columns aren't visible in the table, so a sort
/// header link can never produce them — only URL crafting can. Reject
/// here so the model doesn't receive an unexpected ORDER BY against a
/// column the admin chose to keep server-side.
fn validate_sort_key(sort: Option<String>, fields: &[AdminField]) -> Option<String> {
    sort.filter(|s| {
        fields.iter().any(|f| {
            f.name == s
                && f.sortable
                && f.list_display
                && !matches!(f.kind, AdminFieldKind::Password | AdminFieldKind::Hidden)
        })
    })
}

/// Pick `filter.<name>=<value>` pairs out of the raw query map and keep
/// only those whose `<name>` matches a field declared as `filterable` in
/// the model's schema. Sorted by name for stable output.
fn extract_filters(raw: &HashMap<String, String>, fields: &[AdminField]) -> Vec<(String, String)> {
    let mut out: Vec<(String, String)> = raw
        .iter()
        .filter_map(|(k, v)| {
            let name = k.strip_prefix("filter.")?;
            // Must be declared filterable. Empty values count as "no
            // filter on this field" and are dropped.
            if v.is_empty() {
                return None;
            }
            if !fields.iter().any(|f| f.name == name && f.filterable) {
                return None;
            }
            Some((name.to_owned(), v.clone()))
        })
        .collect();
    out.sort_by(|a, b| a.0.cmp(&b.0));
    out
}

/// Translate an [`AdminError`] to the correct HTTP status. Validation errors
/// become 400, missing records 404, database/other backend failures 500. The
/// `action` word prefixes the message ("Create failed: ..."), which is handy
/// in logs and error pages.
fn admin_err(action: &str, err: AdminError) -> AutumnError {
    match err {
        AdminError::NotFound => AutumnError::not_found_msg(format!("{action}: not found")),
        AdminError::Validation(msg) => AutumnError::bad_request_msg(format!("{action}: {msg}")),
        AdminError::Database(msg) => {
            AutumnError::internal_server_error_msg(format!("{action}: database error: {msg}"))
        }
        AdminError::Other(msg) => {
            AutumnError::internal_server_error_msg(format!("{action}: {msg}"))
        }
    }
}

/// Render a Maud `Markup` into an `Html` response.
fn render(markup: maud::Markup) -> Response {
    Html(markup.into_string()).into_response()
}

/// What failed validation, and what to show the admin again.
struct FormFailure<'a> {
    /// Values to put back in the form.
    submitted: &'a Value,
    /// Names of fields in `submitted` whose value is raw, unparsed form text
    /// (e.g. a `Json` field that failed to parse), not a typed value. The
    /// form page shows that text as is. Empty when `submitted` is fully
    /// coerced (the `AdminError::Validation` case).
    raw_fields: &'a [&'a str],
    /// Message for the flash banner.
    message: String,
}

/// Re-render the create/edit form after a validation failure instead of
/// navigating away to the generic error page. Preserves every value the
/// admin typed (`submitted`) and surfaces `error_message` through the same
/// persistent, accessible flash banner every other page uses — no toast, no
/// blank form, no lost input.
fn invalid_form_response(
    ctx: &AdminPageCtx,
    slug: &str,
    model: &dyn AdminModel,
    fields: &[AdminField],
    failure: FormFailure<'_>,
    id: Option<i64>,
) -> Response {
    let messages = [FlashMessage {
        level: FlashLevel::Error,
        message: failure.message,
    }];
    let markup = templates::model_form_page(
        &ctx.chrome(&messages),
        &templates::ModelFormView {
            model_slug: slug,
            model_name: model.display_name(),
            model_name_plural: model.display_name_plural(),
            fields,
            record: Some(failure.submitted),
            id,
            raw_fields: failure.raw_fields,
        },
    );
    (StatusCode::UNPROCESSABLE_ENTITY, Html(markup.into_string())).into_response()
}

/// After a validation failure on update, `submitted` holds only the fields
/// the browser actually sent — create-only columns render read-only with no
/// `name` attribute (see `render_readonly_display`), so they never round-trip
/// through the form post. Merge the submitted edits onto the stored record so
/// those columns keep showing their real value on redisplay instead of going
/// blank.
///
/// A genuinely missing record (`Ok(None)` — e.g. deleted between the edit
/// page loading and this submit) falls back to `submitted` alone, same as
/// before: there is no stored record to merge with. A fetch error, though,
/// is a real backend problem (e.g. `AdminError::Database`) unrelated to the
/// admin's input — it must reach the caller so it renders the normal error
/// response, not be swallowed into a 422 that quietly blanks out every
/// `create_only` field and calls it a validation failure (Codex review,
/// PR #2422).
async fn merge_with_stored_record(
    model: &dyn AdminModel,
    pool: &Pool<::autumn_web::RuntimeConnection>,
    id: i64,
    submitted: &Value,
) -> Result<Value, AdminError> {
    let mut base = model
        .get(pool, id)
        .await?
        .unwrap_or_else(|| submitted.clone());
    if let (Some(obj), Some(sub)) = (base.as_object_mut(), submitted.as_object()) {
        for (k, v) in sub {
            obj.insert(k.clone(), v.clone());
        }
    }
    Ok(base)
}

/// Extract the value of the `__autumn_reveal` cookie from request headers.
fn extract_reveal_cookie(headers: &axum::http::HeaderMap) -> Option<String> {
    let cookie_str = headers.get(axum::http::header::COOKIE)?.to_str().ok()?;
    cookie_str.split(';').find_map(|part| {
        part.trim()
            .strip_prefix("__autumn_reveal=")
            .filter(|v| !v.is_empty())
            .map(str::to_owned)
    })
}

// ── Handlers ────────────────────────────────────────────────────────

/// `GET /admin` — Dashboard with model counts.
async fn dashboard(
    ctx: AdminPageCtx,
    State(state): State<AppState>,
    flash: Flash,
) -> AutumnResult<Response> {
    let AdminPageCtx { registry, .. } = &ctx;
    let pool = state
        .pool()
        .cloned()
        .ok_or_else(|| AutumnError::service_unavailable_msg("No database pool configured"))?;

    let futures: Vec<_> = registry
        .iter()
        .map(|(slug, model)| {
            let pool = pool.clone();
            async move {
                let count = model.count(&pool).await.unwrap_or(0);
                (slug, model.display_name_plural(), count)
            }
        })
        .collect();
    let counts = join_all(futures).await;
    let messages = flash.consume().await;

    Ok(render(templates::dashboard_page(
        &ctx.chrome(&messages),
        &counts,
    )))
}

/// `GET /admin/jobs` -- built-in background jobs dashboard.
async fn jobs_dashboard(
    ctx: AdminPageCtx,
    State(state): State<AppState>,
    Query(query): Query<JobsQuery>,
    flash: Flash,
) -> AutumnResult<Response> {
    let mut snapshot = match job_admin_backend(&state) {
        Some(backend) => backend.snapshot(query.into()).await?,
        None => JobAdminSnapshot::empty(),
    };
    snapshot.schedules = scheduled_job_summaries(&state);
    let messages = flash.consume().await;

    Ok(render(templates::jobs_page(
        &ctx.chrome(&messages),
        &snapshot,
    )))
}

/// `GET /admin/jobs/counters` -- HTMX counter refresh fragment.
async fn jobs_counters(
    State(state): State<AppState>,
    axum::Extension(AdminPrefix(prefix)): axum::Extension<AdminPrefix>,
    Query(query): Query<JobsQuery>,
) -> AutumnResult<Response> {
    let mut snapshot = match job_admin_backend(&state) {
        Some(backend) => backend.snapshot(query.into()).await?,
        None => JobAdminSnapshot::empty(),
    };
    snapshot.schedules = scheduled_job_summaries(&state);
    Ok(render(templates::jobs_counters(&snapshot, &prefix)))
}

/// `POST /admin/jobs/{id}/retry` -- retry a failed job.
async fn job_retry(
    State(state): State<AppState>,
    axum::Extension(AdminPrefix(prefix)): axum::Extension<AdminPrefix>,
    Path(id): Path<String>,
    flash: Flash,
) -> AutumnResult<Response> {
    let backend = job_admin_backend(&state)
        .ok_or_else(|| AutumnError::service_unavailable_msg("job runtime is not initialized"))?;
    backend.retry(&id).await?;
    flash.success(format!("Retried job {id}.")).await;
    Ok(Redirect::to(&format!("{prefix}/jobs")).into_response())
}

/// `POST /admin/jobs/{id}/discard` -- discard a failed job.
async fn job_discard(
    State(state): State<AppState>,
    axum::Extension(AdminPrefix(prefix)): axum::Extension<AdminPrefix>,
    Path(id): Path<String>,
    flash: Flash,
) -> AutumnResult<Response> {
    let backend = job_admin_backend(&state)
        .ok_or_else(|| AutumnError::service_unavailable_msg("job runtime is not initialized"))?;
    backend.discard(&id).await?;
    flash.success(format!("Discarded job {id}.")).await;
    Ok(Redirect::to(&format!("{prefix}/jobs")).into_response())
}

/// `POST /admin/jobs/{id}/cancel` -- cancel a job that has not started.
async fn job_cancel(
    State(state): State<AppState>,
    axum::Extension(AdminPrefix(prefix)): axum::Extension<AdminPrefix>,
    Path(id): Path<String>,
    flash: Flash,
) -> AutumnResult<Response> {
    let backend = job_admin_backend(&state)
        .ok_or_else(|| AutumnError::service_unavailable_msg("job runtime is not initialized"))?;
    backend.cancel(&id).await?;
    flash.success(format!("Canceled job {id}.")).await;
    Ok(Redirect::to(&format!("{prefix}/jobs")).into_response())
}

fn scheduled_job_summaries(state: &AppState) -> Vec<JobScheduleSummary> {
    let mut schedules: Vec<_> = state
        .task_registry()
        .snapshot()
        .into_iter()
        .map(|(name, status)| {
            let last_run_status = status
                .last_error
                .as_ref()
                .map(|error| format!("failed: {error}"))
                .or(status.last_result);
            JobScheduleSummary {
                name,
                schedule: status.schedule,
                next_run_at: status.next_run_at,
                last_run_status,
            }
        })
        .collect();
    schedules.sort_by(|a, b| a.name.cmp(&b.name));
    schedules
}

/// `GET /admin/{slug}` -- Model list view.
async fn model_list(
    ctx: AdminPageCtx,
    State(state): State<AppState>,
    Path(slug): Path<String>,
    Query(query): Query<ListQuery>,
    Query(raw_query): Query<HashMap<String, String>>,
    flash: Flash,
) -> AutumnResult<Response> {
    let AdminPageCtx { registry, .. } = &ctx;
    let (pool, model) = resolve(&state, registry, &slug)?;

    let ListQuery { page, q, sort, dir } = query;
    let page = page.max(1);
    let per_page = model.per_page();
    let fields = model.fields();
    // Validate the requested sort key against the model's declared
    // sortable fields. A crafted `?sort=<unexpected>` is silently dropped
    // — the model never sees an unvalidated sort key, so it can't error
    // or build unsafe dynamic ORDER BY expressions.
    let sort = validate_sort_key(sort, &fields);
    // Pull `?filter.<name>=<value>` keys out of the raw query string and
    // validate against the model's declared filterable fields. Unknown or
    // non-filterable names are dropped so a crafted URL can't drive
    // arbitrary filter logic in `AdminModel::list`.
    let filters = extract_filters(&raw_query, &fields);

    let params = ListParams {
        page,
        per_page,
        search: (!q.is_empty()).then(|| q.clone()),
        sort_by: sort.clone(),
        sort_dir: dir,
        filters: filters.clone(),
    };

    let result = model
        .list(&pool, params)
        .await
        .map_err(|e| admin_err("List", e))?;

    let actions = model.actions();
    let messages = flash.consume().await;
    Ok(render(templates::model_list_page(
        &ctx.chrome(&messages),
        &templates::ModelListView {
            model_slug: &slug,
            model_name_plural: model.display_name_plural(),
            fields: &fields,
            actions: &actions,
            result: &result,
            search_query: &q,
            sort_by: sort.as_deref(),
            sort_dir: dir,
            filters: &filters,
            supports_csv_export: model.supports_csv_export(),
            supports_csv_import: model.supports_csv_import(),
        },
    )))
}

/// `GET /admin/{slug}/new` — Create form.
async fn model_new_form(
    ctx: AdminPageCtx,
    Path(slug): Path<String>,
    flash: Flash,
) -> AutumnResult<Response> {
    let AdminPageCtx { registry, .. } = &ctx;
    let model = registry
        .get(&slug)
        .ok_or_else(|| AutumnError::not_found_msg(format!("Model '{slug}' not found")))?;

    let fields = model.fields();
    let messages = flash.consume().await;
    Ok(render(templates::model_form_page(
        &ctx.chrome(&messages),
        &templates::ModelFormView {
            model_slug: &slug,
            model_name: model.display_name(),
            model_name_plural: model.display_name_plural(),
            fields: &fields,
            record: None,
            id: None,
            raw_fields: &[],
        },
    )))
}

/// `POST /admin/{slug}` — Create a record.
async fn model_create(
    ctx: AdminPageCtx,
    State(state): State<AppState>,
    Path(slug): Path<String>,
    flash: Flash,
    axum::extract::Form(form_data): axum::extract::Form<Value>,
) -> AutumnResult<Response> {
    let AdminPageCtx {
        registry, prefix, ..
    } = &ctx;
    let (pool, model) = resolve(&state, registry, &slug)?;

    let fields = model.fields();
    let submitted = strip_meta_fields(form_data, &fields, false);
    let form_data = match coerce_form_fields(submitted, &fields) {
        Ok(v) => v,
        Err((partial, field_names, msg)) => {
            return Ok(invalid_form_response(
                &ctx,
                &slug,
                model,
                &fields,
                FormFailure {
                    submitted: &partial,
                    raw_fields: &field_names,
                    message: msg,
                },
                None,
            ));
        }
    };
    let record = match model.create(&pool, form_data.clone()).await {
        Ok(record) => record,
        Err(AdminError::Validation(msg)) => {
            return Ok(invalid_form_response(
                &ctx,
                &slug,
                model,
                &fields,
                FormFailure {
                    submitted: &form_data,
                    raw_fields: &[],
                    message: msg,
                },
                None,
            ));
        }
        Err(e) => return Err(admin_err("Create failed", e)),
    };
    // The post-create redirect needs a routable ID. Treat a missing or
    // non-numeric `id` as a model-impl bug rather than silently sending
    // the admin to `/{slug}/0` (which lands on the wrong row or a 404).
    let new_id = record_id(&record).ok_or_else(|| {
        AutumnError::internal_server_error_msg(format!(
            "{} create returned a record without a numeric `id` field; cannot route post-create redirect",
            model.display_name()
        ))
    })?;
    let detail_path = format!("{prefix}/{slug}/{new_id}");
    let mut response = Redirect::to(&detail_path).into_response();

    // If the model returned a one-time secret (e.g. a raw API token), hand it
    // off via a short-lived HttpOnly reveal cookie rather than through flash.
    // Flash::push stores messages in the Session, and SessionLayer persists
    // dirty sessions to the configured backing store (Redis/DB) — putting a raw
    // bearer token there even briefly is a plaintext-secret-storage violation.
    // The reveal cookie is path-scoped to the detail page and expires in 5
    // minutes; the detail handler reads it exactly once and clears it.
    //
    // Additionally, skip flash.success() on secret-returning creates: the
    // session write would dirty the session before the redirect; if the session
    // store (Redis/DB) is unavailable, SessionLayer replaces the handler's
    // response with its own error — discarding the Set-Cookie header and
    // permanently losing the raw credential.  The "copy now" FlashMessage
    // rendered by model_detail from the reveal cookie is sufficient notification.
    if let Some(Value::String(secret)) = record.get("token") {
        // Mirror the session cookie's Secure flag so the reveal cookie is
        // accepted in both HTTPS and explicit HTTP-only deployments.
        // `config_arc` reads through the shared handle: reading one `bool` must
        // not deep-clone every config section on a request path.
        let secure_attr = if state.config_arc().session.secure {
            "; Secure"
        } else {
            ""
        };
        let cookie = format!(
            "__autumn_reveal={secret}; HttpOnly{secure_attr}; SameSite=Strict; Path={detail_path}; Max-Age=300"
        );
        if let Ok(hv) = axum::http::HeaderValue::from_str(&cookie) {
            response
                .headers_mut()
                .insert(axum::http::header::SET_COOKIE, hv);
        }
    } else {
        // Non-secret create: safe to write a flash message (no raw credential
        // at risk if the session save fails — the record is already committed
        // and remains accessible via the list view).
        flash
            .success(format!("{} created.", model.display_name()))
            .await;
    }
    Ok(response)
}

/// `GET /admin/{slug}/{id}` — Detail view.
async fn model_detail(
    ctx: AdminPageCtx,
    State(state): State<AppState>,
    Path((slug, id)): Path<(String, i64)>,
    request_headers: axum::http::HeaderMap,
    flash: Flash,
) -> AutumnResult<Response> {
    let AdminPageCtx {
        registry, prefix, ..
    } = &ctx;
    let (pool, model) = resolve(&state, registry, &slug)?;

    let record = model
        .get(&pool, id)
        .await
        .map_err(|e| admin_err("Get", e))?
        .ok_or_else(|| {
            AutumnError::not_found_msg(format!("{} #{id} not found", model.display_name()))
        })?;

    let display = model.record_display(&record);
    let fields = model.fields();

    // Consume the reveal cookie if present (set by model_create for one-time
    // secrets such as raw API tokens).  The secret is appended to the in-memory
    // messages slice; it never touches the session store.
    let reveal_secret = extract_reveal_cookie(&request_headers);
    let mut messages = flash.consume().await;
    if let Some(ref secret) = reveal_secret {
        messages.push(FlashMessage {
            level: FlashLevel::Info,
            message: format!("Copy your token now — it will not be shown again: {secret}"),
        });
    }

    let mut response = render(templates::model_detail_page(
        &ctx.chrome(&messages),
        &templates::ModelDetailView {
            model_slug: &slug,
            model_name: model.display_name(),
            model_name_plural: model.display_name_plural(),
            fields: &fields,
            record: &record,
            record_display: &display,
            id,
            has_history: model.has_history(),
        },
    ))
    .into_response();

    // Clear the reveal cookie so a page refresh does not show the token again.
    // Mirror the session cookie's Secure flag for consistency.
    if reveal_secret.is_some() {
        let secure_attr = if state.config_arc().session.secure {
            "; Secure"
        } else {
            ""
        };
        let clear = format!(
            "__autumn_reveal=; HttpOnly{secure_attr}; SameSite=Strict; Path={prefix}/{slug}/{id}; Max-Age=0"
        );
        if let Ok(hv) = axum::http::HeaderValue::from_str(&clear) {
            response
                .headers_mut()
                .insert(axum::http::header::SET_COOKIE, hv);
        }
    }

    Ok(response)
}

/// `GET /admin/{slug}/{id}/history` - Version history pane.
///
/// Returns 404 when the model has not opted into version history
/// (`model.has_history()` returns `false`).
async fn model_history(
    ctx: AdminPageCtx,
    State(state): State<AppState>,
    Path((slug, id)): Path<(String, i64)>,
    Query(params): Query<HashMap<String, String>>,
) -> AutumnResult<Response> {
    let AdminPageCtx { registry, .. } = &ctx;
    let (pool, model) = resolve(&state, registry, &slug)?;

    if !model.has_history() {
        return Err(AutumnError::not_found_msg(format!(
            "{} does not have version history enabled",
            model.display_name()
        )));
    }

    let page: u64 = params.get("page").and_then(|p| p.parse().ok()).unwrap_or(1);
    let per_page: u64 = params
        .get("per_page")
        .and_then(|p| p.parse().ok())
        .unwrap_or(25);

    let history = model
        .get_history(&pool, id, page, per_page)
        .await
        .map_err(|e| admin_err("History", e))?;

    Ok(render(templates::model_history_page(
        &ctx.chrome(&[]),
        &slug,
        model.display_name(),
        model.display_name_plural(),
        id,
        &history,
    )))
}

/// `GET /admin/{slug}/{id}/edit` — Edit form.
async fn model_edit_form(
    ctx: AdminPageCtx,
    State(state): State<AppState>,
    Path((slug, id)): Path<(String, i64)>,
    flash: Flash,
) -> AutumnResult<Response> {
    let AdminPageCtx { registry, .. } = &ctx;
    let (pool, model) = resolve(&state, registry, &slug)?;

    let record = model
        .get(&pool, id)
        .await
        .map_err(|e| admin_err("Get", e))?
        .ok_or_else(|| {
            AutumnError::not_found_msg(format!("{} #{id} not found", model.display_name()))
        })?;

    let fields = model.fields();
    let messages = flash.consume().await;
    Ok(render(templates::model_form_page(
        &ctx.chrome(&messages),
        &templates::ModelFormView {
            model_slug: &slug,
            model_name: model.display_name(),
            model_name_plural: model.display_name_plural(),
            fields: &fields,
            record: Some(&record),
            id: Some(id),
            raw_fields: &[],
        },
    )))
}

/// `POST /admin/{slug}/{id}` — Update a record.
async fn model_update(
    ctx: AdminPageCtx,
    State(state): State<AppState>,
    Path((slug, id)): Path<(String, i64)>,
    flash: Flash,
    axum::extract::Form(form_data): axum::extract::Form<Value>,
) -> AutumnResult<Response> {
    let AdminPageCtx {
        registry, prefix, ..
    } = &ctx;
    let (pool, model) = resolve(&state, registry, &slug)?;

    let fields = model.fields();
    let submitted = strip_meta_fields(form_data, &fields, true);
    let form_data = match coerce_form_fields(submitted, &fields) {
        Ok(v) => v,
        Err((partial, field_names, msg)) => {
            let display = match merge_with_stored_record(model, &pool, id, &partial).await {
                Ok(v) => v,
                Err(e) => return Err(admin_err("Update failed", e)),
            };
            return Ok(invalid_form_response(
                &ctx,
                &slug,
                model,
                &fields,
                FormFailure {
                    submitted: &display,
                    raw_fields: &field_names,
                    message: msg,
                },
                Some(id),
            ));
        }
    };
    if let Err(e) = model.update(&pool, id, form_data.clone()).await {
        if let AdminError::Validation(msg) = e {
            let display = match merge_with_stored_record(model, &pool, id, &form_data).await {
                Ok(v) => v,
                Err(e) => return Err(admin_err("Update failed", e)),
            };
            return Ok(invalid_form_response(
                &ctx,
                &slug,
                model,
                &fields,
                FormFailure {
                    submitted: &display,
                    raw_fields: &[],
                    message: msg,
                },
                Some(id),
            ));
        }
        return Err(admin_err("Update failed", e));
    }
    flash
        .success(format!("{} #{id} updated.", model.display_name()))
        .await;
    Ok(Redirect::to(&format!("{prefix}/{slug}/{id}")).into_response())
}

/// `POST /admin/{slug}/actions` — Execute a bulk action.
///
/// Form body carries `action=<name>`, repeated `ids=<id>` for each selected
/// row, and the CSRF token field. Validates the action name against the model's
/// declared `actions()` list, parses every `ids` entry as `i64`, then
/// dispatches to [`AdminModel::execute_action`].
async fn model_action(
    State(state): State<AppState>,
    axum::Extension(registry): axum::Extension<Arc<AdminRegistry>>,
    axum::Extension(AdminPrefix(prefix)): axum::Extension<AdminPrefix>,
    Path(slug): Path<String>,
    flash: Flash,
    body: axum::body::Bytes,
) -> AutumnResult<Response> {
    let (pool, model) = resolve(&state, &registry, &slug)?;

    // serde_urlencoded doesn't support repeated keys (`ids=1&ids=2&ids=3`),
    // so parse with `form_urlencoded` directly.
    let mut action: Option<String> = None;
    let mut ids: Vec<i64> = Vec::new();
    let mut malformed_id = false;
    for (k, v) in form_urlencoded::parse(&body) {
        match k.as_ref() {
            "action" => action = Some(v.into_owned()),
            "ids" => match v.parse::<i64>() {
                Ok(id) => ids.push(id),
                Err(_) => malformed_id = true,
            },
            // ignore the CSRF token field and any unknown keys
            _ => {}
        }
    }

    if malformed_id {
        return Err(AutumnError::bad_request_msg(
            "bulk action: one or more `ids` values were not valid integers",
        ));
    }
    let action = action
        .ok_or_else(|| AutumnError::bad_request_msg("bulk action: missing `action` form field"))?;
    if ids.is_empty() {
        return Err(AutumnError::bad_request_msg(
            "bulk action: select at least one row",
        ));
    }
    // Validate the action name against the model's declared list.
    if !model.actions().iter().any(|a| a.name == action) {
        return Err(AutumnError::bad_request_msg(format!(
            "bulk action: '{action}' is not declared by this model"
        )));
    }

    let count = model
        .execute_action(&pool, &action, ids)
        .await
        .map_err(|e| admin_err("Bulk action failed", e))?;
    flash
        .success(format!("Applied '{action}' to {count} record(s)."))
        .await;
    Ok(Redirect::to(&format!("{prefix}/{slug}")).into_response())
}

/// `DELETE /admin/{slug}/{id}` — Delete a record.
///
/// Called from the detail view's `confirm_action` dialog (a plain `POST` +
/// `_method=DELETE` form submission, not `hx-delete` — see
/// `autumn_web::widgets::confirm_action`), or its `<noscript>` fallback
/// button when JavaScript is disabled. Neither path sends `HX-Request`
/// today, so the `hx.is_htmx` branch below is currently unreached by the
/// admin plugin's own UI; it's kept for direct API/htmx clients that set
/// the header themselves, in which case they get an empty 200 body with
/// `HX-Redirect` so htmx performs a full-page navigation to the list view
/// (updating `window.location`), rather than swapping the list HTML into
/// the stale detail page. Non-htmx requests get a real 303 redirect, since
/// a plain browser form submission ignores `HX-Redirect` and would
/// otherwise land on a blank 200 response.
async fn model_delete(
    State(state): State<AppState>,
    axum::Extension(registry): axum::Extension<Arc<AdminRegistry>>,
    axum::Extension(AdminPrefix(prefix)): axum::Extension<AdminPrefix>,
    Path((slug, id)): Path<(String, i64)>,
    hx: HxRequest,
    flash: Flash,
) -> AutumnResult<Response> {
    let (pool, model) = resolve(&state, &registry, &slug)?;

    model
        .delete(&pool, id)
        .await
        .map_err(|e| admin_err("Delete failed", e))?;
    flash
        .success(format!("{} #{id} deleted.", model.display_name()))
        .await;
    let list_path = format!("{prefix}/{slug}");
    if hx.is_htmx {
        Ok(StatusCode::OK.hx_redirect(&list_path))
    } else {
        Ok(Redirect::to(&list_path).into_response())
    }
}

// ── CSV export / import handlers ─────────────────────────────────────

/// Records fetched per page during CSV export to bound peak JSON memory usage.
const EXPORT_PAGE_SIZE: u64 = 500;

/// `GET /admin/{slug}/export.csv` — Download all records as a CSV file.
///
/// The response respects active `?q=`, `?sort=`, `?dir=`, and `?filter.*`
/// query parameters so the exported data matches what the user sees in the
/// list view.
async fn model_export_csv(
    State(state): State<AppState>,
    axum::Extension(registry): axum::Extension<Arc<AdminRegistry>>,
    Path(slug): Path<String>,
    Query(query): Query<ListQuery>,
    Query(raw_query): Query<HashMap<String, String>>,
) -> AutumnResult<Response> {
    let (pool, model) = resolve(&state, &registry, &slug)?;

    if !model.supports_csv_export() {
        return Err(AutumnError::bad_request_msg(format!(
            "Model '{slug}' does not support CSV export"
        )));
    }

    let ListQuery {
        page: _,
        q,
        sort,
        dir,
    } = query;
    let fields = model.fields();
    let sort_key = validate_sort_key(sort, &fields);
    let filters = extract_filters(&raw_query, &fields);
    let search = (!q.is_empty()).then_some(q);

    // Page through records in batches to avoid buffering the entire dataset
    // as JSON in memory at once.
    // #1771: `csv_export_columns` is overridable, and an override that returns a
    // curated list never runs the default's filter. The export is the one admin
    // surface that leaves the database in a file built for sharing, so the
    // confidential columns and their blind-index companions are dropped here,
    // where no model can opt back in.
    let columns: Vec<&'static str> = model
        .csv_export_columns()
        .into_iter()
        .filter(|name| !::autumn_web::confidential::is_confidential_column_name(name))
        .collect();
    let mut buf = Vec::new();
    {
        let mut wtr = csv::WriterBuilder::new()
            .has_headers(true)
            .from_writer(&mut buf);

        wtr.write_record(&columns)
            .map_err(|e| AutumnError::internal_server_error_msg(format!("CSV write error: {e}")))?;

        let mut page: u64 = 1;
        loop {
            let params = ListParams {
                page,
                per_page: EXPORT_PAGE_SIZE,
                search: search.clone(),
                sort_by: sort_key.clone(),
                sort_dir: dir,
                filters: filters.clone(),
            };
            let result = model
                .list(&pool, params)
                .await
                .map_err(|e| admin_err("Export", e))?;
            let done =
                result.records.len() < usize::try_from(EXPORT_PAGE_SIZE).unwrap_or(usize::MAX);
            for record in &result.records {
                let row = model.csv_export_row(&columns, record);
                wtr.write_record(&row).map_err(|e| {
                    AutumnError::internal_server_error_msg(format!("CSV write error: {e}"))
                })?;
            }
            if done {
                break;
            }
            page += 1;
        }

        wtr.flush()
            .map_err(|e| AutumnError::internal_server_error_msg(format!("CSV flush error: {e}")))?;
    }

    let filename = format!("{slug}.csv");
    axum::response::Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, "text/csv; charset=utf-8")
        .header(
            header::CONTENT_DISPOSITION,
            format!("attachment; filename=\"{filename}\""),
        )
        .body(axum::body::Body::from(buf))
        .map_err(|e| AutumnError::internal_server_error_msg(format!("Response error: {e}")))
}

/// `GET /admin/{slug}/import` — Render the CSV import form.
async fn model_import_form(
    ctx: AdminPageCtx,
    State(state): State<AppState>,
    Path(slug): Path<String>,
    flash: Flash,
) -> AutumnResult<Response> {
    let AdminPageCtx { registry, .. } = &ctx;
    let model = registry
        .get(&slug)
        .ok_or_else(|| AutumnError::not_found_msg(format!("Model '{slug}' not found")))?;

    if !model.supports_csv_import() {
        return Err(AutumnError::bad_request_msg(format!(
            "Model '{slug}' does not support CSV import"
        )));
    }

    let _ = state; // pool not needed to render the form
    let messages = flash.consume().await;
    Ok(render(templates::model_import_form_page(
        &ctx.chrome(&messages),
        &slug,
        model.display_name_plural(),
    )))
}

/// `POST /admin/{slug}/import` — Accept a multipart CSV upload and import rows.
#[allow(clippy::too_many_lines)]
async fn model_import_csv(
    ctx: AdminPageCtx,
    State(state): State<AppState>,
    Path(slug): Path<String>,
    flash: Flash,
    mut multipart: Multipart,
) -> AutumnResult<Response> {
    let AdminPageCtx { registry, .. } = &ctx;
    let (pool, model) = resolve(&state, registry, &slug)?;

    if !model.supports_csv_import() {
        return Err(AutumnError::bad_request_msg(format!(
            "Model '{slug}' does not support CSV import"
        )));
    }

    // Read multipart fields: "file" (required) and "mode" (optional).
    let mut csv_bytes: Option<Vec<u8>> = None;
    let mut import_mode = CsvImportMode::Insert;

    while let Some(field) = multipart.next_field().await? {
        match field.name() {
            Some("file") => {
                csv_bytes = Some(field.bytes_limited().await?);
            }
            Some("mode") => {
                let bytes = field.bytes_limited().await?;
                let val = String::from_utf8_lossy(&bytes).into_owned();
                import_mode = CsvImportMode::from_form_value(&val).ok_or_else(|| {
                    AutumnError::bad_request_msg(format!("Unknown import mode: '{val}'"))
                })?;
            }
            _ => {}
        }
    }

    let csv_bytes = csv_bytes
        .ok_or_else(|| AutumnError::bad_request_msg("No CSV file found in the multipart upload"))?;

    // Parse CSV headers first, then process rows.
    let mut rdr = csv::ReaderBuilder::new()
        .has_headers(true)
        .from_reader(csv_bytes.as_slice());

    let headers: Vec<String> = rdr
        .headers()
        .map_err(|e| AutumnError::bad_request_msg(format!("CSV header error: {e}")))?
        .iter()
        .map(str::to_owned)
        .collect();

    let mut report = AdminImportReport::default();

    for result in rdr.records() {
        match result {
            Ok(record) => {
                let line = record.position().map_or(0, csv::Position::line);
                let row: std::collections::HashMap<String, String> = headers
                    .iter()
                    .zip(record.iter())
                    .map(|(k, v)| (k.clone(), v.to_owned()))
                    .collect();

                let outcome = model
                    .import_csv_row(&pool, line, row, import_mode)
                    .await
                    .unwrap_or_else(|e| AdminImportRowResult::RowError(e.to_string()));

                match outcome {
                    AdminImportRowResult::Inserted => report.inserted += 1,
                    AdminImportRowResult::Updated => report.updated += 1,
                    AdminImportRowResult::Skipped => report.skipped += 1,
                    AdminImportRowResult::RowError(msg) => {
                        report.errors.push(AdminImportError {
                            line,
                            column: None,
                            message: msg,
                        });
                    }
                    AdminImportRowResult::FieldError { column, message } => {
                        report.errors.push(AdminImportError {
                            line,
                            column: Some(column),
                            message,
                        });
                    }
                }
            }
            Err(e) => {
                let line = e.position().map_or(0, csv::Position::line);
                report.errors.push(AdminImportError {
                    line,
                    column: None,
                    message: format!("CSV parse error: {e}"),
                });
            }
        }
    }

    let messages = flash.consume().await;
    Ok(render(templates::model_import_result_page(
        &ctx.chrome(&messages),
        &slug,
        model.display_name_plural(),
        &report,
        import_mode,
    )))
}

// ── Runtime config handlers ──────────────────────────────────────────

/// `GET /admin/config` — List all runtime config keys with their values.
async fn config_list(
    ctx: AdminPageCtx,
    axum::Extension(svc): axum::Extension<Arc<RuntimeConfigService>>,
    flash: Flash,
) -> AutumnResult<Response> {
    let entries = svc
        .list()
        .map_err(|e| AutumnError::internal_server_error_msg(format!("Runtime config: {e}")))?;
    let messages = flash.consume().await;
    Ok(render(templates::config_page(
        &ctx.chrome(&messages),
        &entries,
    )))
}

/// `POST /admin/config/{key}/set` — Update a config key's value.
async fn config_set(
    axum::Extension(AdminPrefix(prefix)): axum::Extension<AdminPrefix>,
    axum::Extension(AdminAuthSessionKey(auth_session_key)): axum::Extension<AdminAuthSessionKey>,
    axum::Extension(svc): axum::Extension<Arc<RuntimeConfigService>>,
    session: autumn_web::session::Session,
    Path(key): Path<String>,
    flash: Flash,
    axum::extract::Form(form): axum::extract::Form<HashMap<String, String>>,
) -> AutumnResult<Response> {
    let value = form.get("value").map_or("", String::as_str);
    let actor = config_actor(&session, &auth_session_key).await;
    match svc.set(&key, value, Some(&actor)) {
        Ok(()) => flash.success(format!("Updated {key} = {value}")).await,
        Err(e) => flash.error(format!("Failed to set {key}: {e}")).await,
    }
    Ok(Redirect::to(&format!("{prefix}/config")).into_response())
}

/// Who to record in the runtime-config change history for this request.
///
/// Reads the request's current actor, which the admin router publishes — so
/// while impersonating (#1394) a config change is recorded against the **real
/// operator**, not the customer whose session it is being made from. Falls back
/// to the session's own user, then to `"admin-ui"`, so an app that resolves its
/// principal some other way still gets a name rather than a blank.
async fn config_actor(session: &autumn_web::session::Session, auth_session_key: &str) -> String {
    if let Some(actor) = autumn_web::current::Current::actor() {
        return actor;
    }
    session
        .get(auth_session_key)
        .await
        .unwrap_or_else(|| "admin-ui".to_owned())
}

/// `POST /admin/config/{key}/unset` — Revert a config key to its default.
async fn config_unset(
    axum::Extension(AdminPrefix(prefix)): axum::Extension<AdminPrefix>,
    axum::Extension(AdminAuthSessionKey(auth_session_key)): axum::Extension<AdminAuthSessionKey>,
    axum::Extension(svc): axum::Extension<Arc<RuntimeConfigService>>,
    session: autumn_web::session::Session,
    Path(key): Path<String>,
    flash: Flash,
) -> AutumnResult<Response> {
    let actor = config_actor(&session, &auth_session_key).await;
    match svc.unset(&key, Some(&actor)) {
        Ok(()) => flash.success(format!("Reset {key} to default")).await,
        Err(e) => flash.error(format!("Failed to reset {key}: {e}")).await,
    }
    Ok(Redirect::to(&format!("{prefix}/config")).into_response())
}

/// `GET /admin/config/{key}/history` — View change history for a config key.
async fn config_key_history(
    ctx: AdminPageCtx,
    axum::Extension(svc): axum::Extension<Arc<RuntimeConfigService>>,
    Path(key): Path<String>,
    flash: Flash,
) -> AutumnResult<Response> {
    let history = svc
        .history(&key, 50)
        .map_err(|e| AutumnError::internal_server_error_msg(format!("Runtime config: {e}")))?;
    let messages = flash.consume().await;
    Ok(render(templates::config_history_page(
        &ctx.chrome(&messages),
        &key,
        &history,
    )))
}

// ── Helpers ─────────────────────────────────────────────────────────

/// Filter incoming form data down to fields the model declared as editable.
///
/// Enforcement (all four are necessary):
///
/// 1. **Drop underscore-prefixed keys** (`_csrf` and similar form internals).
/// 2. **Drop keys not declared in `fields`** so a crafted POST can't inject
///    arbitrary columns (e.g. `is_admin=true`) into an `AdminModel::create`.
/// 3. **Drop keys whose `AdminField::editable = false`** so read-only columns
///    (`id`, `created_at`, computed fields, privilege flags) can't be
///    overwritten by admins submitting tampered forms.
/// 4. **Drop `create_only` keys on update** so immutable-after-create fields
///    (e.g. `principal_id`, `expires_at`) can't be silently ignored while
///    an admin thinks they've changed them.
/// 5. **Drop blank string values on declared `Password` fields** so "leave
///    blank to keep current" doesn't wipe stored hashes.
///
/// The UI's readonly contract is the source of truth: if the admin didn't
/// declare a field as editable, model code never sees it.
fn strip_meta_fields(mut data: Value, fields: &[AdminField], for_update: bool) -> Value {
    if let Some(obj) = data.as_object_mut() {
        obj.retain(|k, v| {
            if k.starts_with('_') {
                return false;
            }
            let Some(field) = fields.iter().find(|f| f.name == k) else {
                // Key not in the schema — drop it. Prevents arbitrary columns
                // from being injected past the declared editable surface.
                return false;
            };
            if matches!(field.kind, AdminFieldKind::Hidden) {
                // Hidden fields are read-only by contract, regardless of
                // whether `editable` was flipped back to true — the form
                // never exposes an input for them, so any submitted value
                // is necessarily tampered.
                return false;
            }
            if !field.editable {
                // Readonly field — drop it regardless of submitted value.
                return false;
            }
            if for_update && field.create_only {
                // Immutable-after-create field — drop on update so the model
                // never sees it and the admin can't be misled into thinking
                // the change was persisted.
                return false;
            }
            // Drop blank string values on Password fields so admins editing
            // unrelated fields don't overwrite stored hashes. (Encrypted columns
            // are rendered as disabled, unsubmitted controls in the form, so they
            // never reach this map and need no name-based special-casing here —
            // which also avoids dropping blanks on same-named plaintext columns of
            // other admin resources.)
            !matches!(v, Value::String(s) if s.is_empty() && matches!(field.kind, AdminFieldKind::Password))
        });
    }
    data
}

/// Coerce every field's raw form-string value to its declared type.
///
/// Attempts every field regardless of earlier failures (currently only
/// possible for `Json`) — never stops at the first one — so a field
/// declared after a malformed one still comes back properly typed rather
/// than redisplaying with its pre-coercion raw string (e.g. a checked
/// `Boolean` appearing unchecked, or a valid JSON object getting
/// re-quoted). Returns the fully-attempted `data` alongside every failing
/// field's name and a combined message on error — rather than discarding
/// it — so a caller redisplaying the form after a validation failure can
/// show every successfully coerced field normally and single out just the
/// field(s) that didn't parse (see `render_form_widget`'s `raw_fields`;
/// Codex review, PR #2422).
fn coerce_form_fields(
    mut data: Value,
    fields: &[AdminField],
) -> Result<Value, (Value, Vec<&'static str>, String)> {
    let mut failed_names = Vec::new();
    let mut messages = Vec::new();
    if let Some(obj) = data.as_object_mut() {
        for field in fields {
            let Some(value) = obj.get_mut(field.name) else {
                continue;
            };
            if let Err(msg) = coerce_form_value(value, field) {
                failed_names.push(field.name);
                messages.push(msg);
            }
        }
    }
    if messages.is_empty() {
        Ok(data)
    } else {
        Err((data, failed_names, messages.join("; ")))
    }
}

fn coerce_form_value(value: &mut Value, field: &AdminField) -> Result<(), String> {
    // On a nullable text-ish column (String/Uuid/Enum/Decimal all route to
    // `AdminFieldKind::Text`), as well as the numeric/date kinds, an empty
    // submission clears to NULL — matching the existing numeric/date
    // convention. Required columns deliberately keep the empty string.
    if !field.required
        && field.kind.blank_submission_is_null()
        && matches!(value, Value::String(raw) if raw.trim().is_empty())
    {
        *value = Value::Null;
        return Ok(());
    }

    match &field.kind {
        AdminFieldKind::Boolean => {
            if let Value::String(raw) = value
                && let Some(parsed) = parse_form_bool(raw)
            {
                *value = Value::Bool(parsed);
            }
        }
        AdminFieldKind::Integer => {
            if let Value::String(raw) = value
                && let Ok(parsed) = raw.parse::<i64>()
            {
                *value = Value::Number(parsed.into());
            }
        }
        AdminFieldKind::Float => {
            if let Value::String(raw) = value
                && let Ok(parsed) = raw.parse::<f64>()
                && let Some(number) = serde_json::Number::from_f64(parsed)
            {
                *value = Value::Number(number);
            }
        }
        // Unlike Integer/Float/Boolean above — where a value that fails to
        // parse is simply left as a raw JSON string, and the strict target
        // type (`i64`/`f64`/`bool`) then rejects that string during the
        // model's own `serde_json::from_value` deserialize — a JSON column's
        // Rust type is `serde_json::Value` itself, which happily accepts
        // *any* JSON value, including that leftover raw string. So a
        // malformed submission here needs its own explicit rejection: a
        // required field would otherwise silently persist a string like
        // `"{broken"` as the "JSON" value instead of surfacing a validation
        // error (issue #1341 review). Only the exact empty string is exempt
        // — for a required column it deliberately falls through unparsed,
        // matching the required-text convention below (and ONLY that exact
        // convention: a whitespace-only submission like `"   "` is not
        // "blank", it's malformed JSON, and must still be rejected — a
        // browser's `required` validation accepts whitespace as non-empty,
        // so `raw.trim().is_empty()` would have silently let it through
        // unparsed). For an optional column the blank-to-null short-circuit
        // above already handled every whitespace-only submission.
        AdminFieldKind::Json => {
            if let Value::String(raw) = value
                && !raw.is_empty()
            {
                match serde_json::from_str::<Value>(raw) {
                    Ok(parsed) => *value = parsed,
                    Err(err) => return Err(format!("{}: invalid JSON ({err})", field.name)),
                }
            }
        }
        AdminFieldKind::Text
        | AdminFieldKind::TextArea
        | AdminFieldKind::Date
        | AdminFieldKind::DateTime
        | AdminFieldKind::Select(_)
        | AdminFieldKind::Hidden
        | AdminFieldKind::Password => {}
    }
    Ok(())
}

fn parse_form_bool(raw: &str) -> Option<bool> {
    match raw.trim().to_ascii_lowercase().as_str() {
        "true" | "1" | "yes" | "on" => Some(true),
        "false" | "0" | "no" | "off" | "" => Some(false),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::traits::{AdminFuture, ListResult, SelectOption};
    use autumn_web::job::{JobAdminBackendEntry, JobAdminMemoryBackend};
    use autumn_web::session::Session;
    use axum::body::Body;
    use serde_json::json;
    use std::collections::HashMap;
    use tower::ServiceExt;

    fn fields(specs: &[(&'static str, AdminFieldKind)]) -> Vec<AdminField> {
        specs
            .iter()
            .cloned()
            .map(|(name, kind)| AdminField::new(name, kind))
            .collect()
    }

    // ── Validation-failure redisplay (form data loss on 400) ────────────
    //
    // Baseline (pre-fix): a validation failure on `POST /{slug}` or
    // `POST /{slug}/{id}` — malformed JSON in a `Json` field, or the model
    // rejecting the payload with `AdminError::Validation` — propagated as an
    // `AutumnError`, which the framework's `ErrorPageFilter` renders as a
    // full generic error page (status/title/"Go to homepage" link only).
    // The admin lost every value they had typed; the only recovery step
    // offered was navigating away. See PR description for the audit.
    //
    // A lazy pool that never connects: fine here because every scenario
    // below fails validation before any handler reaches the database.
    fn lazy_pool() -> Pool<::autumn_web::RuntimeConnection> {
        let config = autumn_web::config::DatabaseConfig {
            url: Some("postgres://localhost/unused".into()),
            pool_size: 1,
            ..Default::default()
        };
        autumn_web::db::create_pool(&config)
            .expect("pool config")
            .expect("pool")
    }

    /// Minimal `AdminModel` for exercising the create/update
    /// validation-failure path without a real database. `name == "taken"`
    /// simulates a model-level validation failure (e.g. a uniqueness
    /// check); everything else succeeds. `owner` is `create_only` so it
    /// renders read-only (and is never submitted) on the edit form —
    /// exactly the case that needs the stored record merged back in on
    /// redisplay.
    struct FormTestModel;

    impl AdminModel for FormTestModel {
        fn slug(&self) -> &'static str {
            "widgets"
        }
        fn display_name(&self) -> &'static str {
            "Widget"
        }
        fn display_name_plural(&self) -> &'static str {
            "Widgets"
        }
        fn fields(&self) -> Vec<AdminField> {
            vec![
                AdminField::new("name", AdminFieldKind::Text),
                AdminField::new("owner", AdminFieldKind::Text).create_only(),
                AdminField::new("metadata", AdminFieldKind::Json),
                AdminField::new("api_key", AdminFieldKind::Text)
                    .optional()
                    .encrypted(),
                AdminField::new("published", AdminFieldKind::Boolean).optional(),
            ]
        }
        fn list(
            &self,
            _pool: &Pool<::autumn_web::RuntimeConnection>,
            _params: ListParams,
        ) -> AdminFuture<'_, ListResult> {
            Box::pin(async {
                Ok(ListResult {
                    records: vec![],
                    total: 0,
                    page: 1,
                    per_page: 25,
                })
            })
        }
        fn get(
            &self,
            _pool: &Pool<::autumn_web::RuntimeConnection>,
            id: i64,
        ) -> AdminFuture<'_, Option<Value>> {
            Box::pin(async move {
                if id == 1 {
                    Ok(Some(json!({
                        "id": 1,
                        "name": "Widget One",
                        "owner": "alice",
                        "metadata": {"a": 1},
                    })))
                } else if id == 999 {
                    // Sentinel id simulating a backend outage on the
                    // refetch `merge_with_stored_record` does to redisplay
                    // an update's `create_only` fields correctly.
                    Err(AdminError::Database("simulated outage".into()))
                } else {
                    Ok(None)
                }
            })
        }
        fn create(
            &self,
            _pool: &Pool<::autumn_web::RuntimeConnection>,
            data: Value,
        ) -> AdminFuture<'_, Value> {
            Box::pin(async move {
                if data.get("name").and_then(Value::as_str) == Some("taken") {
                    return Err(AdminError::Validation("name already taken".into()));
                }
                let mut record = data;
                if let Some(obj) = record.as_object_mut() {
                    obj.insert("id".into(), json!(2));
                }
                Ok(record)
            })
        }
        fn update(
            &self,
            _pool: &Pool<::autumn_web::RuntimeConnection>,
            _id: i64,
            data: Value,
        ) -> AdminFuture<'_, Value> {
            Box::pin(async move {
                if data.get("name").and_then(Value::as_str) == Some("taken") {
                    return Err(AdminError::Validation("name already taken".into()));
                }
                Ok(data)
            })
        }
        fn delete(
            &self,
            _pool: &Pool<::autumn_web::RuntimeConnection>,
            _id: i64,
        ) -> AdminFuture<'_, ()> {
            Box::pin(async { Ok(()) })
        }
    }

    fn form_test_app() -> axum::Router {
        let mut registry = AdminRegistry::new();
        registry.register(FormTestModel);
        let session = Session::new_for_test("sid".to_owned(), HashMap::new());
        let state = AppState::for_test().with_pool(lazy_pool());
        admin_router(
            Arc::new(registry),
            "/admin",
            "/actuator".to_owned(),
            AdminGuards {
                auth_session_key: "user_id".to_owned(),
                require_role: None,
                step_up_mutations: false,
                step_up_max_age_secs: autumn_web::step_up::DEFAULT_MAX_AGE_SECS,
            },
            None,
            false,
        )
        .layer(axum::Extension(session))
        .with_state(state)
    }

    async fn post_form(
        app: axum::Router,
        uri: &str,
        pairs: &[(&str, &str)],
    ) -> (StatusCode, String) {
        let body = {
            let mut ser = form_urlencoded::Serializer::new(String::new());
            for (k, v) in pairs {
                ser.append_pair(k, v);
            }
            ser.finish()
        };
        let response = app
            .oneshot(
                axum::http::Request::builder()
                    .method("POST")
                    .uri(uri)
                    .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                    // Real browser form-submit navigation always sends this —
                    // exercise the same HTML error-page path a real admin hits,
                    // not the JSON fallback an unspecified `Accept` would take.
                    .header(header::ACCEPT, "text/html,application/xhtml+xml")
                    .body(Body::from(body))
                    .expect("request"),
            )
            .await
            .expect("response");
        let status = response.status();
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        (status, String::from_utf8(bytes.to_vec()).expect("utf8"))
    }

    // FIXED: a validation failure on `POST /{slug}` or `POST /{slug}/{id}`
    // now re-renders the same form (422, HTML) with every value the admin
    // typed still filled in and the failure surfaced through the same
    // persistent, accessible flash banner every other admin page uses —
    // instead of discarding the form for a bare `application/problem+json`
    // body. See the previous commit for the measured baseline this replaces.
    #[tokio::test]
    async fn model_create_malformed_json_redisplays_form_with_entered_data() {
        let (status, html) = post_form(
            form_test_app(),
            "/widgets",
            &[("name", "Widget X"), ("metadata", "{broken")],
        )
        .await;

        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "html: {html}");
        assert!(html.contains("New Widget"), "html: {html}");
        assert!(html.contains(r#"value="Widget X""#), "html: {html}");
        assert!(html.contains("invalid JSON"), "html: {html}");
        assert!(!html.contains("Go to homepage"), "html: {html}");
        // The malformed text must reach the textarea VERBATIM — not
        // round-tripped through `Value::to_string()`, which would wrap it in
        // an extra pair of quotes (`"{broken"`) and risk silently persisting
        // that as a valid-but-wrong JSON string on a blind resubmit (Codex
        // review, PR #2422).
        assert!(
            html.contains(">{broken</textarea>"),
            "malformed JSON must render raw, unquoted: {html}"
        );
        assert!(
            !html.contains(r"&quot;{broken&quot;") && !html.contains(r#">"{broken"</textarea>"#),
            "malformed JSON must not be re-quoted: {html}"
        );
    }

    #[tokio::test]
    async fn model_create_malformed_json_keeps_encrypted_field_editable() {
        // A validation failure on CREATE passes `Some(record)` to
        // `model_form_page` (the resubmitted values) so they can be
        // refilled — but the encrypted-field branch must still treat this
        // as CREATE (no stored ciphertext to protect yet), not EDIT, or an
        // encrypted field silently becomes a disabled, unsubmittable control
        // and the admin can never get past validation for a model with a
        // required encrypted column (Codex review, PR #2422).
        let (status, html) = post_form(
            form_test_app(),
            "/widgets",
            &[
                ("name", "Widget X"),
                ("metadata", "{broken"),
                ("api_key", "sk-live-123"),
            ],
        )
        .await;

        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "html: {html}");
        assert!(
            html.contains(r#"name="api_key""#),
            "encrypted field must stay submittable on a create failure: {html}"
        );
        // The redacted edit-only control has no `name=` attribute at all (so
        // it never submits and can't overwrite the stored ciphertext) — the
        // `name="api_key"` check above already rules it out; this pins down
        // the other half of that control's shape.
        assert!(
            !html.contains("••••••••"),
            "encrypted field must not show the edit-only redaction mask on create: {html}"
        );
        // The admin's just-typed secret must not round-trip back into the
        // response body (Codex review, PR #2422) — the control stays
        // enabled and submittable, but blank, so they retype it.
        assert!(
            !html.contains("sk-live-123"),
            "encrypted field's plaintext must not leak into the redisplayed HTML: {html}"
        );
    }

    #[tokio::test]
    async fn model_create_malformed_json_keeps_other_fields_coerced() {
        // Codex review, PR #2422: coercion used to stop at the first
        // failure, leaving every later field's raw form string uncoerced —
        // a checked Boolean would redisplay unchecked. `published` is
        // declared after `metadata` on `FormTestModel`, so this exercises
        // exactly that ordering.
        let (status, html) = post_form(
            form_test_app(),
            "/widgets",
            &[
                ("name", "Widget X"),
                ("metadata", "{broken"),
                ("published", "true"),
            ],
        )
        .await;

        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "html: {html}");
        assert!(
            html.contains(r#"id="published" value="true" checked"#),
            "a later field must still coerce and redisplay checked: {html}"
        );
    }

    #[tokio::test]
    async fn model_create_validation_error_redisplays_form_with_entered_data() {
        let (status, html) = post_form(
            form_test_app(),
            "/widgets",
            &[("name", "taken"), ("owner", "bob"), ("metadata", "{}")],
        )
        .await;

        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "html: {html}");
        assert!(html.contains("New Widget"), "html: {html}");
        assert!(html.contains(r#"value="taken""#), "html: {html}");
        assert!(html.contains("name already taken"), "html: {html}");
        assert!(!html.contains("Go to homepage"), "html: {html}");
    }

    #[tokio::test]
    async fn model_update_validation_error_preserves_create_only_field_and_entered_data() {
        let (status, html) = post_form(
            form_test_app(),
            "/widgets/1",
            &[("name", "taken"), ("metadata", "{}")],
        )
        .await;

        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "html: {html}");
        assert!(html.contains("Edit Widget"), "html: {html}");
        assert!(html.contains(r#"value="taken""#), "html: {html}");
        assert!(html.contains("name already taken"), "html: {html}");
        // `owner` is create_only: never submitted by the edit form (it
        // renders read-only, with no `name=` attribute). It must still show
        // its stored value on redisplay instead of going blank.
        assert!(html.contains("alice"), "html: {html}");
        assert!(!html.contains("Go to homepage"), "html: {html}");
    }

    #[tokio::test]
    async fn model_update_validation_error_propagates_a_refetch_backend_failure() {
        // Codex review, PR #2422: `merge_with_stored_record`'s refetch (done
        // purely to redisplay `create_only` fields correctly) used to turn
        // ANY error from it — including a real backend outage — into a
        // silent fallback, masking the outage as an ordinary 422 validation
        // failure with blanked-out `create_only` fields. It must surface as
        // the normal error response instead.
        let (status, body) = post_form(
            form_test_app(),
            "/widgets/999",
            &[("name", "taken"), ("metadata", "{}")],
        )
        .await;

        assert_ne!(
            status,
            StatusCode::UNPROCESSABLE_ENTITY,
            "a backend outage on the refetch must not be reported as a validation failure: {body}"
        );
        assert!(status.is_server_error(), "status: {status}, body: {body}");
        assert!(body.contains("simulated outage"), "body: {body}");
    }

    #[tokio::test]
    async fn jobs_route_renders_without_database_pool() {
        let backend = JobAdminMemoryBackend::new();
        let state =
            AppState::for_test().with_extension(JobAdminBackendEntry(std::sync::Arc::new(backend)));
        state.task_registry().register_scheduled(
            "cleanup",
            "every 60s",
            autumn_web::task::TaskCoordination::Fleet,
            "local",
            "replica-a",
        );
        state
            .task_registry()
            .record_next_run_at("cleanup", "2026-05-08T12:00:00Z");
        let session = Session::new_for_test("sid".to_owned(), HashMap::new());
        let app = admin_router(
            std::sync::Arc::new(AdminRegistry::new()),
            "/admin",
            "/actuator".to_owned(),
            AdminGuards {
                auth_session_key: "user_id".to_owned(),
                require_role: None,
                step_up_mutations: false,
                step_up_max_age_secs: autumn_web::step_up::DEFAULT_MAX_AGE_SECS,
            },
            None,
            false,
        )
        .layer(axum::Extension(session))
        .with_state(state);

        let response = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/jobs")
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");
        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let html = String::from_utf8(body.to_vec()).expect("utf8");
        assert!(html.contains("Jobs"), "html: {html}");
        assert!(html.contains("Enqueued"), "html: {html}");
        assert!(
            html.contains(r#"hx-get="/admin/jobs/counters""#),
            "html: {html}"
        );
        assert!(html.contains("cleanup"), "html: {html}");
        assert!(html.contains("2026-05-08T12:00:00Z"), "html: {html}");
    }

    #[test]
    fn strip_meta_removes_csrf_and_underscore_fields() {
        let input = json!({"name": "x", "_csrf": "t", "_foo": 1});
        let out = strip_meta_fields(input, &fields(&[("name", AdminFieldKind::Text)]), false);
        assert_eq!(out, json!({"name": "x"}));
    }

    #[test]
    fn strip_meta_drops_blank_password_by_declared_kind() {
        let fields = fields(&[
            ("password", AdminFieldKind::Password),
            ("other", AdminFieldKind::Text),
        ]);
        let out = strip_meta_fields(json!({"password": "", "other": "y"}), &fields, false);
        assert_eq!(out, json!({"other": "y"}));

        let out = strip_meta_fields(json!({"password": "hunter2", "other": "y"}), &fields, false);
        assert_eq!(out, json!({"password": "hunter2", "other": "y"}));
    }

    #[test]
    fn strip_meta_drops_blank_custom_named_password() {
        // Regression: the old name-heuristic version missed this.
        // A field called "secret" declared as Password must still be stripped.
        let fields = fields(&[("secret", AdminFieldKind::Password)]);
        let out = strip_meta_fields(json!({"secret": ""}), &fields, false);
        assert_eq!(out, json!({}));
    }

    #[test]
    fn strip_meta_preserves_blank_non_password_fields() {
        let fields = fields(&[
            ("name", AdminFieldKind::Text),
            ("bio", AdminFieldKind::TextArea),
        ]);
        let out = strip_meta_fields(json!({"name": "", "bio": ""}), &fields, false);
        assert_eq!(out, json!({"name": "", "bio": ""}));
    }

    #[test]
    fn coerce_form_fields_converts_boolean_strings() {
        let fields = fields(&[("published", AdminFieldKind::Boolean)]);
        let out = coerce_form_fields(json!({"published": "true"}), &fields).unwrap();
        assert_eq!(out, json!({"published": true}));

        let out = coerce_form_fields(json!({"published": "false"}), &fields).unwrap();
        assert_eq!(out, json!({"published": false}));
    }

    #[test]
    fn coerce_form_fields_converts_numeric_and_json_strings() {
        let fields = fields(&[
            ("count", AdminFieldKind::Integer),
            ("rating", AdminFieldKind::Float),
            ("settings", AdminFieldKind::Json),
        ]);
        let out = coerce_form_fields(
            json!({
                "count": "42",
                "rating": "3.5",
                "settings": "{\"published\":true}"
            }),
            &fields,
        )
        .unwrap();

        assert_eq!(
            out,
            json!({
                "count": 42,
                "rating": 3.5,
                "settings": {"published": true}
            })
        );
    }

    #[test]
    fn coerce_form_fields_converts_blank_optional_numeric_strings_to_null() {
        let fields = vec![
            AdminField::new("count", AdminFieldKind::Integer).optional(),
            AdminField::new("rating", AdminFieldKind::Float).optional(),
        ];
        let out = coerce_form_fields(json!({"count": "", "rating": ""}), &fields).unwrap();

        assert_eq!(out, json!({"count": null, "rating": null}));
    }

    #[test]
    fn coerce_form_fields_converts_blank_optional_date_strings_to_null() {
        let fields = vec![
            AdminField::new("published_on", AdminFieldKind::Date).optional(),
            AdminField::new("starts_at", AdminFieldKind::DateTime).optional(),
        ];
        let out =
            coerce_form_fields(json!({"published_on": "", "starts_at": "   "}), &fields).unwrap();

        assert_eq!(out, json!({"published_on": null, "starts_at": null}));
    }

    #[test]
    fn coerce_form_fields_converts_blank_optional_textish_strings_to_null() {
        // Text-routed nullable columns (String/Uuid/Enum/Decimal all map to
        // `AdminFieldKind::Text`) clear to NULL on an empty submission, matching
        // the numeric/date convention.
        let fields = vec![
            AdminField::new("token", AdminFieldKind::Text).optional(),
            AdminField::new("notes", AdminFieldKind::TextArea).optional(),
            AdminField::new(
                "status",
                AdminFieldKind::Select(vec![SelectOption {
                    value: "a".to_owned(),
                    label: "A".to_owned(),
                }]),
            )
            .optional(),
        ];
        let out = coerce_form_fields(json!({"token": "", "notes": "   ", "status": ""}), &fields)
            .unwrap();

        assert_eq!(out, json!({"token": null, "notes": null, "status": null}));
    }

    #[test]
    fn coerce_form_fields_converts_blank_optional_json_to_null() {
        // A blank submission on a nullable JSON column clears to NULL rather
        // than silently storing `Value::String("")` (which `serde_json::from_str`
        // can't parse, so the raw empty string would otherwise be persisted).
        // The null-coercion short-circuit runs before the JSON parse arm.
        let fields = vec![AdminField::new("settings", AdminFieldKind::Json).optional()];

        let out = coerce_form_fields(json!({"settings": ""}), &fields).unwrap();
        assert_eq!(out, json!({"settings": null}));

        let out = coerce_form_fields(json!({"settings": "   "}), &fields).unwrap();
        assert_eq!(out, json!({"settings": null}));

        // A non-blank optional JSON submission still parses normally.
        let out = coerce_form_fields(json!({"settings": "{\"published\":true}"}), &fields).unwrap();
        assert_eq!(out, json!({"settings": {"published": true}}));
    }

    #[test]
    fn coerce_form_fields_keeps_blank_required_json_as_empty_string() {
        // Required columns keep the empty string rather than clearing to NULL,
        // matching the required-text convention. A blank submission is exempt
        // from the malformed-JSON rejection below — it's left for the model's
        // own required-field validation to catch.
        let fields = vec![AdminField::new("settings", AdminFieldKind::Json)];
        let out = coerce_form_fields(json!({"settings": ""}), &fields).unwrap();
        assert_eq!(out, json!({"settings": ""}));
    }

    #[test]
    fn coerce_form_fields_keeps_blank_required_text_as_empty_string() {
        // Required columns keep the empty string rather than clearing to NULL.
        let fields = vec![AdminField::new("token", AdminFieldKind::Text)];
        let out = coerce_form_fields(json!({"token": ""}), &fields).unwrap();

        assert_eq!(out, json!({"token": ""}));
    }

    #[test]
    fn coerce_form_fields_rejects_malformed_non_blank_json() {
        // Issue #1341 review: unlike Integer/Float/Boolean, a JSON column's
        // Rust type (`serde_json::Value`) accepts *any* JSON value — including
        // a raw string — so a malformed, non-blank submission must be rejected
        // here rather than silently persisted as a JSON string literal.
        let fields = vec![AdminField::new("settings", AdminFieldKind::Json)];
        let (partial, field_names, msg) =
            coerce_form_fields(json!({"settings": "{broken"}), &fields)
                .expect_err("malformed non-blank JSON must be rejected, not silently stored");
        assert_eq!(
            field_names,
            vec!["settings"],
            "error should name the offending field"
        );
        assert!(msg.contains("settings"), "error message: {msg}");
        // The raw, unparsed text survives in the partial result so the caller
        // can redisplay exactly what the admin typed.
        assert_eq!(partial, json!({"settings": "{broken"}));

        // Nullable columns are rejected the same way.
        let fields = vec![AdminField::new("settings", AdminFieldKind::Json).optional()];
        assert!(coerce_form_fields(json!({"settings": "{broken"}), &fields).is_err());

        // A syntactically valid JSON string scalar (not a formula/exploit —
        // just quoted text) is NOT malformed and must still round-trip.
        let fields = vec![AdminField::new("settings", AdminFieldKind::Json)];
        let out = coerce_form_fields(json!({"settings": "\"not broken\""}), &fields).unwrap();
        assert_eq!(out, json!({"settings": "not broken"}));
    }

    #[test]
    fn coerce_form_fields_partial_result_keeps_earlier_fields_coerced() {
        // A field ahead of the failing one in declaration order must still
        // come back properly typed in the partial result — only the failing
        // field itself is left as raw text (routes.rs's redisplay path
        // relies on this: every other widget renders normally).
        let fields = vec![
            AdminField::new("count", AdminFieldKind::Integer),
            AdminField::new("settings", AdminFieldKind::Json),
        ];
        let (partial, field_names, _msg) =
            coerce_form_fields(json!({"count": "42", "settings": "{broken"}), &fields)
                .expect_err("malformed JSON must be rejected");
        assert_eq!(field_names, vec!["settings"]);
        assert_eq!(partial, json!({"count": 42, "settings": "{broken"}));
    }

    #[test]
    fn coerce_form_fields_still_coerces_fields_declared_after_a_failure() {
        // Codex review, PR #2422: stopping at the first failure left every
        // LATER field's raw form string uncoerced too — a checked Boolean
        // after a malformed Json field would redisplay unchecked, and if the
        // admin didn't notice and resubmitted, that wrong value would be
        // persisted. Coercion must keep going past a failure.
        let fields = vec![
            AdminField::new("settings", AdminFieldKind::Json),
            AdminField::new("published", AdminFieldKind::Boolean),
        ];
        let (partial, field_names, _msg) =
            coerce_form_fields(json!({"settings": "{broken", "published": "true"}), &fields)
                .expect_err("malformed JSON must be rejected");
        assert_eq!(field_names, vec!["settings"]);
        assert_eq!(
            partial,
            json!({"settings": "{broken", "published": true}),
            "a field declared after the failing one must still coerce"
        );
    }

    #[test]
    fn coerce_form_fields_collects_every_failing_field() {
        // Two independently malformed Json fields must both be named and
        // both kept as raw text — not just the first one encountered.
        let fields = vec![
            AdminField::new("a", AdminFieldKind::Json),
            AdminField::new("b", AdminFieldKind::Json),
        ];
        let (partial, field_names, msg) =
            coerce_form_fields(json!({"a": "{broken", "b": "[also-broken"}), &fields)
                .expect_err("both malformed fields must be rejected");
        assert_eq!(field_names, vec!["a", "b"]);
        assert!(msg.contains('a') && msg.contains('b'), "message: {msg}");
        assert_eq!(partial, json!({"a": "{broken", "b": "[also-broken"}));
    }

    #[test]
    fn coerce_form_fields_rejects_whitespace_only_required_json() {
        // Issue #1341 review: a browser's `required` validation treats
        // whitespace as satisfying the constraint, so a required JSON field
        // can receive "   " even though it's not the exact blank string the
        // required-text convention exempts. Whitespace-only content is
        // malformed JSON (not valid on its own) and must be rejected — not
        // silently skipped past parsing and persisted as a literal
        // `Value::String("   ")`.
        let fields = vec![AdminField::new("settings", AdminFieldKind::Json)];
        assert!(
            coerce_form_fields(json!({"settings": "   "}), &fields).is_err(),
            "whitespace-only required JSON must be rejected, not silently stored"
        );

        // The exact empty string is still exempt (unchanged pre-existing
        // behavior, matching the required-text convention).
        let out = coerce_form_fields(json!({"settings": ""}), &fields).unwrap();
        assert_eq!(out, json!({"settings": ""}));
    }

    #[test]
    fn validate_sort_key_passes_known_sortable_displayed_fields() {
        let fields = fields(&[("name", AdminFieldKind::Text)]);
        assert_eq!(
            validate_sort_key(Some("name".to_owned()), &fields),
            Some("name".to_owned())
        );
    }

    #[test]
    fn validate_sort_key_drops_unknown_keys() {
        // Crafted `?sort=<unexpected>` reaches model handler — must be dropped.
        let fields = fields(&[("name", AdminFieldKind::Text)]);
        assert_eq!(
            validate_sort_key(Some("DROP TABLE users".into()), &fields),
            None
        );
        assert_eq!(validate_sort_key(Some("password".into()), &fields), None);
    }

    #[test]
    fn validate_sort_key_drops_non_sortable_fields() {
        let mut computed = AdminField::new("computed", AdminFieldKind::Text);
        computed.sortable = false;
        let schema = vec![computed];
        assert_eq!(validate_sort_key(Some("computed".into()), &schema), None);
    }

    #[test]
    fn validate_sort_key_drops_hidden_columns() {
        // Fields excluded from list_display can't be sorted by URL crafting
        // either — the affordance doesn't exist in the UI.
        let mut secret = AdminField::new("secret", AdminFieldKind::Text);
        secret.list_display = false;
        let schema = vec![secret];
        assert_eq!(validate_sort_key(Some("secret".into()), &schema), None);
    }

    #[test]
    fn validate_sort_key_drops_sensitive_kinds_even_if_flagged_sortable() {
        // AdminField::new defaults sortable=true and list_display=true for
        // every kind, so without an explicit kind check, crafted
        // `?sort=password_hash` or `?sort=internal_token` would reach the
        // model. Mirror the template's Hidden/Password exclusion.
        let pw = AdminField::new("password_hash", AdminFieldKind::Password);
        let hidden = AdminField::new("internal_token", AdminFieldKind::Hidden);
        let schema = vec![pw, hidden];
        assert_eq!(
            validate_sort_key(Some("password_hash".into()), &schema),
            None
        );
        assert_eq!(
            validate_sort_key(Some("internal_token".into()), &schema),
            None
        );
    }

    #[test]
    fn extract_filters_keeps_declared_filterable_fields() {
        let mut status = AdminField::new("status", AdminFieldKind::Text);
        status.filterable = true;
        let schema = vec![status, AdminField::new("name", AdminFieldKind::Text)];
        let raw = HashMap::from([
            ("filter.status".into(), "active".into()),
            ("filter.name".into(), "alice".into()), // not filterable — drop
            ("page".into(), "1".into()),            // not a filter — drop
            ("filter.unknown".into(), "x".into()),  // not in schema — drop
        ]);
        let out = extract_filters(&raw, &schema);
        assert_eq!(out, vec![("status".to_owned(), "active".to_owned())]);
    }

    #[test]
    fn extract_filters_drops_empty_values() {
        let mut status = AdminField::new("status", AdminFieldKind::Text);
        status.filterable = true;
        let schema = vec![status];
        let raw = HashMap::from([("filter.status".into(), String::new())]);
        assert_eq!(extract_filters(&raw, &schema), vec![]);
    }

    #[test]
    fn extract_filters_handles_no_filters() {
        let schema = vec![AdminField::new("name", AdminFieldKind::Text)];
        let raw = HashMap::from([("page".into(), "2".into()), ("q".into(), "x".into())]);
        assert_eq!(extract_filters(&raw, &schema), vec![]);
    }

    #[test]
    fn extract_filters_sorts_for_stable_output() {
        let mut a = AdminField::new("zeta", AdminFieldKind::Text);
        a.filterable = true;
        let mut b = AdminField::new("alpha", AdminFieldKind::Text);
        b.filterable = true;
        let schema = vec![a, b];
        let raw = HashMap::from([
            ("filter.zeta".into(), "z".into()),
            ("filter.alpha".into(), "a".into()),
        ]);
        let out = extract_filters(&raw, &schema);
        assert_eq!(
            out,
            vec![
                ("alpha".to_owned(), "a".to_owned()),
                ("zeta".to_owned(), "z".to_owned()),
            ]
        );
    }

    #[test]
    fn validate_sort_key_passes_through_none() {
        let fields = fields(&[("name", AdminFieldKind::Text)]);
        assert_eq!(validate_sort_key(None, &fields), None);
    }

    #[test]
    fn admin_err_maps_variants_to_correct_status() {
        use axum::http::StatusCode;
        assert_eq!(
            admin_err("X", AdminError::NotFound).status(),
            StatusCode::NOT_FOUND
        );
        assert_eq!(
            admin_err("X", AdminError::Validation("bad".into())).status(),
            StatusCode::BAD_REQUEST
        );
        assert_eq!(
            admin_err("X", AdminError::Database("pg down".into())).status(),
            StatusCode::INTERNAL_SERVER_ERROR
        );
        assert_eq!(
            admin_err("X", AdminError::Other("boom".into())).status(),
            StatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn admin_csrf_extractor_returns_empty_when_layer_missing() {
        // Simulate a dev/test setup where CsrfLayer is not installed.
        let req = axum::http::Request::builder().uri("/").body(()).unwrap();
        let (mut parts, ()) = req.into_parts();
        let extracted = AdminCsrf::from_request_parts(&mut parts, &())
            .await
            .expect("infallible");
        assert_eq!(extracted.token(), "");
        assert_eq!(extracted.form_field(), "_csrf");
    }

    #[tokio::test]
    async fn admin_csrf_extractor_reads_token_from_extensions() {
        // Build a CsrfToken the way CsrfLayer would — via its public
        // `FromRequestParts`-adjacent API isn't exposed, so reach through
        // the debug impl: we can't construct CsrfToken outside its crate.
        // Instead, verify the extractor at least doesn't panic when the
        // extension IS present by round-tripping through an axum handler.
        use axum::Router;
        use axum::body::Body;
        use axum::http::StatusCode;
        use axum::routing::get;
        use tower::ServiceExt;

        async fn handler(csrf: AdminCsrf) -> String {
            csrf.token().to_owned()
        }
        let app = Router::new().route("/", get(handler));
        let res = app
            .oneshot(
                axum::http::Request::builder()
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        // No panic, no 500 — just an empty-string body because no CsrfLayer.
        assert_eq!(res.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn admin_csrf_extractor_reads_configured_form_field_from_extensions() {
        let req = axum::http::Request::builder().uri("/").body(()).unwrap();
        let (mut parts, ()) = req.into_parts();
        parts
            .extensions
            .insert(CsrfFormField("authenticity_token".to_owned()));

        let extracted = AdminCsrf::from_request_parts(&mut parts, &())
            .await
            .expect("infallible");

        assert_eq!(extracted.token(), "");
        assert_eq!(extracted.form_field(), "authenticity_token");
    }

    #[test]
    fn strip_meta_keeps_field_named_password_if_not_declared_as_such() {
        // If the model exposes a Text field literally named "password" (weird
        // but legal), we should NOT drop the empty string — the model gets to
        // decide. Only `AdminFieldKind::Password` triggers the strip.
        let fields = fields(&[("password", AdminFieldKind::Text)]);
        let out = strip_meta_fields(json!({"password": ""}), &fields, false);
        assert_eq!(out, json!({"password": ""}));
    }

    #[test]
    fn strip_meta_drops_fields_not_in_schema() {
        // Prevents a crafted POST from injecting arbitrary columns past the
        // declared editable surface (e.g. `is_admin=true` on a users model
        // that doesn't expose it).
        let fields = fields(&[("name", AdminFieldKind::Text)]);
        let input = json!({"name": "x", "is_admin": true, "raw_column": "y"});
        let out = strip_meta_fields(input, &fields, false);
        assert_eq!(out, json!({"name": "x"}));
    }

    #[test]
    fn strip_meta_drops_hidden_fields_even_if_editable_true() {
        // Defense in depth: even if a caller flipped `editable` back to true
        // on a Hidden field (which `AdminField::new` defaults to `false`),
        // the server must still reject it — the form never exposes an input
        // so any submitted value is tampered.
        let mut hidden = AdminField::new("owner_id", AdminFieldKind::Hidden);
        hidden.editable = true; // deliberately wrong
        let schema = vec![hidden];
        let out = strip_meta_fields(json!({"owner_id": 999}), &schema, false);
        assert_eq!(out, json!({}));
    }

    #[test]
    fn strip_meta_drops_create_only_fields_on_update_but_keeps_on_create() {
        let mut principal = AdminField::new("principal_id", AdminFieldKind::Text);
        principal.create_only = true;
        let name = AdminField::new("name", AdminFieldKind::Text);
        let schema = vec![principal, name];
        let input = json!({"principal_id": "svc:x", "name": "my-token"});

        // create context — create_only field is kept
        let out = strip_meta_fields(input.clone(), &schema, false);
        assert_eq!(out, json!({"principal_id": "svc:x", "name": "my-token"}));

        // update context — create_only field is dropped
        let out = strip_meta_fields(input, &schema, true);
        assert_eq!(out, json!({"name": "my-token"}));
    }

    #[test]
    fn strip_meta_drops_readonly_fields() {
        // `editable = false` fields (id, created_at, computed, privilege
        // flags) must not be forwarded to model code even if submitted.
        let mut id = AdminField::new("id", AdminFieldKind::Integer);
        id.editable = false;
        let mut created_at = AdminField::new("created_at", AdminFieldKind::DateTime);
        created_at.editable = false;
        let name = AdminField::new("name", AdminFieldKind::Text);
        let schema = vec![id, created_at, name];

        let input = json!({
            "id": 999,
            "created_at": "2026-01-01T00:00:00Z",
            "name": "legit",
        });
        let out = strip_meta_fields(input, &schema, false);
        assert_eq!(out, json!({"name": "legit"}));
    }

    // ── parse_form_bool coverage ──────────────────────────────────────

    #[test]
    fn parse_form_bool_recognizes_truthy_falsy_and_unknown_variants() {
        // Truthy variants
        assert_eq!(parse_form_bool("true"), Some(true));
        assert_eq!(parse_form_bool("1"), Some(true));
        assert_eq!(parse_form_bool("yes"), Some(true));
        assert_eq!(parse_form_bool("on"), Some(true));
        assert_eq!(parse_form_bool("TRUE"), Some(true)); // case-insensitive
        assert_eq!(parse_form_bool("YES"), Some(true));
        // Falsy variants
        assert_eq!(parse_form_bool("false"), Some(false));
        assert_eq!(parse_form_bool("0"), Some(false));
        assert_eq!(parse_form_bool("no"), Some(false));
        assert_eq!(parse_form_bool("off"), Some(false));
        assert_eq!(parse_form_bool(""), Some(false));
        assert_eq!(parse_form_bool("  "), Some(false)); // trims whitespace
        // Unknown → None (value is left as-is by coerce_form_value)
        assert_eq!(parse_form_bool("maybe"), None);
        assert_eq!(parse_form_bool("y"), None);
        assert_eq!(parse_form_bool("2"), None);
    }

    // ── extract_reveal_cookie ─────────────────────────────────────────────────

    fn headers_with_cookie(cookie: &str) -> axum::http::HeaderMap {
        let mut map = axum::http::HeaderMap::new();
        map.insert(
            axum::http::header::COOKIE,
            axum::http::HeaderValue::from_str(cookie).unwrap(),
        );
        map
    }

    #[test]
    fn extract_reveal_cookie_returns_none_when_no_cookie_header() {
        let headers = axum::http::HeaderMap::new();
        assert!(extract_reveal_cookie(&headers).is_none());
    }

    #[test]
    fn extract_reveal_cookie_returns_none_when_cookie_absent_from_header() {
        let headers = headers_with_cookie("session=abc; other=xyz");
        assert!(extract_reveal_cookie(&headers).is_none());
    }

    #[test]
    fn extract_reveal_cookie_returns_none_when_value_is_empty() {
        let headers = headers_with_cookie("__autumn_reveal=; session=abc");
        assert!(extract_reveal_cookie(&headers).is_none());
    }

    #[test]
    fn extract_reveal_cookie_returns_value_when_present() {
        let headers = headers_with_cookie("session=abc; __autumn_reveal=tok123; other=xyz");
        assert_eq!(extract_reveal_cookie(&headers).as_deref(), Some("tok123"));
    }

    #[test]
    fn extract_reveal_cookie_handles_leading_only_cookie() {
        let headers = headers_with_cookie("__autumn_reveal=supersecret");
        assert_eq!(
            extract_reveal_cookie(&headers).as_deref(),
            Some("supersecret")
        );
    }
}