runique 3.0.2

A Django-inspired web framework for Rust with ORM, templates, and comprehensive security middleware
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
//! Generation of `src/admins/admin.rs` — `DynForm` wrappers and `admin_register()` from `ResourceDef`.
use crate::admin::daemon::parser::{ParsedAdmin, ResourceDef};
use crate::utils::trad::t;
use std::{fmt::Write, fs, path::Path};

/// Generates `src/admins/admin.rs` — the only file produced by the daemon.
///
/// Contains:
/// - One `DynForm` implementation per resource (wrapping the concrete `RuniqueForm`)
/// - `admin_register()` → `HashMap<String, ResourceEntry>` populated at boot
pub(crate) fn generate(parsed: &ParsedAdmin) -> Result<(), String> {
    let admins_dir = Path::new("src/admins");

    // The generator owns exactly the three files written below, and `fs::write`
    // truncates them — so nothing has to be deleted first. Wiping the directory
    // (former `remove_dir_all`) only ever destroyed what the generator does NOT
    // own: a helper a developer dropped in there, which conflicted with nothing.
    // Not deleting is also safer on failure: a write error leaves the previous
    // `admin.rs` in place instead of an empty directory.
    fs::create_dir_all(admins_dir)
        .map_err(|e| format!("Impossible to create {}: {}", admins_dir.display(), e))?;

    write_readme(admins_dir)?;
    write_admin(parsed, admins_dir)?;
    write_mod(admins_dir)?;

    Ok(())
}

/// The warning addressed to the developer — translated, unlike `tracing` messages
/// which stay in English by convention: this one is read by a human opening the
/// directory, not by whoever greps the logs.
fn write_readme(dir: &Path) -> Result<(), String> {
    let content = format!(
        "<!-- {}\n     {} -->\n",
        t("daemon.generated_header"),
        t("daemon.generated_notice")
    );
    fs::write(dir.join("README.md"), content)
        .map_err(|e| format!("Impossible to write README.md: {}", e))
}

fn write_mod(dir: &Path) -> Result<(), String> {
    let content = "pub mod admin;\npub use admin::{routes, admin_state};\n";
    fs::write(dir.join("mod.rs"), content).map_err(|e| format!("Impossible to write mod.rs: {}", e))
}

fn write_admin(parsed: &ParsedAdmin, dir: &Path) -> Result<(), String> {
    let resources = &parsed.resources;
    let mut out = String::new();

    let _ = writeln!(out, "// {}", t("daemon.generated_header"));
    let _ = writeln!(out, "// {}", t("daemon.generated_notice"));
    let _ = writeln!(out);
    let _ = writeln!(out, "use runique::prelude::*;");
    let _ = writeln!(out);

    // Entity imports (AdminForm is generated by model! in each module)
    for r in resources {
        let module = model_to_module(&r.model_type);
        let _ = writeln!(out, "use crate::entities::{};", module);
    }
    let _ = writeln!(out);

    // One DynForm implementation per resource (main form + edit_form if declared)
    for r in resources {
        write_dyn_form_impl(&mut out, r)?;
        if r.edit_form_type.is_some() {
            write_edit_dyn_form_impl(&mut out, r)?;
        } else if r.bulk_create.is_some() {
            // bulk_create without explicit edit_form: auto-generate edit wrapper using AdminForm
            let module = model_to_module(&r.model_type);
            let default_form = format!("{}::AdminForm", module);
            let edit_wrapper = format!("{}EditFormDynWrapper", pascal_case(&module));
            write_dyn_form_wrapper(
                &mut out,
                &format!(
                    "DynForm edit wrapper for {} (auto from bulk_create)",
                    module
                ),
                &edit_wrapper,
                &default_form,
                "_db",
                "Ok(()) // update_fn handles persistence",
            )?;
        }
    }

    // admin_register()
    write_admin_register(&mut out, parsed)?;

    fs::write(dir.join("admin.rs"), out).map_err(|e| format!("Impossible to write admin.rs: {}", e))
}

fn write_dyn_form_impl(out: &mut String, r: &ResourceDef) -> Result<(), String> {
    let module = model_to_module(&r.model_type);
    let form_path = r
        .create_form_type
        .as_deref()
        .unwrap_or(&format!("{}::AdminForm", module))
        .to_string();
    let wrapper = format!("{}AdminFormDynWrapper", pascal_case(&module));
    write_dyn_form_wrapper(
        out,
        &format!("DynForm wrapper for {}::AdminForm", module),
        &wrapper,
        &form_path,
        "db",
        "self.0.save(db).await",
    )
}

fn write_edit_dyn_form_impl(out: &mut String, r: &ResourceDef) -> Result<(), String> {
    let edit_form_path = r.edit_form_type.as_ref().unwrap();
    let module = model_to_module(&r.model_type);
    let wrapper = format!("{}EditFormDynWrapper", pascal_case(&module));
    write_dyn_form_wrapper(
        out,
        &format!("DynForm edit wrapper for {}", edit_form_path),
        &wrapper,
        edit_form_path,
        "_db",
        "Ok(()) // update_fn handles persistence",
    )
}

fn write_admin_register(out: &mut String, parsed: &ParsedAdmin) -> Result<(), String> {
    let resources = &parsed.resources;

    let _ = writeln!(out, "/// Builds the admin registry at boot.");
    let _ = writeln!(out, "/// Called by the application builder.");
    let _ = writeln!(out, "pub fn admin_register() -> AdminRegistry {{");
    let _ = writeln!(out, "    let mut registry = AdminRegistry::new();");
    let _ = writeln!(
        out,
        "    for entry in runique::admin::builtin_resources() {{"
    );
    let _ = writeln!(out, "        registry.register(entry);");
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out);

    for r in resources {
        write_resource_entry(out, r)?;
    }

    // Applies configure{}: overrides the DisplayConfig and group_actions of any resource
    for cfg in &parsed.configures {
        if cfg.hidden {
            let _ = writeln!(out, "    registry.remove(\"{}\");", cfg.key);
            continue;
        }
        let has_display = !cfg.list_display.is_empty()
            || !cfg.list_exclude.is_empty()
            || !cfg.list_filter.is_empty();
        if has_display {
            let display_3: Vec<(
                String,
                String,
                Option<crate::admin::daemon::parser::FkDisplay>,
            )> = cfg
                .list_display
                .iter()
                .map(|(c, l)| (c.clone(), l.clone(), None))
                .collect();
            let chain = build_display_chain(&display_3, &cfg.list_exclude, &cfg.list_filter);
            let _ = writeln!(out, "    registry.configure(\"{}\", {});", cfg.key, chain);
        }
        if !cfg.group_action.is_empty() {
            let actions_str = build_group_actions_str(&cfg.group_action);
            let _ = writeln!(
                out,
                "    registry.configure_group_actions(\"{}\", vec![{}]);",
                cfg.key, actions_str
            );
        }
    }

    let _ = writeln!(out, "    registry");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);

    // routes() function — returns the Axum Router of the admin prototype
    let _ = writeln!(out, "/// Builds the admin CRUD routes for the given path.");
    let _ = writeln!(
        out,
        "/// To be passed to `.with_admin(|a| a.routes(admins::routes(\"/admin\")))` in main.rs."
    );
    let _ = writeln!(
        out,
        "/// This is where the admin lives. To serve it behind an extra segment"
    );
    let _ = writeln!(
        out,
        "/// (`/secret/admin/…`), add `.prefix(\"secret\")` — the two are independent."
    );
    let _ = writeln!(
        out,
        "pub fn routes(path: &str) -> runique::admin::AdminRoutes {{"
    );
    let _ = writeln!(out, "    let p = path.trim_end_matches('/');");
    let _ = writeln!(out, "    let router = runique::axum::Router::new()");
    let _ = writeln!(
        out,
        "        .route(&format!(\"{{}}/{{{{resource}}}}/{{{{action}}}}\", p), get(admin_get).post(admin_post))"
    );
    let _ = writeln!(
        out,
        "        .route(&format!(\"{{}}/{{{{resource}}}}/{{{{id}}}}/{{{{action}}}}\", p), get(admin_get_id).post(admin_post_id))"
    );
    // Nested (scoped child) routes: /{parent}/{parent_id}/{resource}/[{id}/]{action}
    let _ = writeln!(
        out,
        "        .route(&format!(\"{{}}/{{{{parent}}}}/{{{{parent_id}}}}/{{{{resource}}}}/{{{{action}}}}\", p), get(admin_nested_get).post(admin_nested_post))"
    );
    let _ = writeln!(
        out,
        "        .route(&format!(\"{{}}/{{{{parent}}}}/{{{{parent_id}}}}/{{{{resource}}}}/{{{{id}}}}/{{{{action}}}}\", p), get(admin_nested_get_id).post(admin_nested_post_id));"
    );
    let _ = writeln!(out, "    runique::admin::AdminRoutes::new(p, router)");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    let _ = writeln!(
        out,
        "/// Returns the shared state of the admin prototype (for the dashboard)."
    );
    let _ = writeln!(
        out,
        "pub fn admin_state() -> std::sync::Arc<PrototypeAdminState> {{"
    );
    let _ = writeln!(out, "    let config = Arc::new(AdminConfig::new());");
    let _ = writeln!(out, "    std::sync::Arc::new(PrototypeAdminState {{");
    let _ = writeln!(out, "        registry: Arc::new(admin_register()),");
    let _ = writeln!(out, "        config,");
    let _ = writeln!(out, "    }})");
    let _ = writeln!(out, "}}");

    Ok(())
}

fn write_resource_entry(out: &mut String, r: &ResourceDef) -> Result<(), String> {
    let key = &r.key;
    let model = full_model_path(&r.model_type);
    let title = &r.title;
    let module = model_to_module(&r.model_type);
    let form_path = r
        .create_form_type
        .as_deref()
        .unwrap_or(&format!("{}::AdminForm", module))
        .to_string();
    let wrapper = format!("{}AdminFormDynWrapper", pascal_case(&module));
    // ID conversion code from String according to id_type
    let id_parse_code = match r.id_type.as_str() {
        "I32" => {
            "let id = id.parse::<i32>().map_err(|_| DbErr::Custom(\"invalid id\".to_string()))?"
        }
        "I64" => {
            "let id = id.parse::<i64>().map_err(|_| DbErr::Custom(\"invalid id\".to_string()))?"
        }
        "Uuid" => {
            "let id = uuid::Uuid::parse_str(&id).map_err(|_| DbErr::Custom(\"invalid id\".to_string()))?"
        }
        _ => {
            // default "Pk": follows the big-pk feature flag automatically
            "let id = id.parse::<Pk>().map_err(|_| DbErr::Custom(\"invalid id\".to_string()))?"
        }
    };
    // `get_fn` alone can express "not found" cleanly (`Result<Option<Value>, _>`):
    // a malformed id is indistinguishable from "no such record" to every caller,
    // so it must never surface as a database error (never a 5xx on garbage input).
    // delete_fn/update_fn/partial_update_fn keep `id_parse_code` above — their
    // `Result<(), DbErr>` has no clean "not found" of their own; the admin
    // handlers already check existence via `get_fn` before calling them, so
    // this remains a defensive branch, not the one users actually hit.
    let id_parse_or_not_found = match r.id_type.as_str() {
        "I32" => "let Ok(id) = id.parse::<i32>() else { return Ok(None) }",
        "I64" => "let Ok(id) = id.parse::<i64>() else { return Ok(None) }",
        "Uuid" => "let Ok(id) = uuid::Uuid::parse_str(&id) else { return Ok(None) }",
        _ => "let Ok(id) = id.parse::<Pk>() else { return Ok(None) }",
    };

    // AdminResource
    let _ = writeln!(out, "    // ── Resource: {} ──", key);
    let _ = writeln!(out, "    let meta = AdminResource::new(");
    let _ = writeln!(out, "        \"{}\",", key);
    let _ = writeln!(out, "        \"{}\",", model);
    let _ = writeln!(out, "        \"AdminForm\",");
    let _ = writeln!(out, "        \"{}\",", title);
    let _ = writeln!(out, "    );");

    // inject_password: enabled when a custom create_form is declared
    if r.create_form_type.is_some() {
        let _ = writeln!(out, "    let meta = meta.inject_password(true);");
    }

    // Template overrides
    if let Some(ref t) = r.template_list {
        let _ = writeln!(out, "    let meta = meta.template_list(\"{}\");", t);
    }
    if let Some(ref t) = r.template_create {
        let _ = writeln!(out, "    let meta = meta.template_create(\"{}\");", t);
    }
    if let Some(ref t) = r.template_edit {
        let _ = writeln!(out, "    let meta = meta.template_edit(\"{}\");", t);
    }
    if let Some(ref t) = r.template_detail {
        let _ = writeln!(out, "    let meta = meta.template_detail(\"{}\");", t);
    }
    if let Some(ref t) = r.template_delete {
        let _ = writeln!(out, "    let meta = meta.template_delete(\"{}\");", t);
    }

    // Extra context
    for (k, v) in &r.extra_context {
        let _ = writeln!(out, "    let meta = meta.extra(\"{}\", \"{}\");", k, v);
    }

    // FormBuilder closure — injecte les ChoiceFields FK si déclarés dans list_display
    let fk_cols_for_form: Vec<_> = r
        .list_display
        .iter()
        .filter(|(_, _, fk)| fk.is_some())
        .collect();
    write_form_builder_closure_fk(out, "form_builder", &form_path, &wrapper, &fk_cols_for_form);

    // ListFn closure
    let _ = writeln!(
        out,
        "    let list_fn: ListFn = Arc::new(|db: ADb, params: ListParams| {{"
    );
    let _ = writeln!(out, "        Box::pin(async move {{");
    let _ = writeln!(
        out,
        "            use sea_orm::{{QueryFilter, sea_query::{{Alias, Expr, Order}}}};"
    );
    let _ = writeln!(
        out,
        "            let mut query = {}::Entity::find();",
        module
    );

    // Whitelist columns for sort and filters — built at code generation time from DSL declarations.
    // Any col not in the whitelist is silently ignored, preventing SQL injection via URL parameters.
    let sort_cols: Vec<String> = std::iter::once("id".to_string())
        .chain(r.list_display.iter().map(|(col, _, _)| col.clone()))
        .collect();
    let sort_cols_literal = sort_cols
        .iter()
        .map(|c| format!("\"{}\"", c))
        .collect::<Vec<_>>()
        .join(", ");
    let filter_cols: Vec<String> = r
        .list_filter
        .iter()
        .map(|(col, _, _)| col.clone())
        .collect();
    let filter_cols_literal = filter_cols
        .iter()
        .map(|c| format!("\"{}\"", c))
        .collect::<Vec<_>>()
        .join(", ");
    let _ = writeln!(
        out,
        "            const SORT_COLS: &[&str] = &[{sort_cols_literal}];",
        sort_cols_literal = sort_cols_literal
    );
    let _ = writeln!(
        out,
        "            const FILTER_COLS: &[&str] = &[{filter_cols_literal}];",
        filter_cols_literal = filter_cols_literal
    );

    let _ = writeln!(
        out,
        "            if let Some(ref col) = params.sort_by && SORT_COLS.contains(&col.as_str()) {{"
    );
    let _ = writeln!(
        out,
        "                let order = if params.sort_dir == SortDir::Desc {{ Order::Desc }} else {{ Order::Asc }};"
    );
    let _ = writeln!(
        out,
        "                query = query.order_by(Expr::col(Alias::new(col.as_str())), order);"
    );
    let _ = writeln!(out, "            }}");
    let _ = writeln!(
        out,
        "            for (col, val) in &params.column_filters {{"
    );
    let _ = writeln!(
        out,
        "                if !FILTER_COLS.contains(&col.as_str()) {{ continue; }}"
    );
    let _ = writeln!(
        out,
        "                query = query.filter(text_eq(&db, col.as_str(), val));"
    );
    let _ = writeln!(out, "            }}");
    // Trusted parent scope (framework-injected) — applied unconditionally, bypasses FILTER_COLS.
    let _ = writeln!(
        out,
        "            if let Some((col, val)) = &params.scope && col.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {{"
    );
    let _ = writeln!(
        out,
        "                query = query.filter(text_eq(&db, col.as_str(), val));"
    );
    let _ = writeln!(out, "            }}");
    let _ = writeln!(
        out,
        "            if let Some(ref search_str) = params.search {{"
    );
    write_search_conditions(out, &r.list_display, &module);
    let _ = writeln!(out, "                query = query.filter(search_cond);");
    let _ = writeln!(out, "            }}");
    let _ = writeln!(
        out,
        "            let db_rows = query.offset(params.offset).limit(params.limit).all(&*db).await?;"
    );
    let _ = writeln!(
        out,
        "            let rows: Vec<serde_json::Value> = db_rows.into_iter()"
    );
    let _ = writeln!(
        out,
        "                .map(|r| serde_json::to_value(r).unwrap_or(serde_json::Value::Null))"
    );
    let _ = writeln!(out, "                .collect();");
    // FK display columns are resolved at the display layer (handle_list / detail /
    // delete) via the meta, never here — so the edit form keeps the raw id and
    // pre-selects the right option. `fk_display_specs` feeds `meta.fk_display(...)`.
    let fk_cols: Vec<_> = r
        .list_display
        .iter()
        .filter(|(_, _, fk)| fk.is_some())
        .collect();
    let fk_display_specs: String = fk_cols
        .iter()
        .map(|(col, _, fk_opt)| {
            let fk = fk_opt.as_ref().unwrap();
            format!(
                "({c:?}.to_string(), {t:?}.to_string(), {fc:?}.to_string())",
                c = col,
                t = fk.table,
                fc = fk.col
            )
        })
        .collect::<Vec<_>>()
        .join(", ");
    let _ = writeln!(out, "            Ok(rows)");
    let _ = writeln!(out, "        }})");
    let _ = writeln!(out, "    }});");
    let _ = writeln!(out);

    // CountFn closure
    let _ = writeln!(
        out,
        "    let count_fn: CountFn = Arc::new(|db: ADb, _search: Option<String>, column_filters: Vec<(String, String)>, scope: Option<(String, String)>| {{"
    );
    let _ = writeln!(out, "        Box::pin(async move {{");
    let _ = writeln!(out, "            use sea_orm::QueryFilter;");
    let _ = writeln!(
        out,
        "            let mut query = {}::Entity::find();",
        module
    );
    // Same filters as list_fn, through the same allowlist: otherwise pagination
    // counts the rows a sidebar filter hides.
    let _ = writeln!(
        out,
        "            const FILTER_COLS: &[&str] = &[{filter_cols_literal}];"
    );
    let _ = writeln!(out, "            for (col, val) in &column_filters {{");
    let _ = writeln!(
        out,
        "                if !FILTER_COLS.contains(&col.as_str()) {{ continue; }}"
    );
    let _ = writeln!(
        out,
        "                query = query.filter(text_eq(&db, col.as_str(), val));"
    );
    let _ = writeln!(out, "            }}");
    let _ = writeln!(out, "            if let Some(ref search_str) = _search {{");
    write_search_conditions(out, &r.list_display, &module);
    let _ = writeln!(out, "                query = query.filter(search_cond);");
    let _ = writeln!(out, "            }}");
    // Mirror list_fn's trusted parent scope so a scoped list paginates on its scoped total.
    let _ = writeln!(
        out,
        "            if let Some((col, val)) = &scope && col.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {{"
    );
    let _ = writeln!(
        out,
        "                query = query.filter(text_eq(&db, col.as_str(), val));"
    );
    let _ = writeln!(out, "            }}");
    let _ = writeln!(out, "            query.count(&*db).await");
    let _ = writeln!(out, "        }})");
    let _ = writeln!(out, "    }});");
    let _ = writeln!(out);

    // GetFn closure
    let _ = writeln!(
        out,
        "    let get_fn: GetFn = Arc::new(|db: ADb, id: String| {{"
    );
    let _ = writeln!(out, "        Box::pin(async move {{");
    let _ = writeln!(out, "            {};", id_parse_or_not_found);
    let _ = writeln!(
        out,
        "            let Some(row) = {}::Entity::find_by_id(id).one(&*db).await? else {{ return Ok(None); }};",
        module
    );
    // Raw model — FK ids are NOT resolved here (edit reuses this to pre-fill the
    // form). Display views resolve via `meta.fk_display`. List fields
    // (`checkbox`/`multichoice`) live in their own table: added here.
    let _ = writeln!(
        out,
        "            let mut value = serde_json::to_value(&row).unwrap_or(serde_json::Value::Null);"
    );
    let _ = writeln!(
        out,
        "            row.admin_list_values(&*db, &mut value).await?;"
    );
    let _ = writeln!(out, "            Ok(Some(value))");
    let _ = writeln!(out, "        }})");
    let _ = writeln!(out, "    }});");
    let _ = writeln!(out);

    // DeleteFn closure
    let _ = writeln!(
        out,
        "    let delete_fn: DeleteFn = Arc::new(|db: ADb, id: String| {{"
    );
    let _ = writeln!(out, "        Box::pin(async move {{");
    let _ = writeln!(out, "            {};", id_parse_code);
    let _ = writeln!(
        out,
        "            {}::Entity::delete_by_id(id).exec(&*db).await.map(|_| ())",
        module
    );
    let _ = writeln!(out, "        }})");
    let _ = writeln!(out, "    }});");
    let _ = writeln!(out);

    // CreateFn closure — uses admin_from_form() generated by the proc-macro; its
    // FormDataError becomes a DbErr::Custom through `?`, shown on the form
    let _ = writeln!(
        out,
        "    let create_fn: CreateFn = Arc::new(|db: ADb, data: StrMap| {{"
    );
    let _ = writeln!(out, "        Box::pin(async move {{");
    if let Some(ref bulk_field) = r.bulk_create {
        // Bulk upsert: split the specified field by comma, update if exists, insert otherwise
        let _ = writeln!(out, "            use sea_orm::QueryFilter;");
        let _ = writeln!(
            out,
            "            let raw = data.get(\"{bulk_field}\").cloned().unwrap_or_default();",
            bulk_field = bulk_field
        );
        let _ = writeln!(
            out,
            "            let values: Vec<&str> = raw.split(',').map(str::trim).filter(|v| !v.is_empty()).collect();"
        );
        let _ = writeln!(out, "            for val in values {{");
        let _ = writeln!(out, "                let mut row = data.clone();");
        let _ = writeln!(
            out,
            "                row.insert(\"{bulk_field}\".to_string(), val.to_string());",
            bulk_field = bulk_field
        );
        let _ = writeln!(
            out,
            "                let existing_id: Option<String> = {}::Entity::find()",
            module
        );
        let _ = writeln!(
            out,
            "                    .filter(text_eq(&db, \"{bulk_field}\", val))",
            bulk_field = bulk_field
        );
        let _ = writeln!(out, "                    .one(&*db).await?");
        let _ = writeln!(out, "                    .map(|m| m.id.to_string());");
        let _ = writeln!(out, "                if let Some(id) = existing_id {{");
        let _ = writeln!(out, "                    {};", id_parse_code);
        let _ = writeln!(
            out,
            "                    {}::admin_from_form(&row, Some(id))?.update(&*db).await?;",
            module
        );
        let _ = writeln!(out, "                }} else {{");
        let _ = writeln!(
            out,
            "                    {}::admin_from_form(&row, None)?.insert(&*db).await?;",
            module
        );
        let _ = writeln!(out, "                }}");
        let _ = writeln!(out, "            }}");
        let _ = writeln!(out, "            Ok(())");
    } else {
        // The row, its list fields and its M2M links in one transaction
        let _ = writeln!(out, "            use sea_orm::TransactionTrait;");
        let _ = writeln!(out, "            let txn = db.begin().await?;");
        let _ = writeln!(
            out,
            "            let result = {}::admin_from_form(&data, None)?.insert(&txn).await?;",
            module
        );
        let _ = writeln!(
            out,
            "            result.admin_save_lists(&txn, &data).await?;"
        );
        for m2m in &r.m2m {
            let _ = writeln!(
                out,
                "            runique::admin::helper::m2m::write_links(&txn, \"{junction}\", \"{self_fk}\", \"{target_fk}\", result.id.into(), &data, \"m2m_{field}__\", false).await?;",
                junction = m2m.junction_table,
                self_fk = m2m.self_fk,
                target_fk = m2m.target_fk,
                field = m2m.field_name
            );
        }
        let _ = writeln!(out, "            txn.commit().await");
    }
    let _ = writeln!(out, "        }})");
    let _ = writeln!(out, "    }});");
    let _ = writeln!(out);

    // UpdateFn closure — uses admin_from_form() generated by the proc-macro
    let _ = writeln!(
        out,
        "    let update_fn: UpdateFn = Arc::new(|db: ADb, id: String, data: StrMap| {{"
    );
    let _ = writeln!(out, "        Box::pin(async move {{");
    let _ = writeln!(out, "            {};", id_parse_code);
    // The row, its list fields and its M2M links in one transaction
    let _ = writeln!(out, "            use sea_orm::TransactionTrait;");
    let _ = writeln!(out, "            let txn = db.begin().await?;");
    let _ = writeln!(
        out,
        "            let result = {}::admin_from_form(&data, Some(id))?.update(&txn).await?;",
        module
    );
    let _ = writeln!(
        out,
        "            result.admin_save_lists(&txn, &data).await?;"
    );
    for m2m in &r.m2m {
        let _ = writeln!(
            out,
            "            runique::admin::helper::m2m::write_links(&txn, \"{junction}\", \"{self_fk}\", \"{target_fk}\", id.into(), &data, \"m2m_{field}__\", true).await?;",
            junction = m2m.junction_table,
            self_fk = m2m.self_fk,
            target_fk = m2m.target_fk,
            field = m2m.field_name
        );
    }
    let _ = writeln!(out, "            txn.commit().await");
    let _ = writeln!(out, "        }})");
    let _ = writeln!(out, "    }});");
    let _ = writeln!(out);

    // PartialUpdateFn closure — uses admin_partial_update(): NotSet for absent fields
    let _ = writeln!(
        out,
        "    let partial_update_fn: UpdateFn = Arc::new(|db: ADb, id: String, data: StrMap| {{"
    );
    let _ = writeln!(out, "        Box::pin(async move {{");
    let _ = writeln!(out, "            {};", id_parse_code);
    let _ = writeln!(
        out,
        "            {}::admin_partial_update(&data, id)?",
        module
    );
    let _ = writeln!(out, "                .update(&*db).await.map(|_| ())");
    let _ = writeln!(out, "        }})");
    let _ = writeln!(out, "    }});");
    let _ = writeln!(out);

    // M2mLoaderFn closure (optional — only when m2m is declared)
    if !r.m2m.is_empty() {
        let _ = writeln!(
            out,
            "    let m2m_loader: M2mLoaderFn = Arc::new(|db: ADb, object_id: Option<String>| {{"
        );
        let _ = writeln!(out, "        Box::pin(async move {{");
        let _ = writeln!(
            out,
            "            use sea_orm::{{EntityTrait, ConnectionTrait}};"
        );
        let _ = writeln!(
            out,
            "            let mut fields: Vec<M2mFieldOptions> = Vec::new();"
        );
        for m2m in &r.m2m {
            let _ = writeln!(out, "            {{");
            let _ = writeln!(
                out,
                "                let rows = {entity}::Entity::find().all(&*db).await.unwrap_or_default();",
                entity = m2m.target_entity
            );
            let _ = writeln!(
                out,
                "                let choices: Vec<(String, String)> = rows.iter().map(|r| {{"
            );
            let _ = writeln!(
                out,
                "                    let v = serde_json::to_value(r).unwrap_or_default();"
            );
            let _ = writeln!(
                out,
                "                    let id = v.get(\"id\").map(|i| i.to_string().trim_matches('\"').to_string()).unwrap_or_default();"
            );
            let _ = writeln!(
                out,
                "                    let label = v.get(\"{display}\").and_then(|n| n.as_str()).unwrap_or(\"\").to_string();",
                display = m2m.target_display
            );
            let _ = writeln!(out, "                    (id, label)");
            let _ = writeln!(out, "                }}).collect();");
            let _ = writeln!(
                out,
                "                let selected = if let Some(ref oid) = object_id {{"
            );
            let _ = writeln!(
                out,
                "                    use sea_orm::sea_query::{{Query, Alias, Expr, ExprTrait}};"
            );
            let _ = writeln!(
                out,
                "                    let stmt = Query::select().expr(Expr::col(Alias::new(\"{target_fk}\")).cast_as(Alias::new(text_cast_type(&db)))).from(Alias::new(\"{junction}\")).and_where(text_eq(&db, \"{self_fk}\", oid)).to_owned();",
                target_fk = m2m.target_fk,
                junction = m2m.junction_table,
                self_fk = m2m.self_fk
            );
            let _ = writeln!(
                out,
                "                    db.query_all(&stmt).await.unwrap_or_default().iter().filter_map(|r| r.try_get_by_index::<String>(0).ok()).collect()"
            );
            let _ = writeln!(out, "                }} else {{ vec![] }};");
            let _ = writeln!(out, "                fields.push(M2mFieldOptions {{");
            let _ = writeln!(
                out,
                "                    field_name: \"{field_name}\".to_string(),",
                field_name = m2m.field_name
            );
            let _ = writeln!(
                out,
                "                    label: \"{label}\".to_string(),",
                label = m2m.label
            );
            let _ = writeln!(out, "                    choices,");
            let _ = writeln!(out, "                    selected,");
            let _ = writeln!(out, "                }});");
            let _ = writeln!(out, "            }}");
        }
        let _ = writeln!(out, "            fields");
        let _ = writeln!(out, "        }})");
        let _ = writeln!(out, "    }});");
        let _ = writeln!(out);
    }

    // EditFormBuilder closure (optional, or auto when bulk_create is declared)
    if let Some(ref edit_form_path) = r.edit_form_type {
        let edit_wrapper = format!("{}EditFormDynWrapper", pascal_case(&module));
        write_form_builder_closure(out, "edit_form_builder", edit_form_path, &edit_wrapper);
    } else if r.bulk_create.is_some() {
        let default_form = format!("{}::AdminForm", module);
        let edit_wrapper = format!("{}EditFormDynWrapper", pascal_case(&module));
        write_form_builder_closure(out, "edit_form_builder", &default_form, &edit_wrapper);
    }

    // DisplayConfig with list_display, list_exclude and/or list_filter if configured
    if !r.list_display.is_empty() || !r.list_exclude.is_empty() || !r.list_filter.is_empty() {
        let chain = build_display_chain(&r.list_display, &r.list_exclude, &r.list_filter);
        let _ = writeln!(out, "    let meta = meta.display({});", chain);
    }

    // FK display specs — consumed by the display handlers to resolve FK ids to labels.
    if !fk_display_specs.is_empty() {
        let _ = writeln!(
            out,
            "    let meta = meta.fk_display(vec![{fk_display_specs}]);"
        );
    }

    // FilterFn closure (distinct values for each configured column)
    if !r.list_filter.is_empty() {
        let _ = writeln!(
            out,
            "    let filter_fn: FilterFn = Arc::new(|db: ADb, pages: std::collections::HashMap<String, u64>| {{"
        );
        let _ = writeln!(out, "        Box::pin(async move {{");
        let _ = writeln!(
            out,
            "            use sea_orm::{{ConnectionTrait, ExprTrait}};"
        );
        let _ = writeln!(
            out,
            "            use sea_orm::sea_query::{{Query, Alias, Expr}};"
        );
        let _ = writeln!(
            out,
            "            let mut result: std::collections::HashMap<String, (Vec<String>, u64)> = std::collections::HashMap::new();"
        );
        for (col, _label, limit) in &r.list_filter {
            let _ = writeln!(
                out,
                "            let page_size_{col} = {limit}u64;",
                col = col,
                limit = limit
            );
            let _ = writeln!(
                out,
                "            let cur_page_{col} = pages.get(\"{col}\").copied().unwrap_or(0);",
                col = col
            );
            let _ = writeln!(
                out,
                "            let count_stmt_{col} = Query::select().expr(sea_orm::sea_query::Func::count_distinct(Expr::col(Alias::new(\"{col}\")))).from(Alias::new({module}::Entity.table_name())).and_where(Expr::col(Alias::new(\"{col}\")).is_not_null()).to_owned();",
                col = col,
                module = module
            );
            let _ = writeln!(
                out,
                "            let count_row_{col} = match db.query_one(&count_stmt_{col}).await {{ Ok(r) => r, Err(e) => {{ tracing::error!(\"[runique admin] list_filter `{key}.{col}`: column not found in DB — {{}}\", e); None }} }};",
                col = col,
                key = key
            );
            let _ = writeln!(
                out,
                "            let total_{col} = count_row_{col}.and_then(|r| r.try_get_by_index::<i64>(0).ok()).unwrap_or(0) as u64;",
                col = col
            );
            let _ = writeln!(
                out,
                "            let stmt_{col} = Query::select().distinct().expr(Expr::col(Alias::new(\"{col}\")).cast_as(Alias::new(text_cast_type(&db)))).from(Alias::new({module}::Entity.table_name())).and_where(Expr::col(Alias::new(\"{col}\")).is_not_null()).limit(page_size_{col}).offset(cur_page_{col} * page_size_{col}).to_owned();",
                col = col,
                module = module
            );
            let _ = writeln!(
                out,
                "            let rows_{col} = match db.query_all(&stmt_{col}).await {{ Ok(r) => r, Err(e) => {{ tracing::error!(\"[runique admin] list_filter `{key}.{col}`: column not found in DB — {{}}\", e); vec![] }} }};",
                col = col,
                key = key
            );
            let _ = writeln!(
                out,
                "            let mut vals_{col}: Vec<String> = rows_{col}.iter().filter_map(|r| r.try_get_by_index::<String>(0).ok()).collect(); vals_{col}.sort_by(|a, b| match (a.parse::<i64>(), b.parse::<i64>()) {{ (Ok(x), Ok(y)) => y.cmp(&x), _ => b.cmp(a) }});",
                col = col
            );
            let _ = writeln!(
                out,
                "            result.insert(\"{col}\".to_string(), (vals_{col}, total_{col}));",
                col = col
            );
        }
        let _ = writeln!(out, "            Ok(result)");
        let _ = writeln!(out, "        }})");
        let _ = writeln!(out, "    }});");
        let _ = writeln!(out);
    }

    let _ = writeln!(out, "    registry.register(");
    if r.edit_form_type.is_some() || r.bulk_create.is_some() {
        let _ = writeln!(out, "        ResourceEntry::new(meta, form_builder)");
        let _ = writeln!(
            out,
            "            .with_edit_form_builder(edit_form_builder)"
        );
    } else {
        let _ = writeln!(out, "        ResourceEntry::new(meta, form_builder)");
    }
    let _ = writeln!(
        out,
        "            .with_table(sea_orm::EntityName::table_name(&{}::Entity))",
        module
    );
    let _ = writeln!(out, "            .with_list_fn(list_fn)");
    let _ = writeln!(out, "            .with_get_fn(get_fn)");
    let _ = writeln!(
        out,
        "            .with_enum_label_fn({}::apply_enum_labels)",
        module
    );
    let _ = writeln!(out, "            .with_delete_fn(delete_fn)");
    let _ = writeln!(out, "            .with_create_fn(create_fn)");
    let _ = writeln!(out, "            .with_update_fn(update_fn)");
    let _ = writeln!(
        out,
        "            .with_partial_update_fn(partial_update_fn)"
    );
    let _ = writeln!(out, "            .with_count_fn(count_fn)");
    let _ = writeln!(
        out,
        "            .with_unique_fields({}::UNIQUE_FIELDS)",
        module
    );
    if !r.list_filter.is_empty() {
        let _ = writeln!(out, "            .with_filter_fn(filter_fn)");
    }
    if !r.group_action.is_empty() {
        let actions_str = build_group_actions_str(&r.group_action);
        let _ = writeln!(
            out,
            "            .with_group_actions(vec![{}])",
            actions_str
        );
    }
    if !r.m2m.is_empty() {
        let _ = writeln!(out, "            .with_m2m_loader(m2m_loader)");
    }
    if let Some(ref own_field) = r.own_field {
        let _ = writeln!(out, "            .with_own_field(\"{}\")", own_field);
    }
    let _ = writeln!(out, "    );");
    let _ = writeln!(out);

    Ok(())
}

// ─── Code generation helpers ─────────────────────────────────────────────────

/// Emits a complete `DynForm` impl block for a wrapper struct.
/// `save_param` is the parameter name ("db" or "_db"), `save_body` is the return expression.
fn write_dyn_form_wrapper(
    out: &mut String,
    comment: &str,
    wrapper: &str,
    form_path: &str,
    save_param: &str,
    save_body: &str,
) -> Result<(), String> {
    let _ = writeln!(out, "// ── {} ──", comment);
    let _ = writeln!(out, "struct {}(pub {});", wrapper, form_path);
    let _ = writeln!(out);
    let _ = writeln!(out, "#[async_trait]");
    let _ = writeln!(out, "impl DynForm for {} {{", wrapper);
    let _ = writeln!(out, "    async fn is_valid(&mut self) -> bool {{");
    let _ = writeln!(out, "        self.0.is_valid().await");
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out);
    let _ = writeln!(
        out,
        "    async fn save(&mut self, {}: &ADb) -> Result<(), DbErr> {{",
        save_param
    );
    let _ = writeln!(out, "        {}", save_body);
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out);
    let _ = writeln!(out, "    fn get_form(&self) -> &Forms {{");
    let _ = writeln!(out, "        self.0.get_form()");
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out);
    let _ = writeln!(out, "    fn get_form_mut(&mut self) -> &mut Forms {{");
    let _ = writeln!(out, "        self.0.get_form_mut()");
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out, "}}");
    let _ = writeln!(out);
    Ok(())
}

/// Emits a `FormBuilder` closure assigned to `var_name`.
fn write_form_builder_closure(out: &mut String, var_name: &str, form_path: &str, wrapper: &str) {
    let _ = writeln!(
        out,
        "    let {}: FormBuilder = Arc::new(|_db: ADb, _vec: Vec<std::string::String>, data: StrMap, tera: ATera, csrf: String, method: Method| {{",
        var_name
    );
    let _ = writeln!(out, "        Box::pin(async move {{");
    let _ = writeln!(
        out,
        "            let form = {}::build_with_data(&data, tera, &csrf, method).await;",
        form_path
    );
    let _ = writeln!(
        out,
        "            Box::new({}(form)) as Box<dyn DynForm>",
        wrapper
    );
    let _ = writeln!(out, "        }})");
    let _ = writeln!(out, "    }});");
    let _ = writeln!(out);
}

/// Emits a `FormBuilder` closure with optional FK ChoiceField injection from the DB.
/// When `fk_cols` is empty, behaves identically to `write_form_builder_closure`.
fn write_form_builder_closure_fk(
    out: &mut String,
    var_name: &str,
    form_path: &str,
    wrapper: &str,
    fk_cols: &[&(
        String,
        String,
        Option<crate::admin::daemon::parser::FkDisplay>,
    )],
) {
    let db_param = if fk_cols.is_empty() { "_db" } else { "db" };
    let _ = writeln!(
        out,
        "    let {var}: FormBuilder = Arc::new(|{db}: ADb, _vec: Vec<std::string::String>, data: StrMap, tera: ATera, csrf: String, method: Method| {{",
        var = var_name,
        db = db_param,
    );
    let _ = writeln!(out, "        Box::pin(async move {{");
    let mut_kw = if fk_cols.is_empty() { "let" } else { "let mut" };
    let _ = writeln!(
        out,
        "            {mut_kw} form = {form}::build_with_data(&data, tera, &csrf, method).await;",
        mut_kw = mut_kw,
        form = form_path,
    );
    for (col, label, fk_opt) in fk_cols {
        let fk = fk_opt.as_ref().unwrap();
        let safe_var = col.replace('.', "_");
        let _ = writeln!(out, "            {{");
        let _ = writeln!(
            out,
            "                use sea_orm::{{ConnectionTrait, sea_query::ExprTrait}};"
        );
        let _ = writeln!(
            out,
            "                let _fk_opt_stmt_{safe} = sea_orm::sea_query::Query::select().expr(sea_orm::sea_query::Expr::col(sea_orm::sea_query::Alias::new(\"id\")).cast_as(sea_orm::sea_query::Alias::new(runique::admin::helper::text_cast_type(&db)))).expr(sea_orm::sea_query::Expr::col(sea_orm::sea_query::Alias::new(\"{fk_col}\"))).from(sea_orm::sea_query::Alias::new(\"{fk_table}\")).to_owned();",
            safe = safe_var,
            fk_col = fk.col,
            fk_table = fk.table,
        );
        let _ = writeln!(
            out,
            "                let _fk_opt_choices_{safe}: Vec<(String, String)> = db.query_all(&_fk_opt_stmt_{safe}).await.unwrap_or_default().iter().filter_map(|row| {{ let id = row.try_get_by_index::<String>(0).ok()?; let lbl = row.try_get_by_index::<String>(1).ok()?; Some((id, lbl)) }}).collect();",
            safe = safe_var,
        );
        let _ = writeln!(
            out,
            "                form.get_form_mut().field_choices(\"{col}\", \"{label}\", _fk_opt_choices_{safe});",
            col = col,
            label = label,
            safe = safe_var,
        );
        let _ = writeln!(out, "            }}");
    }
    let _ = writeln!(
        out,
        "            Box::new({wrapper}(form)) as Box<dyn DynForm>",
        wrapper = wrapper,
    );
    let _ = writeln!(out, "        }})");
    let _ = writeln!(out, "    }});");
    let _ = writeln!(out);
}

/// Emits a `search_cond!` call for the search block, then folds in one `is_in`
/// branch per FK-displayed column.
///
/// A FK column (e.g. `commandes.user_id`) can't be searched as literal text —
/// `search_cond!`'s `icontains` would match the raw id, not the related label
/// the admin actually displays (e.g. `eihwaz_users.username`). Instead, the
/// pattern is first resolved against the related table via
/// [`fetch_fk_matching_ids`](crate::admin::helper::fetch_fk_matching_ids),
/// and the matching parent ids are OR'd into the condition against the FK
/// column itself — the same "resolve the join, then constrain by id" trick
/// `resolve_fk_labels` uses for display, applied to filtering instead.
fn write_search_conditions(
    out: &mut String,
    list_display: &[(
        String,
        String,
        Option<crate::admin::daemon::parser::FkDisplay>,
    )],
    module: &str,
) {
    let searchable: Vec<&str> = list_display
        .iter()
        .filter(|(_, _, fk)| fk.is_none())
        .map(|(col, _, _)| col.as_str())
        .collect();
    let fk_searchable: Vec<(&str, &crate::admin::daemon::parser::FkDisplay)> = list_display
        .iter()
        .filter_map(|(col, _, fk)| fk.as_ref().map(|f| (col.as_str(), f)))
        .collect();

    // `search_cond` is only reassigned below when there's at least one
    // FK-displayed searchable column — `mut` on an all-literal search would
    // otherwise trigger an unused-mut warning in the generated code.
    let mut_kw = if fk_searchable.is_empty() { "" } else { "mut " };

    if searchable.is_empty() && fk_searchable.is_empty() {
        let _ = writeln!(
            out,
            "                let {mut_kw}search_cond = search_cond!(&db => {module}::Entity => all_columns icontains search_str);",
            mut_kw = mut_kw,
            module = module
        );
    } else if searchable.is_empty() {
        // Only FK-displayed columns are searchable — start from an empty OR so
        // only the FK id sets resolved below can add a match.
        let _ = writeln!(
            out,
            "                let {mut_kw}search_cond = sea_orm::Condition::any();",
            mut_kw = mut_kw
        );
    } else {
        let cols = searchable
            .iter()
            .map(|col| format!("\"{}\" icontains search_str", col))
            .collect::<Vec<_>>()
            .join(", ");
        let _ = writeln!(
            out,
            "                let {mut_kw}search_cond = search_cond!(&db => {module}::Entity => or({cols}));",
            mut_kw = mut_kw,
            module = module,
            cols = cols
        );
    }

    for (col, fk) in &fk_searchable {
        let _ = writeln!(out, "                {{");
        let _ = writeln!(
            out,
            "                    let __fk_ids = runique::admin::helper::fetch_fk_matching_ids(&*db, \"{table}\", \"{fk_col}\", search_str).await;",
            table = fk.table,
            fk_col = fk.col,
        );
        let _ = writeln!(out, "                    if !__fk_ids.is_empty() {{");
        let _ = writeln!(
            out,
            "                        use sea_orm::sea_query::ExprTrait;"
        );
        let _ = writeln!(
            out,
            "                        search_cond = search_cond.add(sea_orm::sea_query::Expr::col(sea_orm::sea_query::Alias::new(\"{col}\")).cast_as(sea_orm::sea_query::Alias::new(runique::admin::helper::text_cast_type(&db))).is_in(__fk_ids));",
            col = col,
        );
        let _ = writeln!(out, "                    }}");
        let _ = writeln!(out, "                }}");
    }
}

/// Builds a `DisplayConfig::new().columns_include(...).columns_exclude(...).list_filter(...)` chain.
fn build_display_chain(
    list_display: &[(
        String,
        String,
        Option<crate::admin::daemon::parser::FkDisplay>,
    )],
    list_exclude: &[String],
    list_filter: &[(String, String, u64)],
) -> String {
    let mut chain = "DisplayConfig::new()".to_string();
    if !list_display.is_empty() {
        let cols = list_display
            .iter()
            .map(|(c, l, _)| format!("(\"{}\", \"{}\")", c, l))
            .collect::<Vec<_>>()
            .join(", ");
        chain.push_str(&format!(".columns_include(vec![{}])", cols));
    }
    if !list_exclude.is_empty() {
        let cols = list_exclude
            .iter()
            .map(|c| format!("\"{}\"", c))
            .collect::<Vec<_>>()
            .join(", ");
        chain.push_str(&format!(".columns_exclude(vec![{}])", cols));
    }
    if !list_filter.is_empty() {
        let filters = list_filter
            .iter()
            .map(|(col, label, limit)| format!("(\"{}\", \"{}\", {}u64)", col, label, limit))
            .collect::<Vec<_>>()
            .join(", ");
        chain.push_str(&format!(".list_filter(vec![{}])", filters));
    }
    chain
}

/// Builds a comma-separated list of `GroupAction::*` expressions.
fn build_group_actions_str(group_action: &[(String, String, Option<String>)]) -> String {
    group_action
        .iter()
        .map(|(f, l, v)| match v {
            Some(val) => format!("GroupAction::val(\"{}\", \"{}\", \"{}\")", f, l, val),
            None => format!("GroupAction::bool(\"{}\", \"{}\")", f, l),
        })
        .collect::<Vec<_>>()
        .join(", ")
}

// ─── Path utilities ──────────────────────────────────────────────────────────

fn full_model_path(model_type: &str) -> String {
    if model_type.starts_with("crate::") || model_type.starts_with("runique::") {
        model_type.to_string()
    } else {
        format!("crate::entities::{}", model_type)
    }
}

/// Converts snake_case → PascalCase (e.g., `blog_post` → `BlogPost`)
fn pascal_case(s: &str) -> String {
    s.split('_')
        .map(|word| {
            let mut c = word.chars();
            match c.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().collect::<String>() + c.as_str(),
            }
        })
        .collect()
}

/// Extracts the module name from a model path.
/// Ex: `users::Model` → `users`, `crate::entities::blog_post::Model` → `blog_post`
/// The last segment is the struct name (Model), the second to last is the module.
fn model_to_module(model_type: &str) -> String {
    let segments: Vec<&str> = model_type.split("::").collect();
    if segments.len() >= 2 {
        segments[segments.len().saturating_sub(2)].to_string()
    } else {
        // Fallback: PascalCase → snake_case for the single segment
        let base = segments.last().copied().unwrap_or(model_type);
        let mut result = String::new();
        for (i, c) in base.chars().enumerate() {
            if c.is_uppercase() && i > 0 {
                result.push('_');
            }
            result.extend(c.to_lowercase());
        }
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::admin::daemon::parser::parse_admin_file;

    fn entry(body: &str) -> String {
        let parsed = parse_admin_file(&format!("admin! {{\n{body}\n}}")).expect("parses");
        let mut out = String::new();
        write_resource_entry(&mut out, &parsed.resources[0]).expect("writes");
        out
    }

    // List fields (`checkbox`/`multichoice`) live in their own table: the
    // generated closures read and write them with the row, whatever the model.
    #[test]
    fn create_update_and_get_handle_the_list_fields() {
        let out = entry(r#"books: book::Model => BookForm { title: "Books" }"#);
        let create = &out[out.find("let create_fn").unwrap()..out.find("let update_fn").unwrap()];
        let update =
            &out[out.find("let update_fn").unwrap()..out.find("let partial_update_fn").unwrap()];
        let get = &out[out.find("let get_fn").unwrap()..out.find("let delete_fn").unwrap()];
        for code in [create, update] {
            assert!(code.contains("db.begin()"), "{code}");
            assert!(
                code.contains("result.admin_save_lists(&txn, &data)"),
                "{code}"
            );
            assert!(code.contains("txn.commit()"), "{code}");
        }
        assert!(
            get.contains("row.admin_list_values(&*db, &mut value)"),
            "{get}"
        );
    }

    /// One `admin!{}` using every option the generator knows.
    const GOLDEN_INPUT: &str = r#"admin! {
        plats: plat::Model => PlatForm {
            title: "Plats",
            id_type: I32,
            list_display: [["nom", "Nom"], ["menu_id", "Menu", "menus.titre"]],
            list_filter: [["statut", "Statut", 25]],
            group_action: [["is_active", "Activer", "true"], ["is_staff", "Toggle staff"]],
            m2m: [["allergenes", "Allergènes", "plat_allergene", "plat_id", "allergene_id", "crate::entities::allergene", "nom"]],
            edit_form: crate::forms::PlatEditForm,
            bulk_create: allergenes
        },
        tags: crate::entities::tag::Model => TagForm { title: "Tags", id_type: Uuid, list_exclude: ["secret"] },
        logs: log::Model => LogForm { title: "Logs", id_type: I64, edit_form: crate::forms::LogEditForm },
        notes: note::Model => NoteForm { title: "Notes", list_display: [["author_id", "Auteur", "users.username"]] },
        configure {
            users: { list_display: [["username", "Nom"]], group_action: [["is_active", "Activer", "true"]] },
            droits: { hidden: true },
            groupes: { group_action: [["nom", "Renommer", "x"]] },
            sessions: { list_filter: [["user_id", "User", 10]] },
            history: { list_exclude: ["summary"] }
        }
    }"#;

    const GOLDEN_PATH: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/src/admin/daemon/golden_admin.txt"
    );

    fn temp_admins_dir(tag: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("rq_gen_{tag}_{}", uuid::Uuid::new_v4()));
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// The generated `admin.rs`, compared whole with the committed reference.
    /// Any change to the generator's output shows up here: review the diff,
    /// then refresh the reference with `RUNIQUE_UPDATE_GOLDEN=1`.
    ///
    /// The reference is text, never compiled: `cast_as_has_its_trait_in_scope`
    /// checks the one thing it once froze broken.
    /// Written from cargo-mutants survivors (2026-10-08): write_admin,
    /// write_admin_register, write_resource_entry and the form wrappers.
    #[test]
    fn generated_admin_matches_the_reference() {
        let parsed = parse_admin_file(GOLDEN_INPUT).expect("parses");
        let dir = temp_admins_dir("golden");
        write_admin(&parsed, &dir).expect("writes");
        let out = fs::read_to_string(dir.join("admin.rs")).unwrap();
        let _ = fs::remove_dir_all(&dir);
        if std::env::var_os("RUNIQUE_UPDATE_GOLDEN").is_some() {
            fs::write(GOLDEN_PATH, &out).unwrap();
        }
        let expected = fs::read_to_string(GOLDEN_PATH).expect("reference file");
        assert!(
            out == expected,
            "generated admin.rs changed: diff it against {GOLDEN_PATH}"
        );
    }

    #[test]
    fn readme_and_mod_are_written() {
        let dir = temp_admins_dir("files");
        write_readme(&dir).unwrap();
        write_mod(&dir).unwrap();
        let readme = fs::read_to_string(dir.join("README.md")).unwrap();
        let module = fs::read_to_string(dir.join("mod.rs")).unwrap();
        let _ = fs::remove_dir_all(&dir);
        assert!(readme.contains(&*t("daemon.generated_header")), "{readme}");
        assert_eq!(
            module,
            "pub mod admin;\npub use admin::{routes, admin_state};\n"
        );
    }

    #[test]
    fn model_paths_and_names() {
        assert_eq!(full_model_path("crate::x::Model"), "crate::x::Model");
        assert_eq!(
            full_model_path("runique::auth::user::Model"),
            "runique::auth::user::Model"
        );
        assert_eq!(
            full_model_path("blog::Model"),
            "crate::entities::blog::Model"
        );
        assert_eq!(pascal_case("blog_post"), "BlogPost");
        assert_eq!(pascal_case("users"), "Users");
        assert_eq!(model_to_module("users::Model"), "users");
        assert_eq!(
            model_to_module("crate::entities::blog_post::Model"),
            "blog_post"
        );
        assert_eq!(model_to_module("BlogPost"), "blog_post");
        assert_eq!(model_to_module("Model"), "model");
    }

    /// `cast_as` comes from `ExprTrait`: each generated block calling it imports
    /// the trait first (the FK select block didn't, and the admin of any
    /// resource with a FK field failed to compile).
    #[test]
    fn cast_as_has_its_trait_in_scope() {
        let parsed = parse_admin_file(GOLDEN_INPUT).expect("parses");
        let dir = temp_admins_dir("cast_as");
        write_admin(&parsed, &dir).expect("writes");
        let code = fs::read_to_string(dir.join("admin.rs")).unwrap();
        let _ = fs::remove_dir_all(&dir);
        // A block's imports are consecutive `use` lines: the trait may be on any of them.
        let (mut in_imports, mut has_trait) = (false, false);
        for line in code.lines() {
            if line.trim_start().starts_with("use sea_orm") {
                has_trait = (in_imports && has_trait) || line.contains("ExprTrait");
                in_imports = true;
                continue;
            }
            in_imports = false;
            if line.contains(".cast_as(") {
                assert!(has_trait, "no ExprTrait before: {line}");
            }
        }
    }
}