rustio-core 1.8.0

RustIO runtime library: HTTP, router, Postgres ORM, admin, RBAC, search, migrations, AI planner.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
//! Template context builders. Every piece of data the admin templates
//! need comes from here, as a `serde::Serialize` struct. No HTML lives
//! in Rust code.
//!
//! # Phase 6a: shared `BaseContext`
//!
//! Every page context embeds [`BaseContext`] via `#[serde(flatten)]`.
//! That gives every template uniform access to `identity`,
//! `csrf_token`, `site_title`, and `site_header` without per-page
//! plumbing. `identity` is `Option<…>` because the login page renders
//! before authentication.

use std::collections::HashMap;

use serde::Serialize;

use super::audit::AdminAction;
use super::types::{Admin, AdminEntry, AdminField, EditRow, ListRow};
use crate::auth::Identity;
use crate::error::Result;
use crate::http::FormData;
use crate::orm::Db;

#[derive(Serialize)]
pub(crate) struct IdentityCtx {
    pub email: String,
    pub is_admin: bool,
    /// Phase 7a/2 — exposed so the sidebar can show the
    /// Developer-only section (`/admin/__schema__`, `/__logs__`,
    /// `/__sql_console__`) without making it look like dead nav for
    /// Administrator-rank users.
    pub is_developer: bool,
}

impl From<&Identity> for IdentityCtx {
    fn from(i: &Identity) -> Self {
        Self {
            email: i.email.clone(),
            is_admin: i.is_admin(),
            is_developer: i.is_active && i.role.includes(crate::auth::Role::Developer),
        }
    }
}

#[derive(Serialize)]
pub(crate) struct BaseContext {
    pub identity: Option<IdentityCtx>,
    pub csrf_token: String,
    pub site_title: String,
    pub site_header: String,
    pub index_title: String,
    pub footer_copyright: String,
    /// Phase 7a/0.5/d — `true` when the active session belongs to a
    /// demo user (`is_demo` column on `rustio_users`). Templates use
    /// this to render the red banner above the page content.
    pub is_demo_session: bool,
    /// Optional human-readable label for the demo user
    /// ("Demo Staff", "Demo Administrator"). Rendered in parens after
    /// the banner's "DEMO USER" text when present.
    pub demo_label: Option<String>,
}

impl BaseContext {
    /// Build the shared base context every page extends. Reads the
    /// active branding from `&Admin` so projects can override defaults
    /// via `Admin::site_branding(...)`. Future Phase 8/9 may pull more
    /// from `Admin` (locale, theme) without re-touching every handler.
    pub fn new(identity: Option<&Identity>, csrf_token: String, admin: &Admin) -> Self {
        let b = admin.branding();
        let (is_demo_session, demo_label) = match identity {
            Some(i) => (i.is_demo, i.demo_label.clone()),
            None => (false, None),
        };
        Self {
            identity: identity.map(IdentityCtx::from),
            csrf_token,
            site_title: b.site_title.clone(),
            site_header: b.site_header.clone(),
            index_title: b.index_title.clone(),
            footer_copyright: b.footer_copyright.clone(),
            is_demo_session,
            demo_label,
        }
    }
}

#[derive(Serialize)]
pub(crate) struct SidebarEntry {
    pub admin_name: &'static str,
    pub display_name: &'static str,
}

impl From<&AdminEntry> for SidebarEntry {
    fn from(e: &AdminEntry) -> Self {
        Self {
            admin_name: e.admin_name,
            display_name: e.display_name,
        }
    }
}

#[derive(Serialize)]
pub(crate) struct FlashCtx {
    pub kind: &'static str,
    pub message: String,
}

// ---- Page contexts --------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct LoginCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub error: Option<String>,
    /// Phase 6.2 — login form fields (email + password) rendered via
    /// the shared `_form_field.html` include. Page chrome (card,
    /// hidden sidebar/breadcrumbs) stays bespoke.
    pub sections: Vec<FormSection>,
    /// Phase 11.B — contextual notice rendered above the card via the
    /// shared `messagelist` block in `base.html`. Currently used for the
    /// post-logout confirmation ("You've been signed out."). `kind` maps
    /// to the existing `.message-success` / `.message-info` styles.
    pub flash: Option<FlashCtx>,
}

/// Phase 6.2 — pre-built FormField list for the login form. Static
/// because the values never change between requests; built once and
/// cloned into LoginCtx.sections.
pub(crate) fn login_form_sections() -> Vec<FormSection> {
    vec![FormSection {
        title: None,
        fields: vec![
            FormField {
                name: "email",
                label: "Email".to_string(),
                widget: "input",
                input_type: "email",
                value: String::new(),
                hint: None,
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 1,
                autocomplete: Some("username"),
                autofocus: true,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "password",
                label: "Password".to_string(),
                widget: "input",
                input_type: "password",
                value: String::new(),
                hint: None,
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 1,
                autocomplete: Some("current-password"),
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
        ],
    }]
}

// ---------------------------------------------------------------------------
// Dashboard
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct DashboardCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    /// Phase 7a/2 — sidebar nav. Same shape every other page already
    /// uses (list/form/confirm-delete/builtin), so the base.html
    /// sidebar partial works uniformly across all pages.
    pub entries: Vec<SidebarEntry>,
    pub apps: Vec<DashboardApp>,
    pub recent_actions: Vec<RecentActionCtx>,
    pub flash: Option<FlashCtx>,
}

#[derive(Serialize)]
pub(crate) struct DashboardApp {
    pub label: String,
    pub models: Vec<DashboardModel>,
}

#[derive(Serialize)]
pub(crate) struct DashboardModel {
    pub admin_name: &'static str,
    pub display_name: &'static str,
    pub field_count: usize,
}

#[derive(Serialize)]
pub(crate) struct RecentActionCtx {
    pub action_type: String,
    pub label: &'static str,
    pub pill_class: &'static str,
    pub model_name: String,
    pub object_id: i64,
    pub user_email: String,
    pub summary: String,
    pub when_relative: String,
}

/// Group every `AdminEntry` by `app_label` derived from `admin_name`.
///
/// Convention: if `admin_name` contains a `.`, the prefix is the app
/// label (e.g. `"tolkhuset.translators"` → label `"Tolkhuset"`); the
/// remaining path is the model slug. Otherwise the whole `admin_name`
/// becomes a single-app label, capitalised.
pub(crate) fn group_entries_by_app(entries: &[AdminEntry]) -> Vec<DashboardApp> {
    let mut apps: Vec<DashboardApp> = Vec::new();
    for entry in entries {
        // Core entries (currently just the synthetic User) have a
        // bespoke admin page reachable via the header's Users link.
        // Listing them here would offer "Add"/"Change" actions that
        // route through CoreUserOps, which is schema-only — hitting
        // either button 500s. Skip them entirely.
        if entry.core {
            continue;
        }
        let label = app_label_for(entry.admin_name);
        let app = match apps.iter_mut().find(|a| a.label == label) {
            Some(a) => a,
            None => {
                apps.push(DashboardApp {
                    label: label.clone(),
                    models: Vec::new(),
                });
                apps.last_mut().unwrap()
            }
        };
        app.models.push(DashboardModel {
            admin_name: entry.admin_name,
            display_name: entry.display_name,
            field_count: entry.fields.len(),
        });
    }
    apps
}

pub(crate) fn app_label_for(admin_name: &str) -> String {
    let prefix = admin_name.split('.').next().unwrap_or(admin_name);
    capitalise(prefix)
}

fn capitalise(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

pub(crate) fn dashboard_ctx(
    identity: &Identity,
    admin: &Admin,
    recent_actions: Vec<AdminAction>,
    csrf_token: String,
) -> DashboardCtx {
    let recent = recent_actions
        .into_iter()
        .map(|a| RecentActionCtx {
            action_type: a.action_type.clone(),
            label: action_label(&a.action_type),
            pill_class: action_pill_class(&a.action_type),
            model_name: a.model_name,
            object_id: a.object_id,
            user_email: a.user_email.unwrap_or_else(|| "".to_string()),
            summary: a.summary,
            when_relative: relative_time(a.timestamp),
        })
        .collect();

    DashboardCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        apps: group_entries_by_app(admin.entries()),
        recent_actions: recent,
        flash: None,
    }
}

fn action_label(action_type: &str) -> &'static str {
    match action_type {
        "create" => "Created",
        "update" => "Changed",
        "delete" => "Deleted",
        _ => "Action",
    }
}

fn action_pill_class(action_type: &str) -> &'static str {
    match action_type {
        "create" => "badge-success",
        "update" => "badge-neutral",
        "delete" => "badge-danger",
        _ => "badge-neutral",
    }
}

pub(crate) fn relative_time(ts: chrono::DateTime<chrono::Utc>) -> String {
    let now = chrono::Utc::now();
    let delta = now - ts;
    if delta.num_seconds() < 60 {
        "just now".to_string()
    } else if delta.num_minutes() < 60 {
        format!("{}m ago", delta.num_minutes())
    } else if delta.num_hours() < 24 {
        format!("{}h ago", delta.num_hours())
    } else if delta.num_days() < 30 {
        format!("{}d ago", delta.num_days())
    } else {
        ts.format("%Y-%m-%d").to_string()
    }
}

// ---------------------------------------------------------------------------
// Changelist
// ---------------------------------------------------------------------------

/// Phase 5/a — describes one column of the changelist table. Replaces
/// the previous `columns: Vec<String>` shape on `ListCtx` so templates
/// can drive both the header label AND the row-cell key from a single
/// loop (`{% for field in fields %}<td>{{ row[field.name] }}</td>{% endfor %}`).
///
/// Stabilization (v1.4.x): `kind` carries `FieldType.widget()` so the
/// list template can dispatch on type ("number" / "datetime" /
/// "checkbox" / "text") instead of duck-typing on the cell's string
/// shape. Removes the hardcoded `field.name in ['pages',…]` numeric
/// column list, the `row[field.name] == "true"` boolean string match,
/// and the `length == 16 and [10] == "T"` ISO-datetime shape test
/// from `admin/list.html`.
#[derive(Serialize)]
pub(crate) struct ListField {
    pub name: String,
    pub label: String,
    pub kind: &'static str,
}

#[derive(Serialize)]
pub(crate) struct ListCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub entries: Vec<SidebarEntry>,
    pub admin_name: &'static str,
    pub display_name: &'static str,
    pub singular_name: &'static str,
    pub fields: Vec<ListField>,
    pub rows: Vec<ListRowCtx>,
    pub search_query: String,
    pub filters: Vec<FilterGroupCtx>,
    pub page: usize,
    pub total_pages: usize,
    pub per_page: usize,
    pub total_rows: usize,
    /// Whether the bulk-action UI should render. Always `false` in
    /// Phase 6a — the `/admin/<model>/_action` POST endpoint isn't
    /// wired until a later phase. Templates hide the action bar
    /// when this is `false` so we don't ship UI that 404s on submit.
    pub bulk_actions_enabled: bool,
    pub flash: Option<FlashCtx>,
}

/// Phase 5/a — `values` is flattened into the JSON object so template
/// code can do `row[field.name]` (minijinja resolves dict subscript on
/// the merged map). The explicit `id: i64` struct field stays out of
/// the flattened map (the loader skips inserting an "id" key) so
/// `row.id` continues to render as the integer id without colliding
/// with any model field literally named "id".
///
/// Stability lock (v1.4.x) — value type is `serde_json::Value` instead
/// of `String`. Boolean cells get parsed to JSON `true` / `false` in
/// `list_ctx`, so the template does `{% if row[field.name] %}` (real
/// truthiness) instead of `{% if row[field.name] == "true" %}` (string
/// match). Other types (text / number / datetime) stay as JSON strings
/// because the macro emits them in their final display form already.
#[derive(Serialize)]
pub(crate) struct ListRowCtx {
    pub id: i64,
    #[serde(flatten)]
    pub values: HashMap<String, serde_json::Value>,
}

#[derive(Serialize)]
pub(crate) struct FilterGroupCtx {
    pub field: String,
    pub label: String,
    pub options: Vec<FilterOptionCtx>,
    pub current: Option<String>,
}

#[derive(Serialize)]
pub(crate) struct FilterOptionCtx {
    pub value: String,
    pub label: String,
    pub selected: bool,
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn list_ctx(
    identity: &Identity,
    admin: &Admin,
    entry: &AdminEntry,
    rows: Vec<ListRow>,
    search_query: String,
    filters: Vec<FilterGroupCtx>,
    page: usize,
    per_page: usize,
    total_rows: usize,
    csrf_token: String,
) -> ListCtx {
    let total_pages = total_rows.div_ceil(per_page.max(1)).max(1);
    let fields: Vec<ListField> = entry
        .fields
        .iter()
        .map(|f| ListField {
            name: f.name.to_string(),
            label: f.label.to_string(),
            // Single source of truth — `FieldType::widget()` already
            // maps every variant to one of "text" / "number" /
            // "checkbox" / "datetime". Carrying it on every column
            // means the list template never inspects the cell's
            // string value to figure out what kind of data it holds.
            kind: f.field_type.widget(),
        })
        .collect();
    // Field-name positions used to convert each row's positional cells
    // (Vec<String>) into a name-keyed values map. Stays in lockstep with
    // `entry.fields` because `AdminModel::display_values` is generated
    // in the same field order as `FIELDS`.
    let field_names: Vec<&'static str> = entry.fields.iter().map(|f| f.name).collect();
    // Stability lock (v1.4.x) — pre-compute the field type per index so
    // the row loop can decide how to type each cell value. Boolean
    // fields decode to JSON `true` / `false` so templates use
    // truthiness; everything else stays as a JSON string.
    let field_types: Vec<crate::admin::FieldType> =
        entry.fields.iter().map(|f| f.field_type).collect();
    ListCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: entry.display_name.to_string(),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        admin_name: entry.admin_name,
        display_name: entry.display_name,
        singular_name: entry.singular_name,
        fields,
        rows: rows
            .into_iter()
            .map(|r| {
                let mut values: HashMap<String, serde_json::Value> =
                    HashMap::with_capacity(field_names.len().saturating_sub(1));
                for (i, cell) in r.cells.into_iter().enumerate() {
                    if let Some(name) = field_names.get(i) {
                        // Skip the "id" key so the explicit `id: i64`
                        // struct field wins on serialization (otherwise
                        // a flatten-map "id" string would shadow it).
                        if *name == "id" {
                            continue;
                        }
                        let typed = match field_types.get(i) {
                            Some(crate::admin::FieldType::Bool) => {
                                serde_json::Value::Bool(cell == "true")
                            }
                            _ => serde_json::Value::String(cell),
                        };
                        values.insert((*name).to_string(), typed);
                    }
                }
                ListRowCtx { id: r.id, values }
            })
            .collect(),
        search_query,
        filters,
        page,
        total_pages,
        per_page,
        total_rows,
        bulk_actions_enabled: false,
        flash: None,
    }
}

// ---------------------------------------------------------------------------
// Change form
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct FormCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub entries: Vec<SidebarEntry>,
    pub admin_name: &'static str,
    pub display_name: &'static str,
    pub singular_name: &'static str,
    pub mode: &'static str, // "new" or "edit"
    pub object_id: Option<i64>,
    /// Phase 6 — fields grouped into logical sections. The form
    /// template iterates `sections` and within each its `fields`.
    /// Phase 1/b's flat `fields: Vec<FormField>` is gone; group_into
    /// the heuristic in `form_ctx` always emits at least one section
    /// when the model has any editable fields.
    pub sections: Vec<FormSection>,
    pub errors: Vec<String>,
    pub flash: Option<FlashCtx>,
}

/// Phase 5/d — one option in a `<select>` list. Both fields are
/// `String` because options come from runtime data: enum choices
/// (static strings copied), foreign-key rows (id → display label),
/// many-to-many memberships. The label and value can diverge — for
/// FK selects, `value` is the row id, `label` is the human-readable
/// display string.
#[derive(Serialize, Clone)]
pub(crate) struct SelectOption {
    pub value: String,
    pub label: String,
}

#[derive(Serialize)]
pub(crate) struct FormField {
    pub name: &'static str,
    /// Phase 1/b — humanised label sourced from
    /// `intelligence::field_ui_metadata` ("created_at" → "Created At")
    /// instead of the raw column name. `String` because the intelligence
    /// layer owns the buffer.
    pub label: String,
    pub widget: &'static str,
    pub input_type: &'static str,
    pub value: String,
    pub hint: Option<String>,
    pub placeholder: Option<String>,
    /// Phase 1/b — `true` for fields the form template should mark
    /// with the required-asterisk. Optional types and booleans never
    /// carry the marker (booleans always submit a value, optionals
    /// are explicitly nullable).
    pub required: bool,
    /// Phase 5/d — populated when `widget == "select"`. `None` for
    /// non-select widgets so serialisation doesn't carry an empty
    /// list per field.
    pub options: Option<Vec<SelectOption>>,
    /// Phase 5/d — `true` for many-to-many relations so the template
    /// emits `<select multiple>`. `false` for single-select / non-select
    /// widgets.
    pub multiple: bool,
    /// Phase 6 — grid-span hint. `1` (default) renders the field at
    /// half-width inside the section's `grid-cols-2`; `2` makes the
    /// field span both columns. Currently set to `2` for textareas,
    /// `1` everywhere else; the form template branches on this with
    /// `{% if field.span == 2 %}col-span-2{% endif %}`.
    pub span: u8,
    /// Phase 6.2 — HTML5 `autocomplete` token. `Some("current-password")`
    /// / `Some("new-password")` / `Some("username")` / `Some("email")` /
    /// `Some("off")`. `None` skips the attribute. Surfaced for password
    /// manager hints on bespoke forms (login / password-change /
    /// user-new); generic AdminEntry-driven forms default to `None`.
    pub autocomplete: Option<&'static str>,
    /// Phase 6.2 — `true` emits the HTML5 `autofocus` attribute. Set on
    /// the first user-editable field of a bespoke form so the cursor
    /// lands there; defaults to `false` for AdminEntry-driven forms.
    pub autofocus: bool,
    /// Phase 6.2 — `true` emits HTML5 `disabled`. Used for read-only
    /// displays inside edit forms (user_edit's email field).
    pub disabled: bool,
    /// Phase 6.2 — HTML5 `maxlength` attribute. `Some(150)` for group
    /// names; `None` skips. Surfaced for length-limited free-text fields
    /// on bespoke forms.
    pub maxlength: Option<u16>,
    /// Phase 7.2 — `true` for select fields backed by a relation
    /// (FK / M2M) so the form template wraps the `<select>` with a
    /// client-side filter input. `false` for everything else,
    /// including enum-style closed-list selects (which are typically
    /// short enough to need no filter).
    pub searchable: bool,
    /// Phase 7.2 — `true` when the relation has more rows than the
    /// resolver's truncation limit (currently 50). Drives a hint
    /// message under the search input ("Showing first 50 results.
    /// Keep typing to filter.").
    pub has_more: bool,
    /// Phase 7.3 — when present, JS upgrades the client-side filter
    /// to a remote-search call against this URL. `Some("/admin/search/User")`
    /// for FK / M2M fields whose target resolves; `None` for enums,
    /// non-relation fields, and bespoke-handler-built fields. The
    /// plain `<select>` keeps working with the truncated 50-row
    /// initial set when JS is disabled or the URL is `None`.
    pub search_url: Option<String>,
    /// Phase 7.5 — per-field validation errors. Default empty. The
    /// generic admin path (`do_create` / `do_update`) leaves this
    /// untouched because `AdminOps::create / update` returns flat
    /// `Vec<String>`; those errors stay in `FormCtx.errors`. Bespoke
    /// handlers (user_new / user_edit / group_new / password_change)
    /// build a parallel `HashMap<String, Vec<String>>` while pushing
    /// global errors and pass it through `apply_field_errors`.
    pub errors: Vec<String>,
    /// Phase 10 — display name of the target model for relation
    /// fields. `Some("User")` when this field carries an
    /// `AdminRelation`; `None` otherwise. The form template uses it
    /// for the "Select <Model>…" placeholder and the
    /// "No <Model> available" empty-options message. Mirrors
    /// `search_url`'s relation-derived nature.
    pub target_model: Option<String>,
    /// Stability lock (v1.4.x) — checked-state for boolean fields,
    /// computed once at FormField construction time using the same
    /// normalization as `FormData::bool_flag` (`on` / `true` / `1` /
    /// `yes` → `true`, anything else → `false`).
    ///
    /// Removes a latent bug: `_form_field.html` previously read
    /// `field.value == "true"` to decide whether to emit `checked`.
    /// That worked for values loaded from the DB (display_values
    /// emits `"true"` / `"false"`), but failed when the SAME form
    /// re-rendered after a validation error: HTML form submits send
    /// `is_active=on`, not `is_active=true`. The string-match path
    /// then rendered the checkbox as unchecked even though the user
    /// had just checked it. Computing `checked` here normalizes the
    /// representation once, and templates do `{% if field.checked %}`.
    pub checked: bool,
}

/// Phase 6 — one logical group of fields on a form. `title: None`
/// renders without an `<h3>` (used for the default "core fields"
/// section). Sections preserve insertion order, and fields within a
/// section preserve the macro's `FIELDS` order.
#[derive(Serialize)]
pub(crate) struct FormSection {
    pub title: Option<&'static str>,
    pub fields: Vec<FormField>,
}

/// Snake-case → Title Case ("priority" → "Priority", "is_active" → "Is active").
///
/// Mirrors `rustio_macros::humanise_field` byte-for-byte. The macro emits
/// validation messages prefixed with this transformed label
/// (`"Title is required."`); `bucket_errors_by_label` reverses the mapping
/// at runtime to route flat errors to their owning field. The two copies
/// must stay in sync — if you edit one, edit both.
fn humanise_field(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut next_upper = true;
    for ch in s.chars() {
        if ch == '_' {
            out.push(' ');
            next_upper = true;
        } else if next_upper {
            out.push(ch.to_ascii_uppercase());
            next_upper = false;
        } else {
            out.push(ch);
        }
    }
    out
}

/// Split a flat `Vec<String>` from `AdminOps::create / update` into a
/// global vec + a per-field map by prefix-matching against each editable
/// field's humanised label (see `humanise_field`).
///
/// **Brittle by design.** This depends on `rustio-macros` emitting messages
/// of the form `"<HumanisedLabel> ..."` (currently `is required.`,
/// `must be a number.`, `is not a valid date.`). If the macro ever changes
/// that wording, unmatched errors fall through to the global vec — the
/// banner still shows them; only the inline / aria attribution is lost.
/// No crash, no wrong field. Don't tighten this into a hard contract.
pub(crate) fn bucket_errors_by_label(
    entry: &AdminEntry,
    errors: Vec<String>,
) -> (Vec<String>, HashMap<String, Vec<String>>) {
    // Pre-compute "<Label> " once per editable field. The trailing space
    // disambiguates `Title ` from `Title bar ` — `"Title bar is required."`
    // must not match a field named `title`.
    let labels: Vec<(&'static str, String)> = entry
        .fields
        .iter()
        .filter(|f| f.editable)
        .map(|f| (f.name, format!("{} ", humanise_field(f.name))))
        .collect();

    let mut global: Vec<String> = Vec::new();
    let mut per_field: HashMap<String, Vec<String>> = HashMap::new();
    'outer: for err in errors {
        for (name, prefix) in &labels {
            if err.starts_with(prefix.as_str()) {
                per_field.entry((*name).to_string()).or_default().push(err);
                continue 'outer;
            }
        }
        global.push(err);
    }
    (global, per_field)
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn form_ctx(
    identity: &Identity,
    admin: &Admin,
    entry: &AdminEntry,
    mode: &'static str,
    object_id: Option<i64>,
    existing: Option<&EditRow>,
    errors: Vec<String>,
    csrf_token: String,
    // Phase 7 — pre-fetched FK / M2M options keyed by field name. The
    // caller (an async show_* handler) builds this via
    // `resolve_relation_options` before invoking this sync builder.
    // A missing entry or empty Vec produces an empty `<select>` — the
    // pre-Phase-7 mock pair is gone.
    relation_options: HashMap<&'static str, (Vec<SelectOption>, bool)>,
    // Phase 7.5 — per-field validation errors keyed by field name.
    // Populated by bespoke validators that already know which field a
    // given error belongs to. The generic AdminEntry path
    // (`do_create` / `do_update`) builds this map by parsing the flat
    // `Vec<String>` from `AdminOps::create / update` against each
    // field's humanised label (see `bucket_errors_by_label`).
    field_errors: HashMap<String, Vec<String>>,
    // When re-rendering a form after a failed submit, the user's
    // posted values must repopulate the inputs. `Some(form)` makes the
    // submitted value the source of truth for every field (no fallback
    // to `existing`); `None` keeps the original behaviour (read from
    // `existing`). HTML omits unchecked checkboxes, so the no-fallback
    // semantics are required for booleans to render unchecked when the
    // user unchecked them.
    submitted: Option<&FormData>,
) -> FormCtx {
    let fields = entry
        .fields
        .iter()
        .filter(|f| f.editable)
        .map(|f| {
            let value = if let Some(form) = submitted {
                form.get(f.name).map(str::to_string).unwrap_or_default()
            } else {
                existing
                    .and_then(|row| {
                        row.values
                            .iter()
                            .find(|(col, _)| col == f.name)
                            .map(|(_, v)| v.clone())
                    })
                    .unwrap_or_default()
            };
            // Phase 6a: pass None to the classifier (ContextConfig
            // integration deferred to Phase 7).
            let ui = super::intelligence::field_ui_metadata(f, None);
            // Phase 5/c+d — base widget + input_type from the centralized
            // mapping. Sees choices + relation, so enum / FK / M2M fields
            // resolve to ("select", "select" | "select-multiple") here.
            let (base_widget, input_type) = map_field_to_ui(f);
            // Phase 7a/2/critical-fix — String fields with content-y
            // names (body / description / notes / content / summary)
            // render as <textarea> instead of the base single-line
            // <input>. The mapping fn intentionally doesn't see the
            // field name, so this name-hint override stays in the
            // caller. Only fires when the base mapping landed on
            // "input" — a select-shaped field (enum/FK/M2M) doesn't
            // get rewritten to textarea even if its name happens to
            // be "body".
            let widget = if base_widget == "input"
                && matches!(
                    f.field_type,
                    super::types::FieldType::String | super::types::FieldType::OptionalString
                )
                && is_long_text_name(f.name)
            {
                "textarea"
            } else {
                base_widget
            };
            // Phase 1/b — bools always submit (checked = true, absent
            // = false), so they never carry a required-asterisk; every
            // other non-nullable field does.
            let required =
                !f.field_type.nullable() && !matches!(f.field_type, super::types::FieldType::Bool);
            // Phase 5/d — select options + multiple flag.
            //   - Enum (choices): one option per allowed value (raw
            //     string used as both value and label per "no
            //     invented content" rule).
            //   - FK / M2M (relation): mocked option list for now.
            //     A real DB-backed lookup is the next sub-phase per
            //     spec ("Mock for now (no DB query yet)").
            //   - Everything else: None / false.
            // Phase 7.2 — per-field tuple now carries four signals so
            // FormField can drive the searchable filter UI. Order:
            //   options, multiple, searchable, has_more.
            //   - choices (enum): closed list, never searchable.
            //   - relation (FK / M2M): always searchable; has_more
            //     comes from the resolver's truncation flag.
            //   - other: no select, all defaults false.
            let (mut options, multiple, mut searchable, mut has_more) =
                if let Some(values) = f.choices {
                    let mut opts: Vec<SelectOption> = Vec::with_capacity(values.len() + 1);
                    // Phase 7 / F4 — nullable enum fields prepend a leading
                    // empty option so the user can clear the selection back
                    // to NULL.
                    if f.field_type.nullable() {
                        opts.push(SelectOption {
                            value: String::new(),
                            label: "".to_string(),
                        });
                    }
                    opts.extend(values.iter().map(|v| SelectOption {
                        value: (*v).to_string(),
                        label: (*v).to_string(),
                    }));
                    (Some(opts), false, false, false)
                } else if let Some(rel) = &f.relation {
                    // Phase 7.2 — `(options, has_more)` from the resolver;
                    // missing entry or empty Vec → empty select. searchable
                    // is always true for relation-backed selects.
                    let (opts, has_more) =
                        relation_options.get(f.name).cloned().unwrap_or_default();
                    (Some(opts), rel.multi, true, has_more)
                } else {
                    (None, false, false, false)
                };

            // Phase 10 — synthesise a status select when no enum is
            // declared. UI-only — the underlying field stays a String
            // (no schema change). Triggers when:
            //   - field.name == "status"
            //   - no `choices` (closed enum list)
            //   - no `relation` (would already be a select)
            // The select is small + closed → not searchable, no
            // truncation flag.
            let mut widget = widget;
            if f.name == "status" && options.is_none() {
                options = Some(vec![
                    SelectOption {
                        value: "draft".to_string(),
                        label: "draft".to_string(),
                    },
                    SelectOption {
                        value: "published".to_string(),
                        label: "published".to_string(),
                    },
                ]);
                searchable = false;
                has_more = false;
                widget = "select";
            }
            // Phase 6 — span hint. Long-text textareas span the full
            // grid (col-span-2); everything else takes one half.
            let span: u8 = if widget == "textarea" { 2 } else { 1 };
            // Phase 7.3 — remote-search URL only for relation-backed
            // fields. Enum / closed-list selects keep `None` (their
            // option set is in-page; nothing to fetch).
            let search_url = f
                .relation
                .as_ref()
                .map(|rel| format!("/admin/search/{}", rel.target_model));
            // Phase 10 — relation fields gain a "Select <Model>…"
            // placeholder so the empty-select state reads as a
            // prompt, not a blank line. The template also uses the
            // target_model below for the empty-options message
            // ("No <Model> available"). For non-relation fields the
            // placeholder + target_model come from `intelligence`.
            let target_model = f.relation.as_ref().map(|rel| rel.target_model.to_string());
            // Stability lock (v1.4.x) — boolean fields' checked-state is
            // computed once here using the same normalization
            // `FormData::bool_flag` applies on submit (`on` / `true` /
            // `1` / `yes`). Templates render `{% if field.checked %}`
            // instead of comparing strings.
            let checked = matches!(value.as_str(), "on" | "true" | "1" | "yes");
            let placeholder = if let Some(rel) = &f.relation {
                Some(format!("Select {}", rel.target_model))
            } else {
                ui.placeholder
            };
            FormField {
                name: f.name,
                label: ui.label,
                widget,
                input_type,
                value,
                hint: ui.hint,
                placeholder,
                required,
                options,
                multiple,
                span,
                // Phase 6.2 — UX attributes are surfaced only by
                // bespoke handlers that hand-build FormField. The
                // AdminEntry-driven path defaults them off; the
                // template's `{% if field.autofocus %}` etc. checks
                // produce no markup.
                autocomplete: None,
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable,
                has_more,
                search_url,
                // Phase 7.5 — per-field errors from the caller's map.
                // Generic do_create / do_update pass an empty map, so
                // every field on those paths starts with an empty Vec.
                errors: field_errors.get(f.name).cloned().unwrap_or_default(),
                target_model,
                checked,
            }
        })
        .collect::<Vec<FormField>>();

    // Phase 6 — group fields into Default / Metadata / Advanced
    // sections via a deterministic name heuristic. Order within each
    // section is preserved from the macro's FIELDS order.
    let sections = group_fields_into_sections(fields);

    FormCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: match mode {
            "new" => format!("Add {}", entry.singular_name),
            _ => format!("Change {}", entry.singular_name),
        },
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        admin_name: entry.admin_name,
        display_name: entry.display_name,
        singular_name: entry.singular_name,
        mode,
        object_id,
        sections,
        errors,
        flash: None,
    }
}

/// Phase 7.5 — apply a per-field error map to an existing
/// `Vec<FormSection>` in place. Used by bespoke validators
/// (do_new_user, do_new_group, render_user_edit_with_errors,
/// do_password_change) that already know which field a given error
/// belongs to: the validator builds a `HashMap<String, Vec<String>>`
/// while pushing global errors, calls a section helper to produce
/// the flat sections, then walks them with this fn to attach the
/// keyed errors. Keeps the section-builder signatures unchanged.
pub(crate) fn apply_field_errors(
    sections: &mut [FormSection],
    field_errors: &HashMap<String, Vec<String>>,
) {
    for section in sections.iter_mut() {
        for field in section.fields.iter_mut() {
            if let Some(errs) = field_errors.get(field.name) {
                field.errors = errs.clone();
            }
        }
    }
}

/// Phase 6 — partition the form's flat field list into three logical
/// sections by name heuristic. Default (untitled) collects business
/// fields; Metadata collects audit-trail timestamps; Advanced collects
/// system identifiers. Empty sections are dropped, so a form with no
/// audit / id fields still renders as a single section.
fn group_fields_into_sections(fields: Vec<FormField>) -> Vec<FormSection> {
    let mut default_fields = Vec::new();
    let mut metadata_fields = Vec::new();
    let mut advanced_fields = Vec::new();

    for field in fields {
        match classify_field_section(field.name) {
            FieldSection::Default => default_fields.push(field),
            FieldSection::Metadata => metadata_fields.push(field),
            FieldSection::Advanced => advanced_fields.push(field),
        }
    }

    // Phase 10 / 10.1 — section rename: Metadata → "System".
    // Default section keeps no header (Phase 10's "General" rename
    // was reverted in 10.1: visual noise on every form). Advanced
    // stays. Empty sections are still dropped.
    let mut sections: Vec<FormSection> = Vec::with_capacity(3);
    if !default_fields.is_empty() {
        sections.push(FormSection {
            title: None,
            fields: default_fields,
        });
    }
    if !metadata_fields.is_empty() {
        sections.push(FormSection {
            title: Some("System"),
            fields: metadata_fields,
        });
    }
    if !advanced_fields.is_empty() {
        sections.push(FormSection {
            title: Some("Advanced"),
            fields: advanced_fields,
        });
    }
    sections
}

/// Phase 6 — section bucket for a single field name. Substring match
/// for audit-trail words (so `created_at`, `updated_at`,
/// `creation_timestamp` all land in Metadata); exact match for system
/// identifiers (so `user_id`, `application_id` etc. stay in Default —
/// they're business-meaningful FKs, not "advanced" internals).
enum FieldSection {
    Default,
    Metadata,
    Advanced,
}

fn classify_field_section(name: &str) -> FieldSection {
    if name.contains("created") || name.contains("updated") || name.contains("timestamp") {
        FieldSection::Metadata
    } else if matches!(name, "id" | "uuid" | "slug") {
        FieldSection::Advanced
    } else {
        FieldSection::Default
    }
}

/// Phase 7a/2/critical-fix — names that imply multi-line content.
/// Used by `form_ctx` to upgrade a `String` / `OptionalString` field
/// to a `<textarea>` instead of a single-line `<input>`. Conservative
/// list; expand only when a real model needs it.
fn is_long_text_name(name: &str) -> bool {
    matches!(
        name,
        "body" | "description" | "notes" | "content" | "summary" | "bio" | "details"
    )
}

/// Phase 5/c+d — backend-driven field-to-UI mapping.
///
/// Returns the (`widget`, `input_type`) pair the form template should
/// render for a given `AdminField`. The signature takes `&AdminField`
/// (Phase 5/d change from the original `&FieldType`) so the function
/// can see relation + choices metadata without the caller needing
/// per-site logic. Resolution priority (top-down):
///
///   1. `field.choices.is_some()` → enum-style `<select>`.
///   2. `field.relation.is_some()` && `relation.multi` → `<select multiple>`.
///   3. `field.relation.is_some()` (belongs-to) → single `<select>`.
///   4. Fall through to `field.field_type` mapping (the Phase 5/c rules).
///
/// Adding a new `FieldType` variant remains a one-arm change in the
/// final `match`. The first three arms are additive: any field with
/// choices or a relation overrides the FieldType-based mapping.
///
/// Returns `&'static str` (not `String`) because `FormField.widget` /
/// `.input_type` are already `&'static str`; allocating per call would
/// force a downstream type change with no behavioural benefit.
///
/// The `String → ("input", "text")` rule remains the base for plain
/// strings. Long-text override (`textarea` for `body`/`description`/
/// etc.) lives in `form_ctx` because it depends on the field NAME, not
/// just type.
/// Phase 7.2 — initial-render row cap for FK / M2M selects. A 1000-row
/// relation isn't usable as a flat `<select>`; the resolver truncates
/// to this many entries and the FormField's `has_more` flag drives a
/// "keep typing to filter" hint in the template. Searchable filtering
/// runs against the truncated set client-side; future phases can wire
/// up an XHR endpoint for typeahead beyond the cap.
pub(crate) const FK_OPTIONS_LIMIT: usize = 50;

/// Phase 7 — fetch real `<select>` options for every FK / M2M field on
/// an `AdminEntry`, keyed by the field's name. Async because
/// `AdminOps::list` is the canonical row-fetch API and is itself
/// async; the caller (a show_* handler) is already async and awaits
/// this once per page render before invoking the sync `form_ctx`.
///
/// Phase 7.2 — return value is `(Vec<SelectOption>, bool)` per key. The
/// bool is `has_more`: `true` when the relation had more rows than
/// `FK_OPTIONS_LIMIT` and the option list was truncated. Empty target
/// lists, missing target models, and non-relation fields all produce
/// a benign empty entry (`(vec![], false)`) — never a panic.
///
/// The label for each option follows the resolution ladder:
///   1. `relation.display_field` if present and the column exists on
///      the target.
///   2. `"name"` column if present.
///   3. `"title"` column if present.
///   4. Stringified id (`row.id.to_string()`).
pub(crate) async fn resolve_relation_options(
    admin: &Admin,
    entry: &AdminEntry,
    db: &Db,
) -> Result<HashMap<&'static str, (Vec<SelectOption>, bool)>> {
    let mut out: HashMap<&'static str, (Vec<SelectOption>, bool)> = HashMap::new();
    for f in entry.fields.iter() {
        let Some(rel) = &f.relation else {
            continue;
        };
        // The macro emits `target_model` from the
        // `#[rustio(belongs_to = "User")]` attribute — that's the
        // singular struct name. Match against any of the AdminEntry
        // identifiers so handlers don't have to think about which.
        let target = admin.entries().iter().find(|e| {
            e.singular_name == rel.target_model
                || e.admin_name == rel.target_model
                || e.display_name == rel.target_model
        });
        let Some(target) = target else {
            // Unknown target — emit an empty list so the form still
            // renders with a `<select>` and an explicit empty state.
            out.insert(f.name, (Vec::new(), false));
            continue;
        };
        let rows = target.ops.list(db).await?;
        let total = rows.len();
        let display_idx = pick_display_index(target.fields, rel.display_field);
        let mut opts: Vec<SelectOption> = rows
            .into_iter()
            .map(|r| {
                let label = display_idx
                    .and_then(|i| r.cells.get(i).cloned())
                    .filter(|s| !s.is_empty())
                    .unwrap_or_else(|| r.id.to_string());
                SelectOption {
                    value: r.id.to_string(),
                    label,
                }
            })
            .collect();
        let has_more = total > FK_OPTIONS_LIMIT;
        opts.truncate(FK_OPTIONS_LIMIT);
        out.insert(f.name, (opts, has_more));
    }
    Ok(out)
}

/// Phase 7.3 — case-insensitive substring filter for SelectOption
/// labels. Hoisted out of the search handler so the filter logic is
/// unit-testable without DB / route plumbing.
pub(crate) fn filter_options(
    opts: Vec<SelectOption>,
    query: &str,
    limit: usize,
) -> Vec<SelectOption> {
    let needle = query.to_lowercase();
    opts.into_iter()
        .filter(|o| o.label.to_lowercase().contains(&needle))
        .take(limit)
        .collect()
}

/// Phase 7.3 — remote-search row cap. Capped lower than the initial
/// page render (Phase 7.2's `FK_OPTIONS_LIMIT = 50`) because each
/// search hit is a network round-trip that the user actively
/// initiated; 20 is the conventional typeahead size.
pub(crate) const SEARCH_RESULT_LIMIT: usize = 20;

/// Phase 7.3 — backend for the `/admin/search/:model` endpoint.
/// Resolves the target AdminEntry by model name (singular / slug /
/// display), fetches its rows via `AdminOps::list`, builds
/// SelectOption labels via the same display-field ladder as
/// `resolve_relation_options` (with `display_field=None` because the
/// search URL doesn't currently encode it), and filters by the
/// query. Returns an empty Vec if the model is unknown or no rows
/// match — never an error, never a panic.
pub(crate) async fn search_options(
    admin: &Admin,
    db: &Db,
    model: &str,
    query: &str,
) -> Result<Vec<SelectOption>> {
    let target = admin
        .entries()
        .iter()
        .find(|e| e.singular_name == model || e.admin_name == model || e.display_name == model);
    let Some(target) = target else {
        return Ok(Vec::new());
    };
    // Phase 7.6 — a transient DB blip during FK lookup must NOT 500
    // the search endpoint. Swallow the error, log it, and return an
    // empty result; the client falls back to the in-page truncated
    // option set, which is still submittable.
    let rows = match target.ops.list(db).await {
        Ok(r) => r,
        Err(e) => {
            log::warn!(
                "search_options: list({model}) failed, returning empty result: {e}"
            );
            return Ok(Vec::new());
        }
    };
    let display_idx = pick_display_index(target.fields, None);
    let opts: Vec<SelectOption> = rows
        .into_iter()
        .map(|r| {
            let label = display_idx
                .and_then(|i| r.cells.get(i).cloned())
                .filter(|s| !s.is_empty())
                .unwrap_or_else(|| r.id.to_string());
            SelectOption {
                value: r.id.to_string(),
                label,
            }
        })
        .collect();
    Ok(filter_options(opts, query, SEARCH_RESULT_LIMIT))
}

/// Phase 7.6 — cap a search query at `MAX_SEARCH_QUERY_CHARS` so a
/// pathologically long `?q=` doesn't peg a worker. Slicing happens
/// on char boundaries (not bytes) so multi-byte codepoints don't
/// panic.
pub(crate) const MAX_SEARCH_QUERY_CHARS: usize = 200;

pub(crate) fn truncate_query(raw: &str) -> String {
    raw.chars().take(MAX_SEARCH_QUERY_CHARS).collect()
}

/// Phase 7 — pick the index in `fields` whose name matches the
/// preferred display column, with a `name` → `title` fallback. Returns
/// `None` if neither matches; callers fall back to the row id.
fn pick_display_index(fields: &[AdminField], display_field: Option<&str>) -> Option<usize> {
    if let Some(preferred) = display_field {
        if let Some(i) = fields.iter().position(|f| f.name == preferred) {
            return Some(i);
        }
    }
    for fallback in ["name", "title"] {
        if let Some(i) = fields.iter().position(|f| f.name == fallback) {
            return Some(i);
        }
    }
    None
}

fn map_field_to_ui(field: &super::types::AdminField) -> (&'static str, &'static str) {
    // 1. Closed-list enum → `<select>`. Trumps any FieldType mapping.
    if field.choices.is_some() {
        return ("select", "select");
    }
    // 2. & 3. Relation-backed → `<select>`, with `select-multiple` for M2M.
    if let Some(rel) = &field.relation {
        if rel.multi {
            return ("select", "select-multiple");
        }
        return ("select", "select");
    }
    // 4. Fall through to the FieldType-based base mapping.
    use super::types::FieldType::*;
    match field.field_type {
        Bool => ("checkbox", "checkbox"),
        I32 | I64 | OptionalI64 => ("input", "number"),
        DateTime | OptionalDateTime => ("input", "datetime-local"),
        String | OptionalString => ("input", "text"),
    }
}

// ---------------------------------------------------------------------------
// Confirm-delete (template body deferred to Phase 6b; context refactored now)
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct ConfirmDeleteCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub entries: Vec<SidebarEntry>,
    pub admin_name: &'static str,
    pub singular_name: &'static str,
    pub object_id: i64,
    pub object_label: String,
    /// Models that point at this one via a `BelongsTo` FK. Each entry
    /// lists what *could* cascade if the DB has `ON DELETE CASCADE`
    /// on the FK constraint. Phase 6b doesn't query row counts —
    /// listing the affected model names is the operator-facing
    /// "are you sure" signal.
    pub cascading: Vec<CascadeItem>,
    pub flash: Option<FlashCtx>,
}

#[derive(Serialize)]
pub(crate) struct CascadeItem {
    pub source_display_name: String,
    pub source_admin_name: String,
    pub source_field: String,
}

pub(crate) fn confirm_delete_ctx(
    identity: &Identity,
    admin: &Admin,
    entry: &AdminEntry,
    object_id: i64,
    object_label: String,
    cascading: Vec<CascadeItem>,
    csrf_token: String,
) -> ConfirmDeleteCtx {
    ConfirmDeleteCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        page_title: format!("Delete {}", entry.singular_name),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        admin_name: entry.admin_name,
        singular_name: entry.singular_name,
        object_id,
        object_label,
        cascading,
        flash: None,
    }
}

// ---------------------------------------------------------------------------
// History pages (Phase 6b/2 — first real audit consumer).
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct HistoryEntryCtx {
    pub timestamp_iso: String,
    pub when_relative: String,
    pub user_email: String,
    pub action_type: String,
    pub label: &'static str,
    pub pill_class: &'static str,
    pub model_name: String,
    pub model_admin_name: String,
    pub object_id: i64,
    pub summary: String,
    pub ip_address: String,
}

#[derive(Serialize)]
pub(crate) struct ObjectHistoryCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub admin_name: String,
    pub display_name: String,
    pub singular_name: String,
    pub object_id: i64,
    pub object_label: String,
    pub entries: Vec<HistoryEntryCtx>,
    pub flash: Option<FlashCtx>,
}

#[derive(Serialize)]
pub(crate) struct LogEntriesCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: &'static str,
    pub entries: Vec<HistoryEntryCtx>,
    pub flash: Option<FlashCtx>,
}

pub(crate) fn map_audit_actions(actions: Vec<super::audit::AdminAction>) -> Vec<HistoryEntryCtx> {
    actions
        .into_iter()
        .map(|a| HistoryEntryCtx {
            timestamp_iso: a.timestamp.to_rfc3339(),
            when_relative: relative_time(a.timestamp),
            user_email: a.user_email.unwrap_or_else(|| "".to_string()),
            label: action_label(&a.action_type),
            pill_class: action_pill_class(&a.action_type),
            model_name: a.model_name.clone(),
            // Phase 6b assumption: model_name in the audit row IS the
            // admin_name slug. The `audit::record` callsite that lands
            // when actions are logged (Phase 7+) must pass the admin
            // slug here. The dashboard uses the same convention.
            model_admin_name: a.model_name,
            action_type: a.action_type,
            object_id: a.object_id,
            summary: a.summary,
            ip_address: a.ip_address.unwrap_or_default(),
        })
        .collect()
}

// ---------------------------------------------------------------------------
// "Coming in Phase 8" stub page (Phase 7a/0.5/e — Developer-only).
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct ComingSoonCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    /// Phase 7a/2 — sidebar nav entries (Developer-tier sees this
    /// page; the sidebar should still render with full nav).
    pub entries: Vec<SidebarEntry>,
    pub page_title: String,
    pub feature_name: String,
    pub description: String,
}

// ---------------------------------------------------------------------------
// 403 Forbidden page (Phase 7a/0.5/b).
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct ForbiddenCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    /// Phase 7a/2 — sidebar entries; even on a 403 the user is
    /// authenticated, so the sidebar should render with whichever
    /// surfaces they CAN reach.
    pub entries: Vec<SidebarEntry>,
    pub page_title: &'static str,
    /// The permission codename or URL the user tried to reach. Shown
    /// in the body when present so the operator can audit how the
    /// guard fired without trawling logs.
    pub attempted: Option<String>,
    /// The minimum role required by the page that rejected them.
    /// `None` for permission failures, `Some(label)` for role-tier
    /// failures.
    pub required_role: Option<&'static str>,
}

/// Build the 403 response body. Free function (not on `AdminCtx`)
/// so the unit tests can render the page with just `Templates` +
/// `Admin` — no `Db` required.
/// Phase 11.B — context for the generic `admin/error.html` page.
/// Carries the same `BaseContext` as every admin page so the topbar,
/// sidebar, and footer render consistently. `identity` is `None` on
/// the unauthenticated path (the template guards both the dashboard
/// link and the sidebar with `{% if identity %}`).
#[derive(Serialize)]
pub(crate) struct ErrorCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: String,
    pub status: u16,
    pub heading: String,
    pub message: String,
}

/// Phase 11.B — short heading per HTTP status. Falls back to a neutral
/// "Error" for anything we don't have a copy for. Kept as a single-line
/// fn (not a const map) so the compiler inlines the &'static-str
/// branches.
pub(crate) fn admin_error_heading(status: u16) -> &'static str {
    match status {
        400 => "Bad request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not found",
        405 => "Method not allowed",
        409 => "Conflict",
        500 => "Server error",
        _ => "Error",
    }
}

/// Phase 11.B — render the styled HTML error response for an admin
/// path. The middleware that wires this in (`register_admin_routes`)
/// already filters for `/admin/*` requests, so this fn doesn't
/// double-check the path. `identity` is optional because some errors
/// (e.g. an unrouted path under `/admin/foo`) reach the middleware
/// without a session attached.
pub(crate) fn render_admin_error_response(
    admin: &Admin,
    templates: &crate::templates::Templates,
    identity: Option<&Identity>,
    status: u16,
    message: String,
) -> crate::http::Response {
    let heading = admin_error_heading(status).to_string();
    let view = ErrorCtx {
        base: BaseContext::new(identity, String::new(), admin),
        page_title: format!("{status} {heading}"),
        status,
        heading: heading.clone(),
        message,
    };
    let html_status = hyper::StatusCode::from_u16(status)
        .unwrap_or(hyper::StatusCode::INTERNAL_SERVER_ERROR);
    match templates.render("admin/error.html", &view) {
        Ok(body) => crate::http::Response::html(body).with_status(html_status),
        // Render failure (e.g. project overrode the template with broken
        // syntax) — degrade to plain text so the client still sees the
        // original status and a useful message. Logged so an operator
        // can find the underlying template error.
        Err(e) => {
            log::error!("admin/error.html render failed: {e}");
            crate::http::Response::text(format!("{status} {heading}: {}", view.message))
                .with_status(html_status)
        }
    }
}

pub(crate) fn render_forbidden_body(
    admin: &Admin,
    templates: &crate::templates::Templates,
    identity: &Identity,
    csrf_token: String,
    attempted: Option<String>,
    required_role: Option<&'static str>,
) -> crate::error::Result<String> {
    let view = ForbiddenCtx {
        base: BaseContext::new(Some(identity), csrf_token, admin),
        entries: admin
            .entries()
            .iter()
            .filter(|e| !e.core)
            .map(SidebarEntry::from)
            .collect(),
        page_title: "Permission denied",
        attempted,
        required_role,
    };
    templates.render("admin/forbidden.html", &view)
}

// ---------------------------------------------------------------------------
// Password change (self-service — Phase 6b/5).
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub(crate) struct PasswordChangeCtx {
    #[serde(flatten)]
    pub base: BaseContext,
    pub page_title: &'static str,
    pub errors: Vec<String>,
    pub success: bool,
    /// Phase 6.2 — three password fields rendered through the shared
    /// FormField include. Page chrome (the success branch, the page
    /// header card) stays bespoke.
    pub sections: Vec<FormSection>,
}

/// Phase 6.2 — role options for user_new / user_edit. Labels carry the
/// privilege descriptions shown in the existing dropdowns; values are
/// the role slugs the auth layer expects.
pub(crate) fn role_select_options() -> Vec<SelectOption> {
    vec![
        SelectOption {
            value: "user".to_string(),
            label: "User (no admin access)".to_string(),
        },
        SelectOption {
            value: "staff".to_string(),
            label: "Staff (admin access; per-model group permissions)".to_string(),
        },
        SelectOption {
            value: "supervisor".to_string(),
            label: "Supervisor (view + edit; no destructive ops)".to_string(),
        },
        SelectOption {
            value: "administrator".to_string(),
            label: "Administrator (full coverage; bypasses group checks)".to_string(),
        },
        SelectOption {
            value: "developer".to_string(),
            label: "Developer (schema browser + execution logs + SQL console)".to_string(),
        },
    ]
}

/// Phase 6.2 — FormField list for the user_new form. Two sections:
/// Identity (email + password) and Role (the 5-option select). The
/// caller passes the current values so re-render after validation
/// failure preserves them; new-form callers pass empty/staff defaults.
pub(crate) fn user_new_form_sections(email: &str, role: &str) -> Vec<FormSection> {
    vec![
        FormSection {
            title: Some("Identity"),
            fields: vec![
                FormField {
                    name: "email",
                    label: "Email".to_string(),
                    widget: "input",
                    input_type: "email",
                    value: email.to_string(),
                    hint: Some("Must be unique across all users.".to_string()),
                    placeholder: None,
                    required: true,
                    options: None,
                    multiple: false,
                    span: 2,
                    autocomplete: Some("off"),
                    autofocus: true,
                    disabled: false,
                    maxlength: None,
                    searchable: false,
                    has_more: false,
                    search_url: None,
                    errors: vec![],
                    target_model: None,
                    checked: false,
                },
                FormField {
                    name: "password",
                    label: "Password".to_string(),
                    widget: "input",
                    input_type: "password",
                    value: String::new(),
                    hint: Some(
                        "At least 8 characters. The user can change it later via Change password."
                            .to_string(),
                    ),
                    placeholder: None,
                    required: true,
                    options: None,
                    multiple: false,
                    span: 2,
                    autocomplete: Some("new-password"),
                    autofocus: false,
                    disabled: false,
                    maxlength: None,
                    searchable: false,
                    has_more: false,
                    search_url: None,
                    errors: vec![],
                    target_model: None,
                    checked: false,
                },
            ],
        },
        FormSection {
            title: Some("Role"),
            fields: vec![FormField {
                name: "role",
                label: "Role".to_string(),
                widget: "select",
                input_type: "select",
                value: role.to_string(),
                hint: Some(
                    "Higher roles include all lower-role capabilities. Group memberships are assigned on the next page after save."
                        .to_string(),
                ),
                placeholder: None,
                required: true,
                options: Some(role_select_options()),
                multiple: false,
                span: 2,
                autocomplete: None,
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            }],
        },
    ]
}

/// Phase 6.2 — General section for group_new / group_edit. Two
/// fields: name (text, required, 150-char max) and description
/// (textarea). Caller passes the current values so re-render after
/// validation failure preserves them.
pub(crate) fn group_form_sections(name: &str, description: &str) -> Vec<FormSection> {
    vec![FormSection {
        title: Some("General"),
        fields: vec![
            FormField {
                name: "name",
                label: "Name".to_string(),
                widget: "input",
                input_type: "text",
                value: name.to_string(),
                hint: Some(
                    "A short identifier — letters, digits, dots and dashes only. Example: editors."
                        .to_string(),
                ),
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: Some("off"),
                autofocus: true,
                disabled: false,
                maxlength: Some(150),
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "description",
                label: "Description".to_string(),
                widget: "textarea",
                input_type: "text",
                value: description.to_string(),
                hint: Some("Optional. What this group is for.".to_string()),
                placeholder: None,
                required: false,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: None,
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
        ],
    }]
}

/// Phase 6.2 — Identity section for user_edit. Email is disabled
/// (read-only display); role is the select; is_active is the checkbox.
/// Built per render so values reflect the current row.
pub(crate) fn user_edit_identity_sections(
    email: &str,
    role: &str,
    is_active: bool,
) -> Vec<FormSection> {
    vec![FormSection {
        title: Some("Identity"),
        fields: vec![
            FormField {
                name: "email",
                label: "Email".to_string(),
                widget: "input",
                input_type: "email",
                value: email.to_string(),
                hint: Some(
                    "Email changes aren't exposed here — they require a full user update."
                        .to_string(),
                ),
                placeholder: None,
                required: false,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: None,
                autofocus: false,
                disabled: true,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "role",
                label: "Role".to_string(),
                widget: "select",
                input_type: "select",
                value: role.to_string(),
                hint: None,
                placeholder: None,
                required: true,
                options: Some(role_select_options()),
                multiple: false,
                span: 2,
                autocomplete: None,
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "is_active",
                label: "Active".to_string(),
                widget: "checkbox",
                input_type: "checkbox",
                value: if is_active {
                    "true".to_string()
                } else {
                    "false".to_string()
                },
                hint: Some("Inactive users cannot sign in or hold sessions.".to_string()),
                placeholder: None,
                required: false,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: None,
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                // Bespoke builder — `checked` is the source of truth
                // for whether the rendered <input> emits `checked`.
                // The string `value` field is kept for the form-data
                // submit shape ("true" / "false") that the legacy
                // user-edit handler still parses.
                checked: is_active,
            },
        ],
    }]
}

/// Phase 6.2 — Reset password section for user_edit. Single optional
/// field; leaving it blank keeps the existing password.
pub(crate) fn user_edit_password_sections() -> Vec<FormSection> {
    vec![FormSection {
        title: Some("Reset password (optional)"),
        fields: vec![FormField {
            name: "new_password",
            label: "New password".to_string(),
            widget: "input",
            input_type: "password",
            value: String::new(),
            hint: Some("Leave blank to keep the current password unchanged.".to_string()),
            placeholder: None,
            required: false,
            options: None,
            multiple: false,
            span: 2,
            autocomplete: Some("new-password"),
            autofocus: false,
            disabled: false,
            maxlength: None,
            searchable: false,
            has_more: false,
            search_url: None,
            errors: vec![],
            target_model: None,
            checked: false,
        }],
    }]
}

/// Phase 6.2 — pre-built FormField list for the password-change form.
/// Static; the values are always empty (we never echo passwords back).
pub(crate) fn password_change_form_sections() -> Vec<FormSection> {
    vec![FormSection {
        title: None,
        fields: vec![
            FormField {
                name: "old_password",
                label: "Old password".to_string(),
                widget: "input",
                input_type: "password",
                value: String::new(),
                hint: None,
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: Some("current-password"),
                autofocus: true,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "new_password1",
                label: "New password".to_string(),
                widget: "input",
                input_type: "password",
                value: String::new(),
                hint: Some("Your password must contain at least 8 characters.".to_string()),
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: Some("new-password"),
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
            FormField {
                name: "new_password2",
                label: "Confirm".to_string(),
                widget: "input",
                input_type: "password",
                value: String::new(),
                hint: None,
                placeholder: None,
                required: true,
                options: None,
                multiple: false,
                span: 2,
                autocomplete: Some("new-password"),
                autofocus: false,
                disabled: false,
                maxlength: None,
                searchable: false,
                has_more: false,
                search_url: None,
                errors: vec![],
                target_model: None,
                checked: false,
            },
        ],
    }]
}

// ---------------------------------------------------------------------------
// (Phase 11.B replaces the orphan ErrorCtx scaffold that lived here. The
// live struct + render fn are now defined alongside `render_forbidden_body`
// above and wired in via the admin routes' error middleware.)
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::admin::FieldType;
    use crate::auth::Role;
    use crate::templates::Templates;

    /// Build a minimal AdminField for mapping tests. Phase 5/d shifted
    /// the mapping fn to take `&AdminField` (so it can see relation +
    /// choices); this helper hides the boilerplate.
    fn af(field_type: FieldType) -> crate::admin::AdminField {
        crate::admin::AdminField {
            name: "x",
            label: "x",
            field_type,
            editable: true,
            relation: None,
            choices: None,
        }
    }

    /// Phase 5/c — locks the FieldType→UI mapping. Adding a new
    /// FieldType variant requires updating this test along with the
    /// match in `map_field_to_ui`; that's the single place to encode
    /// "what UI does this field render as".
    #[test]
    fn maps_field_types_to_expected_widgets() {
        assert_eq!(
            map_field_to_ui(&af(FieldType::Bool)),
            ("checkbox", "checkbox")
        );
        assert_eq!(map_field_to_ui(&af(FieldType::String)), ("input", "text"));
        assert_eq!(
            map_field_to_ui(&af(FieldType::OptionalString)),
            ("input", "text")
        );
        assert_eq!(map_field_to_ui(&af(FieldType::I32)), ("input", "number"));
        assert_eq!(map_field_to_ui(&af(FieldType::I64)), ("input", "number"));
        assert_eq!(
            map_field_to_ui(&af(FieldType::OptionalI64)),
            ("input", "number")
        );
        assert_eq!(
            map_field_to_ui(&af(FieldType::DateTime)),
            ("input", "datetime-local")
        );
        assert_eq!(
            map_field_to_ui(&af(FieldType::OptionalDateTime)),
            ("input", "datetime-local")
        );
    }

    /// Phase 5/d — a field with a non-empty `choices` slice resolves
    /// to a `<select>` regardless of its underlying FieldType. Locks
    /// resolution priority #1 in `map_field_to_ui`.
    #[test]
    fn enum_field_renders_select() {
        const VALUES: &[&str] = &["draft", "published", "archived"];
        let mut field = af(FieldType::String);
        field.choices = Some(VALUES);
        assert_eq!(map_field_to_ui(&field), ("select", "select"));

        // FieldType::I64 with choices also resolves to select — the
        // choices arm runs before the FieldType match.
        let mut numeric = af(FieldType::I64);
        numeric.choices = Some(VALUES);
        assert_eq!(map_field_to_ui(&numeric), ("select", "select"));
    }

    /// Phase 7 — FK fields render with the real options the handler
    /// pre-fetched into `relation_options`, NOT the pre-Phase-7 mock
    /// pair. Test passes a hand-built map keyed by field name; asserts
    /// the rendered FormField carries the same options through to the
    /// HTML.
    #[test]
    fn fk_field_renders_real_options() {
        // AdminEntry with one editable FK column (`author_id`) plus a
        // plain text title for contrast. AdminRelation points at the
        // synthetic User entry; the test bypasses the resolver and
        // injects options directly via the relation_options map.
        static FK_FIELDS: &[crate::admin::AdminField] = &[
            crate::admin::AdminField {
                name: "title",
                label: "title",
                field_type: FieldType::String,
                editable: true,
                relation: None,
                choices: None,
            },
            crate::admin::AdminField {
                name: "author_id",
                label: "author_id",
                field_type: FieldType::I64,
                editable: true,
                relation: Some(crate::admin::AdminRelation {
                    target_model: "User",
                    display_field: Some("email"),
                    multi: false,
                }),
                choices: None,
            },
        ];
        let admin = Admin::new();
        let entry = AdminEntry::for_testing("posts", "Posts", "Post", "posts", FK_FIELDS, false);
        let ident = fake_identity(Role::Administrator);

        let mut relation_options: HashMap<&'static str, (Vec<SelectOption>, bool)> = HashMap::new();
        relation_options.insert(
            "author_id",
            (
                vec![
                    SelectOption {
                        value: "1".to_string(),
                        label: "alice@example.com".to_string(),
                    },
                    SelectOption {
                        value: "2".to_string(),
                        label: "bob@example.com".to_string(),
                    },
                    SelectOption {
                        value: "3".to_string(),
                        label: "charlie@example.com".to_string(),
                    },
                ],
                false,
            ),
        );

        let ctx = form_ctx(
            &ident,
            &admin,
            &entry,
            "new",
            None,
            None,
            vec![],
            "csrf".into(),
            relation_options,
            HashMap::new(),
            None,
        );

        // Locate the author_id field in the resolved sections — it
        // should land in the Default bucket (FK column, name doesn't
        // hit Metadata or Advanced heuristics).
        let author_field = ctx
            .sections
            .iter()
            .flat_map(|s| s.fields.iter())
            .find(|f| f.name == "author_id")
            .expect("author_id field present");
        assert_eq!(author_field.widget, "select");
        let opts = author_field
            .options
            .as_ref()
            .expect("author_id field has options");
        assert_eq!(opts.len(), 3, "real options length should reflect input");
        assert_eq!(opts[0].value, "1");
        assert_eq!(opts[0].label, "alice@example.com");
        assert_eq!(opts[2].label, "charlie@example.com");
        // The legacy mock label MUST NOT appear.
        assert!(
            !opts
                .iter()
                .any(|o| o.label == "Item 1" || o.label == "Item 2"),
            "Phase 7 mock pair must be gone; got: {opts:?}",
            opts = opts.iter().map(|o| &o.label).collect::<Vec<_>>()
        );

        // Render the template and confirm the labels surface in the
        // produced HTML — closes the loop end-to-end.
        let templates = Templates::new(None).expect("embedded templates");
        let body = templates
            .render("admin/form.html", &ctx)
            .expect("form renders");
        assert!(
            body.contains("alice@example.com"),
            "alice option missing in HTML"
        );
        assert!(
            body.contains("bob@example.com"),
            "bob option missing in HTML"
        );
        assert!(
            body.contains("charlie@example.com"),
            "charlie option missing in HTML"
        );
        assert!(
            !body.contains("Item 1"),
            "rendered HTML must not contain the Phase 7 mock label"
        );
    }

    /// Phase 7.3 — `filter_options` is the testable core of the
    /// `/admin/search/:model` endpoint. Locks the contract:
    ///   - case-insensitive substring match against `label`
    ///   - results capped at the requested `limit`
    ///   - empty query returns everything (callers gate length;
    ///     the endpoint short-circuits empty in `show_search`)
    #[test]
    fn remote_search_returns_results() {
        let opts = vec![
            SelectOption {
                value: "1".to_string(),
                label: "alice@example.com".to_string(),
            },
            SelectOption {
                value: "2".to_string(),
                label: "bob@example.com".to_string(),
            },
            SelectOption {
                value: "3".to_string(),
                label: "Alice Cooper".to_string(),
            },
            SelectOption {
                value: "4".to_string(),
                label: "carol@acme.io".to_string(),
            },
        ];

        // Case-insensitive: "alice" matches alice@example.com AND
        // "Alice Cooper".
        let r = filter_options(opts.clone(), "alice", 20);
        assert_eq!(r.len(), 2);
        assert_eq!(r[0].value, "1");
        assert_eq!(r[1].value, "3");

        // Mixed case in query: also case-insensitive.
        let r = filter_options(opts.clone(), "BoB", 20);
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].value, "2");

        // Limit honoured.
        let r = filter_options(opts.clone(), "a", 2);
        assert_eq!(r.len(), 2, "limit=2 caps the result vec");

        // No matches → empty.
        let r = filter_options(opts.clone(), "zzznoexist", 20);
        assert!(r.is_empty());

        // The legacy mock label MUST never appear (regression guard).
        let r = filter_options(opts, "Item", 20);
        assert!(r.is_empty(), "no row labelled 'Item' — legacy mock is gone");
    }

    /// Phase 7.3 — FK fields gain a `search_url` pointing at the
    /// `/admin/search/<TargetModel>` endpoint. Locks both the URL
    /// shape and the template's `data-search-url` attribute.
    #[test]
    fn fk_field_carries_search_url() {
        static FK_FIELDS: &[crate::admin::AdminField] = &[crate::admin::AdminField {
            name: "author_id",
            label: "author_id",
            field_type: FieldType::I64,
            editable: true,
            relation: Some(crate::admin::AdminRelation {
                target_model: "User",
                display_field: Some("email"),
                multi: false,
            }),
            choices: None,
        }];
        let admin = Admin::new();
        let entry = AdminEntry::for_testing("posts", "Posts", "Post", "posts", FK_FIELDS, false);
        let ident = fake_identity(Role::Administrator);
        let mut relation_options: HashMap<&'static str, (Vec<SelectOption>, bool)> = HashMap::new();
        relation_options.insert(
            "author_id",
            (
                vec![SelectOption {
                    value: "1".into(),
                    label: "alice@example.com".into(),
                }],
                false,
            ),
        );
        let ctx = form_ctx(
            &ident,
            &admin,
            &entry,
            "new",
            None,
            None,
            vec![],
            "csrf".into(),
            relation_options,
            HashMap::new(),
            None,
        );

        let author = ctx
            .sections
            .iter()
            .flat_map(|s| s.fields.iter())
            .find(|f| f.name == "author_id")
            .expect("author_id field");
        assert_eq!(
            author.search_url.as_deref(),
            Some("/admin/search/User"),
            "FK fields must carry the JSON search endpoint URL"
        );

        // Rendered template surfaces the URL as a data attribute.
        // minijinja autoescapes `/` to `&#x2f;` in attribute values
        // (OWASP-safe — browsers decode it back when reading the DOM,
        // and `input.dataset.searchUrl` returns the unescaped string,
        // which is what the JS fetch handler uses).
        let templates = Templates::new(None).expect("embedded templates");
        let body = templates
            .render("admin/form.html", &ctx)
            .expect("form renders");
        assert!(
            body.contains("data-search-url=\"&#x2f;admin&#x2f;search&#x2f;User\""),
            "search_url must surface as data-search-url on the search input"
        );
    }

    /// Phase 7.2 — searchable FK selects render the search-input
    /// scaffolding (placeholder, `data-target`, `aria-controls`) plus
    /// the underlying `<select>`. The selected option keeps its
    /// `selected` marker so the JS filter (which exempts the selected
    /// option from hiding) never accidentally drops the current
    /// value. Locks both the FormField shape and the template wrap.
    #[test]
    fn searchable_select_filters_options() {
        // FK column with three real options. `field.value = "2"` so
        // the second option is the selected one — must persist.
        static FK_FIELDS: &[crate::admin::AdminField] = &[crate::admin::AdminField {
            name: "author_id",
            label: "author_id",
            field_type: FieldType::I64,
            editable: true,
            relation: Some(crate::admin::AdminRelation {
                target_model: "User",
                display_field: Some("email"),
                multi: false,
            }),
            choices: None,
        }];
        let admin = Admin::new();
        let entry = AdminEntry::for_testing("posts", "Posts", "Post", "posts", FK_FIELDS, false);
        let ident = fake_identity(Role::Administrator);
        let mut relation_options: HashMap<&'static str, (Vec<SelectOption>, bool)> = HashMap::new();
        relation_options.insert(
            "author_id",
            (
                vec![
                    SelectOption {
                        value: "1".to_string(),
                        label: "alice@example.com".to_string(),
                    },
                    SelectOption {
                        value: "2".to_string(),
                        label: "bob@example.com".to_string(),
                    },
                    SelectOption {
                        value: "3".to_string(),
                        label: "charlie@example.com".to_string(),
                    },
                ],
                false, // has_more=false (3 < 50)
            ),
        );

        // Edit-mode render with the existing row carrying author_id="2".
        let existing = EditRow {
            id: 7,
            values: vec![("author_id".to_string(), "2".to_string())],
        };
        let ctx = form_ctx(
            &ident,
            &admin,
            &entry,
            "edit",
            Some(7),
            Some(&existing),
            vec![],
            "csrf".into(),
            relation_options,
            HashMap::new(),
            None,
        );

        let author_field = ctx
            .sections
            .iter()
            .flat_map(|s| s.fields.iter())
            .find(|f| f.name == "author_id")
            .expect("author_id field present");
        assert_eq!(author_field.widget, "select");
        assert!(
            author_field.searchable,
            "FK fields must default to searchable=true"
        );
        assert!(
            !author_field.has_more,
            "3 options is below the 50-row truncation threshold"
        );
        assert_eq!(
            author_field.value, "2",
            "edit mode must surface the existing author_id value"
        );

        let templates = Templates::new(None).expect("embedded templates");
        let body = templates
            .render("admin/form.html", &ctx)
            .expect("form renders");

        // The search input scaffolding is present.
        assert!(
            body.contains("data-search-input"),
            "search input marker missing"
        );
        assert!(
            body.contains("data-target=\"id_author_id\""),
            "search input must wire to the select via data-target"
        );
        assert!(
            body.contains("aria-controls=\"id_author_id\""),
            "search input must announce its target via aria-controls"
        );
        assert!(
            body.contains("placeholder=\"Search…\""),
            "search input must carry the placeholder copy"
        );

        // The selected value persists — bob@example.com (value=2) has
        // the `selected` attribute on its <option>.
        let bob_idx = body
            .find("value=\"2\"")
            .expect("option with value=2 must render");
        let after_bob = &body[bob_idx..bob_idx.saturating_add(120)];
        assert!(
            after_bob.contains("selected"),
            "selected option must carry `selected`; got: {after_bob:?}"
        );

        // No has_more hint when below the threshold.
        assert!(
            !body.contains("Showing first 50 results"),
            "has_more hint must not appear when has_more=false"
        );
    }

    /// Phase 7.2 — when the relation has more rows than the resolver's
    /// truncation cap, FormField.has_more flips to true and the
    /// template renders the "Showing first 50 results" hint paragraph.
    #[test]
    fn searchable_select_renders_has_more_hint() {
        static FK_FIELDS: &[crate::admin::AdminField] = &[crate::admin::AdminField {
            name: "author_id",
            label: "author_id",
            field_type: FieldType::I64,
            editable: true,
            relation: Some(crate::admin::AdminRelation {
                target_model: "User",
                display_field: None,
                multi: false,
            }),
            choices: None,
        }];
        let admin = Admin::new();
        let entry = AdminEntry::for_testing("posts", "Posts", "Post", "posts", FK_FIELDS, false);
        let ident = fake_identity(Role::Administrator);
        let mut relation_options: HashMap<&'static str, (Vec<SelectOption>, bool)> = HashMap::new();
        // Just one option for the test, but flip has_more = true to
        // simulate a relation that exceeded the resolver's cap.
        relation_options.insert(
            "author_id",
            (
                vec![SelectOption {
                    value: "1".into(),
                    label: "first".into(),
                }],
                true,
            ),
        );
        let ctx = form_ctx(
            &ident,
            &admin,
            &entry,
            "new",
            None,
            None,
            vec![],
            "csrf".into(),
            relation_options,
            HashMap::new(),
            None,
        );
        let templates = Templates::new(None).expect("embedded templates");
        let body = templates
            .render("admin/form.html", &ctx)
            .expect("form renders");
        assert!(
            body.contains("Showing first 50 results"),
            "has_more hint copy missing"
        );
    }

    /// Phase 7 — FK field WITHOUT a matching entry in relation_options
    /// renders an empty `<select>` rather than the legacy mock. Locks
    /// the empty-state contract in `form_ctx`.
    #[test]
    fn fk_field_with_no_options_renders_empty_select() {
        static FK_FIELDS: &[crate::admin::AdminField] = &[crate::admin::AdminField {
            name: "author_id",
            label: "author_id",
            field_type: FieldType::I64,
            editable: true,
            relation: Some(crate::admin::AdminRelation {
                target_model: "User",
                display_field: None,
                multi: false,
            }),
            choices: None,
        }];
        let admin = Admin::new();
        let entry = AdminEntry::for_testing("posts", "Posts", "Post", "posts", FK_FIELDS, false);
        let ident = fake_identity(Role::Administrator);
        let ctx = form_ctx(
            &ident,
            &admin,
            &entry,
            "new",
            None,
            None,
            vec![],
            "csrf".into(),
            HashMap::new(),
            HashMap::new(),
            None,
        );
        let author_field = ctx
            .sections
            .iter()
            .flat_map(|s| s.fields.iter())
            .find(|f| f.name == "author_id")
            .expect("author_id field present");
        assert_eq!(author_field.widget, "select");
        let opts = author_field.options.as_ref().expect("options is Some");
        assert!(opts.is_empty(), "no relation_options entry → empty select");
    }

    /// Phase 5/d — a relation with `multi: true` produces
    /// `("select", "select-multiple")`; default `multi: false` stays
    /// single-select. Locks resolution priority #2 vs #3 in
    /// `map_field_to_ui`.
    #[test]
    fn relation_multi_sets_multiple() {
        let mut single = af(FieldType::I64);
        single.relation = Some(crate::admin::AdminRelation {
            target_model: "posts",
            display_field: None,
            multi: false,
        });
        assert_eq!(map_field_to_ui(&single), ("select", "select"));

        let mut many = af(FieldType::I64);
        many.relation = Some(crate::admin::AdminRelation {
            target_model: "tags",
            display_field: None,
            multi: true,
        });
        assert_eq!(map_field_to_ui(&many), ("select", "select-multiple"));
    }

    fn fake_identity(role: Role) -> Identity {
        Identity {
            user_id: 1,
            email: "test@example.com".into(),
            role,
            is_active: true,
            is_demo: false,
            demo_label: None,
        }
    }

    /// Phase 11.B — post-logout confirmation. After `do_logout`
    /// redirects to `/admin/login?logout=1`, `show_login` populates
    /// `LoginCtx.flash` with a success message; base.html's shared
    /// flash block surfaces it above the sign-in card. Asserts both
    /// the template-side rendering and the with-flash-empty path.
    #[test]
    fn login_renders_post_logout_banner_when_flash_present() {
        let admin = Admin::new();
        let templates = Templates::new(None).expect("embedded templates");

        // With flash → banner renders, the message and the success
        // class are both in the body.
        let with_flash = LoginCtx {
            base: BaseContext::new(None, "fake-csrf".into(), &admin),
            error: None,
            sections: login_form_sections(),
            flash: Some(FlashCtx {
                kind: "success",
                message: "You've been signed out.".to_string(),
            }),
        };
        let body = templates
            .render("admin/login.html", &with_flash)
            .expect("login renders with flash");
        // Auto-escape rewrites the apostrophe (`'` → `&#39;`), so assert
        // on the apostrophe-free fragment that survives both encodings.
        assert!(
            body.contains("been signed out."),
            "post-logout message must be in the rendered body — got snippet: {}",
            &body[..body.len().min(400)]
        );
        assert!(
            body.contains("message-success"),
            "flash must use the success kind class"
        );

        // Without flash → no banner, no leftover styling artefacts.
        let bare = LoginCtx {
            base: BaseContext::new(None, "fake-csrf".into(), &admin),
            error: None,
            sections: login_form_sections(),
            flash: None,
        };
        let body = templates
            .render("admin/login.html", &bare)
            .expect("login renders without flash");
        assert!(
            !body.contains("been signed out."),
            "no flash → no leftover post-logout copy"
        );
        assert!(
            !body.contains("message-success"),
            "no flash → no message-success class"
        );
    }

    #[test]
    fn render_forbidden_body_with_required_role() {
        let admin = Admin::new();
        let templates = Templates::new(None).expect("embedded templates");
        let ident = fake_identity(Role::Staff);

        let body = render_forbidden_body(
            &admin,
            &templates,
            &ident,
            "fake-csrf".into(),
            None,
            Some("Administrator"),
        )
        .expect("forbidden page renders");

        assert!(body.contains("Permission denied"), "page h1 missing");
        assert!(
            body.contains("Administrator"),
            "required_role hint should be in body"
        );
        assert!(body.contains("Return to dashboard"), "back link missing");
        // Identity-bearing surfaces still render: the user-tools welcome
        // line should include the test email.
        assert!(
            body.contains("test@example.com"),
            "user-tools email missing"
        );
    }

    /// Phase 11.B — `admin/error.html` renders the status, heading, and
    /// message; the dashboard return-link is conditional on identity
    /// (signed-in users see it, the unauthenticated path doesn't).
    /// Locks the (file, registry, render-test) triple for the new
    /// admin error page.
    #[test]
    fn admin_error_page_renders_with_status_and_heading() {
        let admin = Admin::new();
        let templates = Templates::new(None).expect("embedded templates");

        // Unauthenticated path — no Identity, no dashboard link.
        let resp = render_admin_error_response(
            &admin,
            &templates,
            None,
            404,
            "no admin model: blogs".into(),
        );
        assert_eq!(resp.status, hyper::StatusCode::NOT_FOUND);
        let ct = resp
            .headers
            .iter()
            .find(|(k, _)| k == "content-type")
            .map(|(_, v)| v.as_str())
            .unwrap_or("");
        assert!(
            ct.starts_with("text/html"),
            "content-type must be HTML, got {ct:?}"
        );
        let body = std::str::from_utf8(&resp.body).expect("utf8 body");
        assert!(body.contains("404"), "status code missing in body");
        assert!(body.contains("Not found"), "heading missing in body");
        assert!(
            body.contains("no admin model: blogs"),
            "message missing in body"
        );
        assert!(
            !body.contains("Return to dashboard"),
            "dashboard link must not render without an identity"
        );

        // Authenticated path — identity present, dashboard link shows.
        let ident = fake_identity(Role::Staff);
        let resp = render_admin_error_response(
            &admin,
            &templates,
            Some(&ident),
            500,
            "Internal Server Error".into(),
        );
        let body = std::str::from_utf8(&resp.body).expect("utf8 body");
        assert!(body.contains("500"), "status code missing in body");
        assert!(body.contains("Server error"), "500 heading missing");
        assert!(
            body.contains("Return to dashboard"),
            "dashboard link must render for signed-in users"
        );
    }

    /// Phase 6.2 — `user_edit.html` now renders its Identity and
    /// Reset-password sections through the shared FormField include,
    /// while keeping the group-membership checkbox list as a custom
    /// block (per Phase 6.2 spec correction #1: groups stay as
    /// checkbox-list, NOT multi-select). This locks all three sides:
    ///   - role select renders with its 5 options
    ///   - is_active checkbox renders with the right name + checked state
    ///   - group_<id> checkbox list renders with all_groups + user_groups
    ///     (custom block, not a `<select multiple>`)
    #[test]
    fn user_edit_renders_dynamic_form() {
        let templates = Templates::new(None).expect("embedded templates");
        let identity_sections = user_edit_identity_sections("alice@example.com", "staff", true);
        let password_sections = user_edit_password_sections();
        let ctx = serde_json::json!({
            "site_title": "RustIO administration",
            "site_header": "RustIO administration",
            "index_title": "Site administration",
            "footer_copyright": "RustIO test",
            "csrf_token": "fake",
            "is_demo_session": false,
            "demo_label": null,
            "page_title": "Edit user",
            "entries": [],
            "user_id": 42,
            "email": "alice@example.com",
            "role": "staff",
            "is_active": true,
            "errors": [],
            "is_last_developer": false,
            "all_groups": [
                { "id": 1, "name": "editors", "description": "Edit posts" },
                { "id": 2, "name": "moderators", "description": "Moderate comments" },
            ],
            "user_groups": [1],
            "identity_sections": identity_sections,
            "password_sections": password_sections,
            "identity": { "email": "admin@example.com", "is_admin": true, "is_developer": false },
        });
        let body = templates
            .render("admin/user_edit.html", &ctx)
            .expect("user_edit renders");

        // Role select with all five options.
        assert!(body.contains("name=\"role\""), "role select missing");
        for value in ["user", "staff", "supervisor", "administrator", "developer"] {
            assert!(
                body.contains(&format!("value=\"{value}\"")),
                "role option {value:?} missing"
            );
        }
        // Staff is the current role → that option carries `selected`.
        let staff_idx = body.find("value=\"staff\"").expect("staff option");
        let after_staff = &body[staff_idx..staff_idx.saturating_add(80)];
        assert!(
            after_staff.contains("selected"),
            "Staff option should be selected; got: {after_staff:?}"
        );

        // is_active checkbox renders with name + checked (is_active=true
        // → FormField.value="true" → template sets the checked attr).
        assert!(
            body.contains("name=\"is_active\""),
            "is_active checkbox missing"
        );
        let active_idx = body.find("name=\"is_active\"").expect("is_active checkbox");
        let after_active = &body[active_idx..active_idx.saturating_add(160)];
        assert!(
            after_active.contains("checked"),
            "is_active should be checked when is_active=true; got: {after_active:?}"
        );

        // Group memberships render as the custom checkbox list — NOT a
        // <select multiple>. Each enabled group shows up as
        // `name="group_<id>"` and group #1 (in user_groups) is checked.
        assert!(
            !body.contains("<select multiple"),
            "groups must NOT render as select-multiple — checkbox list is the contract"
        );
        assert!(
            body.contains("name=\"group_1\""),
            "group_1 checkbox missing"
        );
        assert!(
            body.contains("name=\"group_2\""),
            "group_2 checkbox missing"
        );
        let g1_idx = body.find("name=\"group_1\"").expect("group_1 checkbox");
        let after_g1 = &body[g1_idx..g1_idx.saturating_add(100)];
        assert!(
            after_g1.contains("checked"),
            "group_1 should be checked (1 ∈ user_groups); got: {after_g1:?}"
        );
        // The per-group description still surfaces — that's the UX
        // feature the multi-select migration would have lost.
        assert!(
            body.contains("Edit posts"),
            "group description must render alongside the checkbox label"
        );

        // Email field is disabled (read-only display).
        assert!(
            body.contains("name=\"email\""),
            "email input must still be present"
        );
        let email_idx = body.find("name=\"email\"").expect("email input");
        let after_email = &body[email_idx..email_idx.saturating_add(200)];
        assert!(
            after_email.contains("disabled"),
            "email input must carry HTML disabled attribute; got: {after_email:?}"
        );
    }

    #[test]
    fn user_new_form_has_five_role_options() {
        // Phase 6.2 — user_new.html renders the role select via the
        // shared FormField include. Build the JSON ctx through the
        // public `user_new_form_sections` builder so the test exercises
        // the same path the handler uses; assertions on the rendered
        // markup are unchanged (5 options, Staff selected, no legacy
        // `is_staff`/`is_superuser` checkbox names).
        let templates = Templates::new(None).expect("embedded templates");
        let sections = user_new_form_sections("", "staff");
        let ctx = serde_json::json!({
            "site_title": "RustIO administration",
            "site_header": "RustIO administration",
            "index_title": "Site administration",
            "footer_copyright": "RustIO test",
            "csrf_token": "fake",
            "is_demo_session": false,
            "demo_label": null,
            "page_title": "Add user",
            "entries": [],
            "email": "",
            "role": "staff",
            "errors": [],
            "sections": sections,
            "identity": { "email": "admin@example.com", "is_admin": true },
        });
        let body = templates
            .render("admin/user_new.html", &ctx)
            .expect("user_new renders");

        for value in ["user", "staff", "supervisor", "administrator", "developer"] {
            assert!(
                body.contains(&format!("value=\"{value}\"")),
                "role option {value:?} missing"
            );
        }
        // Default role: "staff" → that option carries `selected`.
        let staff_idx = body.find("value=\"staff\"").expect("staff option");
        let after_staff = &body[staff_idx..staff_idx.saturating_add(80)];
        assert!(
            after_staff.contains("selected"),
            "Staff option should be selected; got: {after_staff:?}"
        );
        // Pre-7a/0.5/d checkbox names must NOT appear.
        assert!(
            !body.contains("name=\"is_staff\""),
            "old is_staff checkbox should be gone"
        );
        assert!(
            !body.contains("name=\"is_superuser\""),
            "old is_superuser checkbox should be gone"
        );
    }

    #[test]
    fn render_base_with_demo_banner() {
        let admin = Admin::new();
        let templates = Templates::new(None).expect("embedded templates");
        let demo_ident = Identity {
            user_id: 1,
            email: "staff@rustio.local".into(),
            role: Role::Staff,
            is_active: true,
            is_demo: true,
            demo_label: Some("Demo Staff".into()),
        };

        // Render the dashboard page (any page that extends base.html
        // works) and assert the banner is present with the label.
        let dash = dashboard_ctx(&demo_ident, &admin, vec![], "fake-csrf".into());
        let body = templates
            .render("admin/index.html", &dash)
            .expect("dashboard renders");

        assert!(body.contains("DEMO USER"), "demo banner text missing");
        assert!(body.contains("Demo Staff"), "demo_label not in banner");
        assert!(
            body.contains("RUSTIO_DEMO_MODE"),
            "banner should reference the env flag"
        );
    }

    #[test]
    fn render_base_without_demo_banner_for_real_user() {
        let admin = Admin::new();
        let templates = Templates::new(None).expect("embedded templates");
        let real_ident = Identity {
            user_id: 1,
            email: "admin@example.com".into(),
            role: Role::Administrator,
            is_active: true,
            is_demo: false,
            demo_label: None,
        };

        let dash = dashboard_ctx(&real_ident, &admin, vec![], "fake-csrf".into());
        let body = templates
            .render("admin/index.html", &dash)
            .expect("dashboard renders");

        assert!(
            !body.contains("DEMO USER"),
            "demo banner must NOT render for is_demo=false"
        );
        assert!(
            !body.contains("RUSTIO_DEMO_MODE"),
            "banner copy must be absent for real users"
        );
    }

    #[test]
    fn form_renders_required_marker_humanised_label_and_cancel() {
        // Phase 1/b — template-only assertion. Hand-built JSON ctx
        // mirrors the shape `form_ctx` produces; exercises the three
        // user-visible additions (humanised label, required-asterisk,
        // Cancel button) without depending on AdminEntry plumbing.
        let templates = Templates::new(None).expect("embedded templates");
        let ctx = serde_json::json!({
            "site_title": "RustIO administration",
            "site_header": "RustIO administration",
            "index_title": "Site administration",
            "footer_copyright": "RustIO test",
            "csrf_token": "fake",
            "is_demo_session": false,
            "demo_label": null,
            "page_title": "Add post",
            "entries": [],
            "admin_name": "posts",
            "display_name": "Posts",
            "singular_name": "Post",
            "mode": "new",
            "object_id": null,
            "errors": [],
            "identity": { "email": "admin@example.com", "is_admin": true, "is_developer": false },
            "sections": [
                {
                    "title": null,
                    "fields": [
                        {
                            "name": "title",
                            "label": "Title",
                            "widget": "text",
                            "input_type": "text",
                            "value": "",
                            "hint": null,
                            "placeholder": null,
                            "required": true,
                            "options": null,
                            "multiple": false,
                            "span": 1,
                            "autocomplete": null,
                            "autofocus": false,
                            "disabled": false,
                            "maxlength": null,
                            "searchable": false,
                            "has_more": false,
                            "search_url": null,
                        },
                        {
                            "name": "published",
                            "label": "Published",
                            "widget": "checkbox",
                            "input_type": "checkbox",
                            "value": "false",
                            "hint": null,
                            "placeholder": null,
                            "required": false,
                            "options": null,
                            "multiple": false,
                            "span": 1,
                            "autocomplete": null,
                            "autofocus": false,
                            "disabled": false,
                            "maxlength": null,
                            "searchable": false,
                            "has_more": false,
                            "search_url": null,
                        },
                    ],
                },
            ],
        });
        let body = templates
            .render("admin/form.html", &ctx)
            .expect("form renders");

        // Humanised label is rendered.
        assert!(body.contains(">Title"), "humanised Title label missing");

        // Required-asterisk: present for `title`, absent for `published`.
        // The label tag for `title` should contain the marker.
        let title_label_idx = body.find("for=\"id_title\"").expect("title label present");
        let title_label_end = title_label_idx
            + body[title_label_idx..]
                .find("</label>")
                .expect("label closes");
        let title_label = &body[title_label_idx..title_label_end];
        assert!(
            title_label.contains("class=\"required\""),
            "title label should carry the required marker, got: {title_label:?}"
        );

        let published_label_idx = body
            .find("for=\"id_published\"")
            .expect("published label present");
        let published_label_end = published_label_idx
            + body[published_label_idx..]
                .find("</label>")
                .expect("label closes");
        let published_label = &body[published_label_idx..published_label_end];
        assert!(
            !published_label.contains("class=\"required\""),
            "non-required field should not carry the marker, got: {published_label:?}"
        );

        // Cancel button points at the list page for this admin.
        assert!(
            body.contains("href=\"/admin/posts/\"") && body.contains(">\n            Cancel"),
            "Cancel link to list page missing",
        );

        // Save button still there — regression guard.
        assert!(body.contains("name=\"_save\""), "Save button missing");
    }

    /// Phase 6 — `form_ctx` partitions editable fields into Default,
    /// Metadata (audit-trail names), and Advanced (system identifier
    /// names) sections. Empty buckets are dropped so a model with only
    /// business fields renders as a single section.
    #[test]
    fn fields_are_grouped_into_sections() {
        // Build an AdminEntry with one field per bucket. All editable
        // so each appears in the form. Names chosen to fire each
        // heuristic arm:
        //   - "title"        → Default
        //   - "creation_timestamp" → Metadata (substring "timestamp")
        //   - "uuid"         → Advanced (exact match)
        static MIXED_FIELDS: &[crate::admin::AdminField] = &[
            crate::admin::AdminField {
                name: "title",
                label: "title",
                field_type: FieldType::String,
                editable: true,
                relation: None,
                choices: None,
            },
            crate::admin::AdminField {
                name: "creation_timestamp",
                label: "creation_timestamp",
                field_type: FieldType::DateTime,
                editable: true,
                relation: None,
                choices: None,
            },
            crate::admin::AdminField {
                name: "uuid",
                label: "uuid",
                field_type: FieldType::String,
                editable: true,
                relation: None,
                choices: None,
            },
        ];
        let admin = Admin::new();
        let entry = AdminEntry::for_testing("posts", "Posts", "Post", "posts", MIXED_FIELDS, false);
        let ident = fake_identity(Role::Administrator);
        let ctx = form_ctx(
            &ident,
            &admin,
            &entry,
            "new",
            None,
            None,
            vec![],
            "csrf".into(),
            HashMap::new(),
            HashMap::new(),
            None,
        );

        // Phase 10 / 10.1 — Metadata → "System" stays; the
        // "General" rename of the default section was reverted in
        // 10.1 (visual noise on every form). Default keeps no
        // header; Advanced unchanged.
        assert_eq!(
            ctx.sections.len(),
            3,
            "expected three sections, got {ctx_len:?}",
            ctx_len = ctx.sections.iter().map(|s| s.title).collect::<Vec<_>>()
        );
        assert_eq!(
            ctx.sections[0].title, None,
            "first section is the default bucket — no header"
        );
        assert_eq!(ctx.sections[0].fields.len(), 1);
        assert_eq!(ctx.sections[0].fields[0].name, "title");
        assert_eq!(
            ctx.sections[1].title,
            Some("System"),
            "second section is System (formerly Metadata)"
        );
        assert_eq!(ctx.sections[1].fields.len(), 1);
        assert_eq!(ctx.sections[1].fields[0].name, "creation_timestamp");
        assert_eq!(
            ctx.sections[2].title,
            Some("Advanced"),
            "third section is Advanced"
        );
        assert_eq!(ctx.sections[2].fields.len(), 1);
        assert_eq!(ctx.sections[2].fields[0].name, "uuid");

        // Common-case regression guard: a `user_id` field stays in
        // the Default section (FK with business meaning, not "advanced").
        static FK_FIELDS: &[crate::admin::AdminField] = &[
            crate::admin::AdminField {
                name: "title",
                label: "title",
                field_type: FieldType::String,
                editable: true,
                relation: None,
                choices: None,
            },
            crate::admin::AdminField {
                name: "user_id",
                label: "user_id",
                field_type: FieldType::I64,
                editable: true,
                relation: None,
                choices: None,
            },
        ];
        let entry2 = AdminEntry::for_testing("posts", "Posts", "Post", "posts", FK_FIELDS, false);
        let ctx2 = form_ctx(
            &ident,
            &admin,
            &entry2,
            "new",
            None,
            None,
            vec![],
            "csrf".into(),
            HashMap::new(),
            HashMap::new(),
            None,
        );
        assert_eq!(
            ctx2.sections.len(),
            1,
            "FK fields must NOT go to Advanced — they're business-meaningful"
        );
        assert_eq!(ctx2.sections[0].fields.len(), 2);
    }

    /// Phase 6 — a textarea-shaped field carries `span = 2`. The form
    /// template renders that field's wrapper with `col-span-2` so it
    /// fills the row instead of sharing it with a sibling. Locks
    /// both the form_ctx span computation AND the template's
    /// `{% if field.span == 2 %}col-span-2{% endif %}` branch.
    #[test]
    fn textarea_fields_span_full_width() {
        static TEXTAREA_FIELDS: &[crate::admin::AdminField] = &[
            // "body" hits the long-text-name heuristic → widget = "textarea".
            crate::admin::AdminField {
                name: "body",
                label: "body",
                field_type: FieldType::String,
                editable: true,
                relation: None,
                choices: None,
            },
            // Plain string field for contrast.
            crate::admin::AdminField {
                name: "title",
                label: "title",
                field_type: FieldType::String,
                editable: true,
                relation: None,
                choices: None,
            },
        ];
        let admin = Admin::new();
        let entry =
            AdminEntry::for_testing("posts", "Posts", "Post", "posts", TEXTAREA_FIELDS, false);
        let ident = fake_identity(Role::Administrator);
        let ctx = form_ctx(
            &ident,
            &admin,
            &entry,
            "new",
            None,
            None,
            vec![],
            "csrf".into(),
            HashMap::new(),
            HashMap::new(),
            None,
        );

        let body_field = ctx.sections[0]
            .fields
            .iter()
            .find(|f| f.name == "body")
            .expect("body field present");
        assert_eq!(body_field.widget, "textarea");
        assert_eq!(body_field.span, 2, "textarea must span both columns");

        let title_field = ctx.sections[0]
            .fields
            .iter()
            .find(|f| f.name == "title")
            .expect("title field present");
        assert_eq!(title_field.widget, "input");
        assert_eq!(title_field.span, 1, "plain input takes one column");

        // Template renders the col-span-2 wrapper for the textarea.
        let templates = Templates::new(None).expect("embedded templates");
        let body = templates
            .render("admin/form.html", &ctx)
            .expect("form renders");

        // Stabilization (v1.4.x) — the wrapper around the textarea field
        // uses the field-grid component's own .span-2 class instead of
        // the legacy Tailwind `col-span-2` utility. Same effect, single
        // source of truth.
        let body_wrapper_idx = body
            .find("class=\"span-2\"")
            .expect("span-2 wrapper present (the .field-grid-v14 component class)");
        let body_after = &body[body_wrapper_idx..];
        assert!(
            body_after.contains("name=\"body\""),
            "span-2 wrapper should contain the body field"
        );
    }

    /// Phase 1/c — shared list-page context fixture. Returns a JSON
    /// value with the empty-state shape (`rows: []`, `total_rows: 0`).
    /// Callers patch `search_query` / `filters` to flip between the
    /// true-empty and filtered-empty branches. Phase 5/a — `fields`
    /// replaces the old `columns` shape; row iteration in the template
    /// now uses `row[field.name]` to read each cell.
    fn empty_list_ctx_skeleton() -> serde_json::Value {
        serde_json::json!({
            "site_title": "RustIO administration",
            "site_header": "RustIO administration",
            "index_title": "Site administration",
            "footer_copyright": "RustIO test",
            "csrf_token": "fake",
            "is_demo_session": false,
            "demo_label": null,
            "page_title": "Posts",
            "entries": [],
            "admin_name": "posts",
            "display_name": "Posts",
            "singular_name": "Post",
            "fields": [
                { "name": "title",  "label": "title"  },
                { "name": "body",   "label": "body"   },
                { "name": "author", "label": "author" },
            ],
            "rows": [],
            "search_query": "",
            "filters": [],
            "page": 1,
            "total_pages": 1,
            "per_page": 25,
            "total_rows": 0,
            "bulk_actions_enabled": false,
            "identity": { "email": "admin@example.com", "is_admin": true, "is_developer": false },
        })
    }

    /// Phase 5/a — exercises the dynamic-row path: headers are driven
    /// by `fields[].label`, cells by `row[field.name]`. The empty-state
    /// tests above all hit the `{% else %}` branch and never iterate
    /// rows; this one renders a row so the new lookup path is locked
    /// in. Regression target: a future change that mistakenly drops
    /// the `flatten` on `ListRowCtx.values` would fail the cell
    /// assertions below.
    #[test]
    fn list_renders_rows_via_field_keyed_lookup() {
        let templates = Templates::new(None).expect("embedded templates");
        let mut ctx = empty_list_ctx_skeleton();
        ctx["rows"] = serde_json::json!([
            {
                "id": 7,
                "title": "Alpha",
                "body": "first body",
                "author": "alice",
            },
            {
                "id": 9,
                "title": "Beta",
                "body": "second body",
                "author": "bob",
            },
        ]);
        ctx["total_rows"] = serde_json::json!(2);
        let body = templates
            .render("admin/list.html", &ctx)
            .expect("list renders");

        // Header row: one <th> per field, label rendered.
        assert!(body.contains(">title</th>"), "title header missing");
        assert!(body.contains(">body</th>"), "body header missing");
        assert!(body.contains(">author</th>"), "author header missing");

        // Row 7: first column wrapped in the edit anchor; subsequent
        // cells render as plain text.
        assert!(
            body.contains("href=\"/admin/posts/7/edit\">Alpha</a>"),
            "row 7 first-column edit-link missing"
        );
        assert!(body.contains("first body"), "row 7 body cell missing");
        assert!(body.contains("alice"), "row 7 author cell missing");

        // Row 9 same.
        assert!(
            body.contains("href=\"/admin/posts/9/edit\">Beta</a>"),
            "row 9 first-column edit-link missing"
        );
        assert!(body.contains("second body"), "row 9 body cell missing");
        assert!(body.contains("bob"), "row 9 author cell missing");

        // Empty-state copy must NOT appear when rows are present.
        assert!(
            !body.contains("No posts yet"),
            "true-empty copy must not render when rows present"
        );
        assert!(
            !body.contains("No results match your search"),
            "filtered-empty copy must not render when rows present"
        );
    }

    #[test]
    fn list_true_empty_renders_friendly_cta() {
        // No rows, no search, no active filter — show the "Create
        // your first …" CTA and the friendly heading.
        let templates = Templates::new(None).expect("embedded templates");
        let ctx = empty_list_ctx_skeleton();
        let body = templates
            .render("admin/list.html", &ctx)
            .expect("list renders");

        assert!(body.contains("No posts yet."), "true-empty heading missing");
        assert!(
            body.contains("Create your first post"),
            "true-empty CTA copy missing",
        );
        assert!(
            body.contains("href=\"/admin/posts/new\""),
            "true-empty CTA link missing",
        );
        // The filtered-empty wording must NOT appear in this branch.
        assert!(
            !body.contains("No results match your search"),
            "true-empty branch leaked filtered-empty copy",
        );
    }

    #[test]
    fn list_filtered_empty_omits_cta() {
        // Search query active, no rows — show "no results match" and
        // suppress the CTA so we're not nudging "create" when the
        // user is actively narrowing.
        let templates = Templates::new(None).expect("embedded templates");
        let mut ctx = empty_list_ctx_skeleton();
        ctx["search_query"] = serde_json::Value::String("nonsense".into());
        let body = templates
            .render("admin/list.html", &ctx)
            .expect("list renders");

        assert!(
            body.contains("No results match your search"),
            "filtered-empty copy missing",
        );
        assert!(
            !body.contains("Create your first post"),
            "filtered-empty branch must not show the create CTA",
        );
        assert!(
            !body.contains("No posts yet"),
            "filtered-empty branch must not show the true-empty heading",
        );
    }

    /// Stabilization (v1.4.x) — list cell rendering is type-driven,
    /// not duck-typed. `field.kind` carries the FieldType widget
    /// string ("text" / "number" / "checkbox" / "datetime"); the
    /// template dispatches on it so that a numeric column gets
    /// `class="num"` on th + td, a checkbox column renders as a
    /// Yes/No badge, and a datetime column renders as the two-line
    /// stack — without ever inspecting the cell's string value.
    #[test]
    fn list_dispatches_cell_renderer_by_field_kind() {
        let templates = Templates::new(None).expect("embedded templates");
        let mut ctx = empty_list_ctx_skeleton();
        // Override the fields with explicit `kind` values mirroring
        // the four FieldType::widget() outputs.
        ctx["fields"] = serde_json::json!([
            { "name": "title",         "label": "Title",         "kind": "text" },
            { "name": "pages",         "label": "Pages",         "kind": "number" },
            { "name": "is_available",  "label": "Available",     "kind": "checkbox" },
            { "name": "published_at",  "label": "Published at",  "kind": "datetime" },
        ]);
        ctx["rows"] = serde_json::json!([
            {
                "id": 1,
                "title": "Sample",
                "pages": "180",
                // Stability lock (v1.4.x) — boolean cells arrive as
                // real JSON booleans, not strings. The list_ctx
                // builder type-converts at the boundary.
                "is_available": true,
                "published_at": "1925-04-10T00:00",
            },
            {
                "id": 2,
                "title": "Other",
                "pages": "311",
                "is_available": false,
                "published_at": "1932-09-05T00:00",
            },
        ]);
        ctx["total_rows"] = serde_json::json!(2);
        let body = templates
            .render("admin/list.html", &ctx)
            .expect("list renders");

        // Numeric column: th + td gain class="num" purely from kind.
        assert!(
            body.contains(r#"<th scope="col" class="num">Pages</th>"#),
            "numeric column header must carry class=\"num\" via field.kind, got fragment: {}",
            &body[..body.len().min(800)]
        );
        // Boolean column: badge dispatch.
        assert!(
            body.contains(r#"<span class="badge-v14 badge-yes-v14">Yes</span>"#),
            "checkbox column with value \"true\" must render the Yes badge"
        );
        assert!(
            body.contains(r#"<span class="badge-v14 badge-no-v14">No</span>"#),
            "checkbox column with value \"false\" must render the No badge"
        );
        // Datetime column: two-line stack with time on top, date below.
        assert!(
            body.contains(r#"<div class="rio-time">00:00</div>"#),
            "datetime cell must render time in .rio-time"
        );
        assert!(
            body.contains(r#"<div class="rio-date">1925-04-10</div>"#),
            "datetime cell must render date in .rio-date"
        );
        // First column (text) keeps the row-link convention untouched.
        assert!(
            body.contains(r#"href="/admin/posts/1/edit">Sample</a>"#),
            "first-column row-link convention must still apply for text columns"
        );
    }

    /// Stability lock (v1.4.x) — `list_ctx` MUST type-convert Bool
    /// cells to JSON booleans before they reach templates. This is
    /// the single normalization site for the boolean wire format
    /// ("true" / "false" emitted by the macro's display_values).
    /// Templates downstream do `{% if row[field.name] %}` truthiness;
    /// they never see the string forms again. Locks the boundary.
    #[test]
    fn list_ctx_normalizes_bool_cells_to_json_booleans() {
        use crate::admin::types::AdminEntry;
        use crate::admin::types::ListRow;
        use crate::admin::FieldType;

        // Two-field entry: one bool, one string. Cells come from the
        // macro as strings; list_ctx must keep the string as-is and
        // convert the bool to a real JSON boolean.
        static FIELDS: &[crate::admin::AdminField] = &[
            crate::admin::AdminField {
                name: "title",
                label: "Title",
                field_type: FieldType::String,
                editable: true,
                relation: None,
                choices: None,
            },
            crate::admin::AdminField {
                name: "is_available",
                label: "Available",
                field_type: FieldType::Bool,
                editable: true,
                relation: None,
                choices: None,
            },
        ];
        let admin = Admin::new();
        let entry = AdminEntry::for_testing("books", "Books", "Book", "books", FIELDS, false);
        let ident = fake_identity(Role::Administrator);

        // Cells are positional, in FIELDS order. The fixture's
        // FIELDS doesn't include an `id` column, so cells map
        // directly to (title, is_available).
        let rows = vec![
            ListRow { id: 1, cells: vec!["Gatsby".into(), "true".into()] },
            ListRow { id: 2, cells: vec!["Brave".into(), "false".into()] },
        ];
        let ctx = list_ctx(
            &ident, &admin, &entry, rows,
            String::new(), vec![], 1, 25, 2,
            "csrf".into(),
        );

        // Row 1: is_available was "true" → must be JSON `true`.
        let row1_avail = ctx.rows[0].values.get("is_available").expect("is_available cell");
        assert!(row1_avail.is_boolean(), "Bool cell must be a JSON boolean, got {row1_avail:?}");
        assert_eq!(row1_avail.as_bool(), Some(true));

        // Row 2: is_available was "false" → must be JSON `false`
        // (NOT the truthy string "false", which would render Yes
        // under template truthiness).
        let row2_avail = ctx.rows[1].values.get("is_available").expect("is_available cell");
        assert!(row2_avail.is_boolean(), "Bool cell must be a JSON boolean, got {row2_avail:?}");
        assert_eq!(row2_avail.as_bool(), Some(false));

        // Title (a String field) stays a JSON string. No type
        // conversion — the macro's display_values output IS the
        // display form for non-Bool types.
        let row1_title = ctx.rows[0].values.get("title").expect("title cell");
        assert!(row1_title.is_string(), "String cell must remain a JSON string, got {row1_title:?}");
        assert_eq!(row1_title.as_str(), Some("Gatsby"));
    }

    /// Stability lock (v1.4.x) — `form_ctx` MUST normalize the
    /// boolean form-data wire forms into a single `checked: bool`
    /// flag. `FormData::bool_flag` accepts any of `on / true / 1 /
    /// yes` as truthy on submit; this test pins that the same
    /// vocabulary is honored on render so a checkbox preserves its
    /// visual checked-state across submit-validate-rerender.
    #[test]
    fn form_ctx_normalizes_checkbox_value_to_checked_bool() {
        use crate::admin::types::AdminEntry;
        use crate::admin::FieldType;
        use crate::http::FormData;

        static FIELDS: &[crate::admin::AdminField] = &[
            crate::admin::AdminField {
                name: "is_active",
                label: "Active",
                field_type: FieldType::Bool,
                editable: true,
                relation: None,
                choices: None,
            },
        ];
        let admin = Admin::new();
        let entry = AdminEntry::for_testing("posts", "Posts", "Post", "posts", FIELDS, false);
        let ident = fake_identity(Role::Administrator);

        // Each candidate value should produce checked=true; everything
        // else (including the unchecked-checkbox empty string) → false.
        for truthy in ["on", "true", "1", "yes"] {
            let body = format!("is_active={truthy}");
            let form = FormData::from_urlencoded(&body);
            let ctx = form_ctx(
                &ident, &admin, &entry, "edit", Some(7), None,
                vec![], "csrf".into(), HashMap::new(), HashMap::new(),
                Some(&form),
            );
            let f = ctx.sections.iter().flat_map(|s| s.fields.iter())
                .find(|f| f.name == "is_active").expect("is_active");
            assert!(
                f.checked,
                "value {truthy:?} should produce checked=true (FormData::bool_flag contract)"
            );
        }

        // Unchecked checkbox (HTML omits absent fields entirely) → false.
        let form = FormData::from_urlencoded("");
        let ctx = form_ctx(
            &ident, &admin, &entry, "edit", Some(7), None,
            vec![], "csrf".into(), HashMap::new(), HashMap::new(),
            Some(&form),
        );
        let f = ctx.sections.iter().flat_map(|s| s.fields.iter())
            .find(|f| f.name == "is_active").expect("is_active");
        assert!(!f.checked, "absent checkbox in submission must produce checked=false");
    }

    /// Stabilization (v1.4.x) — the list template must not carry per-page
    /// `style="..."` attributes. Layout decisions belong in the CSS
    /// component classes (`.toolbar-form`, `.toolbar-v14`,
    /// `.actions-cell`). If anyone re-introduces an inline style for
    /// these surfaces, this test fails.
    #[test]
    fn list_template_has_no_per_page_inline_styles() {
        let templates = Templates::new(None).expect("embedded templates");
        let mut ctx = empty_list_ctx_skeleton();
        ctx["fields"] = serde_json::json!([
            { "name": "title", "label": "Title", "kind": "text" },
        ]);
        ctx["filters"] = serde_json::json!([
            {
                "field": "published",
                "label": "Published",
                "options": [
                    { "value": "true",  "label": "Yes", "selected": false },
                    { "value": "false", "label": "No",  "selected": false },
                ],
                "current": null,
            }
        ]);
        ctx["rows"] = serde_json::json!([{ "id": 1, "title": "x" }]);
        ctx["total_rows"] = serde_json::json!(1);
        let body = templates
            .render("admin/list.html", &ctx)
            .expect("list renders");

        // The three layout hacks the v1.4.x stabilization removed:
        for hack in [
            r#"style="display:contents""#,
            r#"style="margin-top:-4px""#,
            r#"style="width:100px;text-align:right""#,
        ] {
            assert!(
                !body.contains(hack),
                "list template must not carry per-page inline style {hack:?}"
            );
        }

        // The component classes that replaced them must be present.
        assert!(
            body.contains(r#"class="toolbar-form""#),
            "search form must use the .toolbar-form component class"
        );
        assert!(
            body.contains(r#"class="actions-cell""#),
            "Actions header must use the .actions-cell component class"
        );
    }

    /// Stabilization (v1.4.x) — guard against regression: there must
    /// be no hardcoded list of numeric field names in the template.
    /// If anyone re-introduces `field.name in ['pages', …]`, this
    /// test fails because a numeric column not in the list won't get
    /// `class="num"` even though its kind is "number".
    #[test]
    fn list_numeric_dispatch_is_kind_driven_not_name_driven() {
        let templates = Templates::new(None).expect("embedded templates");
        let mut ctx = empty_list_ctx_skeleton();
        // Field name `score` is NOT in the legacy hardcoded list —
        // before stabilization, this would render without class="num".
        ctx["fields"] = serde_json::json!([
            { "name": "title", "label": "Title", "kind": "text" },
            { "name": "score", "label": "Score", "kind": "number" },
        ]);
        ctx["rows"] = serde_json::json!([
            { "id": 1, "title": "x", "score": "42" },
        ]);
        ctx["total_rows"] = serde_json::json!(1);
        let body = templates
            .render("admin/list.html", &ctx)
            .expect("list renders");
        assert!(
            body.contains(r#"<th scope="col" class="num">Score</th>"#),
            "numeric column with arbitrary name must still get class=\"num\""
        );
    }

    #[test]
    fn list_filter_only_empty_omits_cta() {
        // Search empty but a filter group has a `current` value —
        // still treated as filtered, not true empty.
        let templates = Templates::new(None).expect("embedded templates");
        let mut ctx = empty_list_ctx_skeleton();
        ctx["filters"] = serde_json::json!([
            {
                "field": "published",
                "label": "Published",
                "options": [],
                "current": "true",
            }
        ]);
        let body = templates
            .render("admin/list.html", &ctx)
            .expect("list renders");

        assert!(
            body.contains("No results match your search"),
            "filter-only empty should still show 'No results match' copy",
        );
        assert!(
            !body.contains("Create your first post"),
            "filter-only empty must not show the create CTA",
        );
    }

    #[test]
    fn render_forbidden_body_with_attempted_perm() {
        let admin = Admin::new();
        let templates = Templates::new(None).expect("embedded templates");
        let ident = fake_identity(Role::Staff);

        let body = render_forbidden_body(
            &admin,
            &templates,
            &ident,
            "fake-csrf".into(),
            Some("posts.delete_post".into()),
            None,
        )
        .expect("forbidden page renders");

        assert!(
            body.contains("posts.delete_post"),
            "attempted permission should appear in body"
        );
        // When `required_role` is None the section is hidden.
        assert!(
            !body.contains("This page requires"),
            "required_role section must be hidden when None"
        );
    }

    /// Phase 7.5 — fixture for the inline-field-error tests. Builds a
    /// FormCtx-shaped JSON literal with one section containing two
    /// FormFields: `email` carries an error, `password` does not.
    /// Both pass through the same `_form_field.html` include, so a
    /// single render exercises the error / no-error paths together.
    fn form_with_field_errors_ctx() -> serde_json::Value {
        serde_json::json!({
            "site_title": "RustIO administration",
            "site_header": "RustIO administration",
            "index_title": "Site administration",
            "footer_copyright": "RustIO test",
            "csrf_token": "fake",
            "is_demo_session": false,
            "demo_label": null,
            "page_title": "Add user",
            "entries": [],
            "admin_name": "users",
            "display_name": "Users",
            "singular_name": "User",
            "mode": "new",
            "object_id": null,
            "errors": ["Email is required."],
            "flash": null,
            "identity": { "email": "admin@example.com", "is_admin": true, "is_developer": false },
            "sections": [
                {
                    "title": null,
                    "fields": [
                        {
                            "name": "email",
                            "label": "Email",
                            "widget": "input",
                            "input_type": "email",
                            "value": "",
                            "hint": null,
                            "placeholder": null,
                            "required": true,
                            "options": null,
                            "multiple": false,
                            "span": 1,
                            "autocomplete": null,
                            "autofocus": false,
                            "disabled": false,
                            "maxlength": null,
                            "searchable": false,
                            "has_more": false,
                            "search_url": null,
                            "errors": ["Email is required."],
                        },
                        {
                            "name": "password",
                            "label": "Password",
                            "widget": "input",
                            "input_type": "password",
                            "value": "",
                            "hint": null,
                            "placeholder": null,
                            "required": true,
                            "options": null,
                            "multiple": false,
                            "span": 1,
                            "autocomplete": null,
                            "autofocus": false,
                            "disabled": false,
                            "maxlength": null,
                            "searchable": false,
                            "has_more": false,
                            "search_url": null,
                            "errors": [],
                        },
                    ],
                },
            ],
        })
    }

    /// Phase 7.5 — Step 1 plumbing renders inline error copy under the
    /// field that owns it. Locks the (validator → field_errors map →
    /// `apply_field_errors` → `FormField.errors` → `_form_field.html`
    /// error block) end-to-end pipeline.
    #[test]
    fn field_errors_render_under_inputs() {
        let templates = Templates::new(None).expect("embedded templates");
        let body = templates
            .render("admin/form.html", &form_with_field_errors_ctx())
            .expect("form renders");

        // The error block lives under the email input with the
        // canonical id `error_<name>`.
        assert!(
            body.contains(r#"id="error_email""#),
            "expected <p id=\"error_email\"> error block, body fragment: {}",
            &body[..body.len().min(500)]
        );
        assert!(
            body.contains("Email is required."),
            "error message must surface under the email field"
        );
        // `password` has no errors → no error block for it. The
        // global error banner above the form may carry the same
        // string, so we narrow the assertion to the per-field id.
        assert!(
            !body.contains(r#"id="error_password""#),
            "no error for password → no error block expected"
        );
    }

    /// Phase 7.5 — `aria-invalid` toggles per-field. Errors → `"true"`,
    /// no errors → `"false"`. Locks the aria attribute the screen
    /// reader uses to announce a field as invalid.
    #[test]
    fn input_has_aria_invalid_when_error() {
        let templates = Templates::new(None).expect("embedded templates");
        let body = templates
            .render("admin/form.html", &form_with_field_errors_ctx())
            .expect("form renders");

        // Locate the email input, slice its tag, assert
        // aria-invalid="true".
        let email_idx = body.find(r#"name="email""#).expect("email input present");
        let email_start = body[..email_idx].rfind('<').expect("tag start");
        let email_end = email_idx + body[email_idx..].find('>').expect("tag end");
        let email_tag = &body[email_start..email_end];
        assert!(
            email_tag.contains(r#"aria-invalid="true""#),
            "email input must carry aria-invalid=\"true\", got: {email_tag}"
        );

        // Same slice trick for the password input — should be "false".
        let pw_idx = body
            .find(r#"name="password""#)
            .expect("password input present");
        let pw_start = body[..pw_idx].rfind('<').expect("tag start");
        let pw_end = pw_idx + body[pw_idx..].find('>').expect("tag end");
        let pw_tag = &body[pw_start..pw_end];
        assert!(
            pw_tag.contains(r#"aria-invalid="false""#),
            "password input must carry aria-invalid=\"false\", got: {pw_tag}"
        );
    }

    /// Phase 7.5 — `aria-describedby` on an erroring input must point
    /// at the id of the error block under it. Renders the same
    /// fixture and asserts both anchors exist with matching ids; if
    /// the template ever drifts (different id prefix on one side),
    /// screen readers stop announcing the error and this fails.
    #[test]
    fn aria_describedby_links_correctly() {
        let templates = Templates::new(None).expect("embedded templates");
        let body = templates
            .render("admin/form.html", &form_with_field_errors_ctx())
            .expect("form renders");

        // Input side: aria-describedby="error_email" only present
        // when errors exist.
        assert!(
            body.contains(r#"aria-describedby="error_email""#),
            "email input missing aria-describedby anchor"
        );
        // Error block side: the id the input points at must exist.
        assert!(
            body.contains(r#"id="error_email""#),
            "error block id must match aria-describedby target"
        );
        // No errors → no aria-describedby on the password input.
        let pw_idx = body
            .find(r#"name="password""#)
            .expect("password input present");
        let pw_end = pw_idx + body[pw_idx..].find('>').expect("tag close");
        let pw_tag = &body[pw_idx..pw_end];
        assert!(
            !pw_tag.contains("aria-describedby"),
            "password (no errors) must NOT carry aria-describedby"
        );
    }

    /// Phase 7.5 — the FK search-input Esc handler calls
    /// `e.stopPropagation()` so the global Esc-to-cancel listener
    /// doesn't navigate away when the user just wants to clear the
    /// search box. This test renders any page that extends base
    /// (login is the smallest) and locks both contract halves: the
    /// stopPropagation in the search-input branch AND the
    /// `[data-cancel]` selector in the global handler. If either
    /// drifts, Esc-to-clear regresses into Esc-to-cancel.
    #[test]
    fn search_escape_does_not_trigger_cancel() {
        let templates = Templates::new(None).expect("embedded templates");
        let body = templates
            .render(
                "admin/login.html",
                &serde_json::json!({
                    "site_title": "RustIO administration",
                    "site_header": "RustIO administration",
                    "index_title": "Site administration",
                    "footer_copyright": "RustIO test",
                    "csrf_token": "fake",
                    "is_demo_session": false,
                    "demo_label": null,
                    "page_title": "Sign in",
                    "error": null,
                    "identity": null,
                    "sections": [],
                }),
            )
            .expect("login renders");

        assert!(
            body.contains("e.stopPropagation()"),
            "search-input Esc handler must call stopPropagation()"
        );
        assert!(
            body.contains(r#"querySelector("[data-cancel]")"#),
            "global Esc handler must target [data-cancel] anchors"
        );
        // The global handler bails out when the keystroke originates
        // in an input/textarea, so individual element listeners
        // (search clear, etc.) get first crack.
        assert!(
            body.contains(r#"!e.target.matches("input, textarea")"#),
            "global Esc must be guarded against input/textarea targets"
        );
    }

    /// Phase 7.5 — empty-state regression. Phase 1/c shipped the
    /// "Create your first …" CTA on a true-empty list page; this
    /// test pins the contract so a future template churn can't
    /// silently drop the CTA. Pairs with
    /// `list_true_empty_renders_friendly_cta` above (which checks
    /// the heading copy); this one focuses on the button + href.
    #[test]
    fn empty_state_has_add_button() {
        let templates = Templates::new(None).expect("embedded templates");
        let ctx = empty_list_ctx_skeleton();
        let body = templates
            .render("admin/list.html", &ctx)
            .expect("list renders");

        assert!(
            body.contains("btn-primary"),
            "empty-state CTA must use btn-primary"
        );
        assert!(
            body.contains(r#"href="/admin/posts/new""#),
            "empty-state CTA must link to /admin/<name>/new"
        );
    }

    /// Phase 7.6 — a transient DB blip during FK lookup must NOT 500
    /// the search endpoint. Builds an Admin with one entry whose
    /// `ops.list()` returns a synthetic Err and calls
    /// `search_options`; asserts the function swallows the error and
    /// returns an empty Vec. The endpoint stays callable; the client
    /// falls back to its truncated in-page option set.
    ///
    /// `Db::for_testing_no_connection` builds a lazy pool that never
    /// opens a real connection — `FailingOps::list` returns Err before
    /// the db is dereferenced, so no network round-trip happens.
    #[tokio::test]
    async fn search_db_failure_safe() {
        static AUTHOR_FIELDS: &[crate::admin::AdminField] = &[];
        let mut admin = Admin::new();
        admin
            .entries
            .push(crate::admin::types::AdminEntry::for_testing_failing_list(
                "authors", "Authors", "Author", "authors", AUTHOR_FIELDS,
            ));
        let db = crate::orm::Db::for_testing_no_connection();

        // FailingOps path: list() returns Err → search_options swallows
        // → empty Vec.
        let opts = search_options(&admin, &db, "Author", "alice")
            .await
            .expect("search_options must NOT bubble the list() Err");
        assert!(
            opts.is_empty(),
            "FailingOps list() should fall through to empty Vec, got {n} options",
            n = opts.len()
        );

        // Unknown-model fast path — early return at the top of
        // `search_options`, never reaches list().
        let opts = search_options(&admin, &db, "DoesNotExist", "alice")
            .await
            .expect("unknown model must NOT error");
        assert!(opts.is_empty(), "unknown model should return empty Vec");
    }

    /// Phase 7.6 — a pathologically long query string (here 100KB)
    /// must be truncated at MAX_SEARCH_QUERY_CHARS. Verifies the
    /// helper is char-boundary-safe (multi-byte input doesn't panic)
    /// and bounds the work `filter_options` would otherwise do on
    /// an unbounded string.
    #[test]
    fn search_query_truncated() {
        // ASCII path: 100,000 chars in, MAX_SEARCH_QUERY_CHARS chars
        // out (`a` is 1 byte, so chars == bytes here).
        let huge = "a".repeat(100_000);
        let truncated = truncate_query(&huge);
        assert_eq!(
            truncated.chars().count(),
            MAX_SEARCH_QUERY_CHARS,
            "ASCII query must truncate to MAX_SEARCH_QUERY_CHARS chars"
        );
        assert_eq!(
            truncated.len(),
            MAX_SEARCH_QUERY_CHARS,
            "ASCII path: byte count == char count"
        );

        // Multi-byte path: a 4-byte emoji repeated 1,000 times. Chars
        // truncate at 200, bytes at 800. The slice must NOT panic on
        // a non-char-boundary cut.
        let emoji = "\u{1F600}".repeat(1_000); // grinning face emoji
        let truncated = truncate_query(&emoji);
        assert_eq!(
            truncated.chars().count(),
            MAX_SEARCH_QUERY_CHARS,
            "multi-byte query must truncate by char count, not bytes"
        );
        assert_eq!(
            truncated.len(),
            MAX_SEARCH_QUERY_CHARS * 4,
            "byte count = chars * UTF-8 width"
        );

        // Short queries pass through untouched.
        assert_eq!(truncate_query("alice"), "alice");
        assert_eq!(truncate_query(""), "");
    }

    // ----- Phase 10 — UX widget tests ----------------------------

    /// Phase 10.A — `slug`-named String field gains the placeholder
    /// "my-post-title" and the hint "URL-friendly identifier" via
    /// `intelligence::field_ui_metadata`. Locks the name-based UI
    /// override so it doesn't drift back to a role-classifier
    /// default (which would emit no placeholder for a plain
    /// `PlainText` slug).
    #[test]
    fn slug_field_has_placeholder_and_hint() {
        static SLUG_FIELDS: &[crate::admin::AdminField] = &[
            crate::admin::AdminField {
                name: "slug",
                label: "slug",
                field_type: FieldType::String,
                editable: true,
                relation: None,
                choices: None,
            },
        ];
        let admin = Admin::new();
        let entry = AdminEntry::for_testing("posts", "Posts", "Post", "posts", SLUG_FIELDS, false);
        let ident = fake_identity(Role::Administrator);
        let ctx = form_ctx(
            &ident,
            &admin,
            &entry,
            "new",
            None,
            None,
            vec![],
            "csrf".into(),
            HashMap::new(),
            HashMap::new(),
            None,
        );
        let slug = ctx
            .sections
            .iter()
            .flat_map(|s| s.fields.iter())
            .find(|f| f.name == "slug")
            .expect("slug field present");
        assert_eq!(slug.placeholder.as_deref(), Some("my-post-title"));
        assert_eq!(slug.hint.as_deref(), Some("URL-friendly identifier"));
    }

    /// Phase 10.B — a `status`-named String field with no `choices`
    /// and no relation gets synthesised select options
    /// `["draft", "published"]` and widget `"select"`. Schema is
    /// unchanged (the underlying field stays `String`); this is a
    /// pure UI hint.
    #[test]
    fn status_field_renders_select_with_synthesized_options() {
        static STATUS_FIELDS: &[crate::admin::AdminField] = &[
            crate::admin::AdminField {
                name: "status",
                label: "status",
                field_type: FieldType::String,
                editable: true,
                relation: None,
                choices: None,
            },
        ];
        let admin = Admin::new();
        let entry =
            AdminEntry::for_testing("posts", "Posts", "Post", "posts", STATUS_FIELDS, false);
        let ident = fake_identity(Role::Administrator);
        let ctx = form_ctx(
            &ident,
            &admin,
            &entry,
            "new",
            None,
            None,
            vec![],
            "csrf".into(),
            HashMap::new(),
            HashMap::new(),
            None,
        );
        let status = ctx
            .sections
            .iter()
            .flat_map(|s| s.fields.iter())
            .find(|f| f.name == "status")
            .expect("status field present");
        assert_eq!(status.widget, "select");
        let opts = status
            .options
            .as_ref()
            .expect("status field has synthesised options");
        let labels: Vec<&str> = opts.iter().map(|o| o.label.as_str()).collect();
        assert_eq!(labels, vec!["draft", "published"]);
    }

    /// Phase 10.C — a relation field gains a "Select <Model>…"
    /// placeholder and `target_model: Some("<Model>")` so the form
    /// template can render the empty-options message
    /// "No <Model> available". Locks the FK UX additions.
    #[test]
    fn fk_field_has_select_model_placeholder_and_target_model() {
        static FK_FIELDS: &[crate::admin::AdminField] = &[
            crate::admin::AdminField {
                name: "author_id",
                label: "author_id",
                field_type: FieldType::I64,
                editable: true,
                relation: Some(crate::admin::AdminRelation {
                    target_model: "User",
                    display_field: Some("email"),
                    multi: false,
                }),
                choices: None,
            },
        ];
        let admin = Admin::new();
        let entry = AdminEntry::for_testing("posts", "Posts", "Post", "posts", FK_FIELDS, false);
        let ident = fake_identity(Role::Administrator);
        let ctx = form_ctx(
            &ident,
            &admin,
            &entry,
            "new",
            None,
            None,
            vec![],
            "csrf".into(),
            HashMap::new(),
            HashMap::new(),
            None,
        );
        let fk = ctx
            .sections
            .iter()
            .flat_map(|s| s.fields.iter())
            .find(|f| f.name == "author_id")
            .expect("author_id field present");
        assert_eq!(fk.placeholder.as_deref(), Some("Select User…"));
        assert_eq!(fk.target_model.as_deref(), Some("User"));
    }

    /// Phase 11 — when a validation error sends the user back to the
    /// form, their typed values must repopulate the inputs (not the DB
    /// row, not blank). Locks the `submitted` arg's no-fallback
    /// semantics: while `submitted` is `Some`, `existing` is ignored
    /// even if a field is absent from the form (HTML omits unchecked
    /// checkboxes — they should re-render unchecked, not as the DB's
    /// `true`).
    #[test]
    fn form_ctx_prefers_submitted_over_existing() {
        static POST_FIELDS: &[crate::admin::AdminField] = &[
            crate::admin::AdminField {
                name: "title",
                label: "title",
                field_type: FieldType::String,
                editable: true,
                relation: None,
                choices: None,
            },
            crate::admin::AdminField {
                name: "is_active",
                label: "is_active",
                field_type: FieldType::Bool,
                editable: true,
                relation: None,
                choices: None,
            },
        ];
        let admin = Admin::new();
        let entry = AdminEntry::for_testing("posts", "Posts", "Post", "posts", POST_FIELDS, false);
        let ident = fake_identity(Role::Administrator);
        let existing = EditRow {
            id: 7,
            values: vec![
                ("title".into(), "DB title".into()),
                ("is_active".into(), "true".into()),
            ],
        };
        // Simulated POST: user typed a new title and unchecked is_active.
        // Unchecked checkboxes are absent from the urlencoded body.
        let form = FormData::from_urlencoded("title=Pending+Edit");

        let ctx = form_ctx(
            &ident,
            &admin,
            &entry,
            "edit",
            Some(7),
            Some(&existing),
            vec![],
            "csrf".into(),
            HashMap::new(),
            HashMap::new(),
            Some(&form),
        );
        let title = ctx
            .sections
            .iter()
            .flat_map(|s| s.fields.iter())
            .find(|f| f.name == "title")
            .expect("title field present");
        assert_eq!(
            title.value, "Pending Edit",
            "submitted value must override `existing` for `title`"
        );
        let active = ctx
            .sections
            .iter()
            .flat_map(|s| s.fields.iter())
            .find(|f| f.name == "is_active")
            .expect("is_active field present");
        assert_eq!(
            active.value, "",
            "absent checkbox in submission must render as empty (unchecked), not the DB's `true`"
        );
    }

    /// Phase 11 — a flat `Vec<String>` of validation messages from
    /// `from_form` is bucketed onto fields by humanised-label prefix.
    /// Verifies the macro contract: messages start with `"<Label> "`,
    /// where `<Label>` is `humanise_field(field.name)`. Unparseable
    /// strings stay in the global vec so the banner still renders them.
    #[test]
    fn bucket_errors_by_label_routes_by_field() {
        static POST_FIELDS: &[crate::admin::AdminField] = &[
            crate::admin::AdminField {
                name: "title",
                label: "title",
                field_type: FieldType::String,
                editable: true,
                relation: None,
                choices: None,
            },
            crate::admin::AdminField {
                name: "is_active",
                label: "is_active",
                field_type: FieldType::Bool,
                editable: true,
                relation: None,
                choices: None,
            },
            crate::admin::AdminField {
                name: "priority",
                label: "priority",
                field_type: FieldType::I32,
                editable: true,
                relation: None,
                choices: None,
            },
        ];
        let entry = AdminEntry::for_testing("posts", "Posts", "Post", "posts", POST_FIELDS, false);
        let (global, per_field) = bucket_errors_by_label(
            &entry,
            vec![
                "Title is required.".into(),
                "Priority must be a number.".into(),
                "Some opaque error not tied to a field.".into(),
            ],
        );
        assert_eq!(
            per_field.get("title").map(Vec::as_slice),
            Some(&["Title is required.".to_string()][..]),
        );
        assert_eq!(
            per_field.get("priority").map(Vec::as_slice),
            Some(&["Priority must be a number.".to_string()][..]),
        );
        assert!(
            !per_field.contains_key("is_active"),
            "is_active had no error, must not appear in per_field map"
        );
        assert_eq!(
            global,
            vec!["Some opaque error not tied to a field.".to_string()],
            "unparseable errors must fall through to the global banner"
        );
    }
}