ferro-cli 0.2.21

CLI for scaffolding Ferro web applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
//! `ferro make:api` command — scaffolds a complete REST API layer for existing models.
//!
//! Generates CRUD controllers, API resources, request validation types,
//! route registration with API key middleware, OpenAPI docs endpoint,
//! and API key migration.

use console::style;
use quote::ToTokens;
use std::fs;
use std::path::Path;
use syn::visit::Visit;
use syn::{Attribute, Fields, ItemStruct, Type};
use walkdir::WalkDir;

// ---------------------------------------------------------------------------
// Sensitive field auto-exclusion
// ---------------------------------------------------------------------------

/// Field names that are auto-excluded from API resources (response serialization).
/// Matched case-insensitively, exact match only.
const SENSITIVE_FIELD_PATTERNS: &[&str] = &[
    "password",
    "password_hash",
    "hashed_password",
    "secret",
    "token",
    "api_key",
    "hashed_key",
    "remember_token",
];

/// Filter fields for API resource generation, excluding sensitive and user-specified fields.
///
/// Returns references to fields that should be included in the resource.
/// When `include_all` is true, no auto-exclusion is applied (user `--exclude` still applies).
pub(crate) fn filter_resource_fields<'a>(
    fields: &'a [FieldInfo],
    exclude: &[String],
    include_all: bool,
) -> Vec<&'a FieldInfo> {
    fields
        .iter()
        .filter(|f| {
            let name_lower = f.name.to_lowercase();

            // Check user-specified exclusions (always applied)
            if exclude.iter().any(|e| e.to_lowercase() == name_lower) {
                return false;
            }

            // Check sensitive field patterns (unless --include-all)
            if !include_all
                && SENSITIVE_FIELD_PATTERNS
                    .iter()
                    .any(|p| p.to_lowercase() == name_lower)
            {
                return false;
            }

            true
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Model metadata types
// ---------------------------------------------------------------------------

/// Parsed model information extracted from source files via syn.
#[derive(Debug, Clone)]
struct ModelInfo {
    /// PascalCase struct name (e.g., "User")
    name: String,
    /// Module name under `crate::models::` (e.g., "users" for `crate::models::users`)
    module_name: String,
    /// Table name from `#[sea_orm(table_name = "...")]`
    table_name: Option<String>,
    /// All struct fields
    fields: Vec<FieldInfo>,
}

#[derive(Debug, Clone)]
pub(crate) struct FieldInfo {
    pub(crate) name: String,
    pub(crate) rust_type: String,
    pub(crate) is_primary_key: bool,
    pub(crate) is_nullable: bool,
}

// ---------------------------------------------------------------------------
// AST visitor for model detection
// ---------------------------------------------------------------------------

struct ModelVisitor {
    models: Vec<ModelInfo>,
}

impl ModelVisitor {
    fn new() -> Self {
        Self { models: Vec::new() }
    }

    fn has_model_derive(attrs: &[Attribute]) -> bool {
        for attr in attrs {
            if attr.path().is_ident("derive") {
                if let Ok(nested) = attr.parse_args_with(
                    syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated,
                ) {
                    for path in nested {
                        let ident = path.segments.last().map(|s| s.ident.to_string());
                        if matches!(
                            ident.as_deref(),
                            Some("DeriveEntityModel") | Some("FerroModel")
                        ) {
                            return true;
                        }
                    }
                }
            }
        }
        false
    }

    fn extract_table_name(attrs: &[Attribute]) -> Option<String> {
        for attr in attrs {
            if attr.path().is_ident("sea_orm") {
                if let Ok(syn::Meta::NameValue(nv)) = attr.parse_args::<syn::Meta>() {
                    if nv.path.is_ident("table_name") {
                        if let syn::Expr::Lit(syn::ExprLit {
                            lit: syn::Lit::Str(s),
                            ..
                        }) = nv.value
                        {
                            return Some(s.value());
                        }
                    }
                }
            }
        }
        None
    }

    fn is_field_primary_key(attrs: &[Attribute]) -> bool {
        for attr in attrs {
            if attr.path().is_ident("sea_orm") {
                let tokens = attr.meta.to_token_stream().to_string();
                if tokens.contains("primary_key") {
                    return true;
                }
            }
        }
        false
    }

    fn type_to_string(ty: &Type) -> String {
        ty.to_token_stream().to_string().replace(' ', "")
    }

    fn extract_fields(fields: &Fields) -> Vec<FieldInfo> {
        let mut result = Vec::new();
        if let Fields::Named(named) = fields {
            for field in &named.named {
                if let Some(ident) = &field.ident {
                    let name = ident.to_string();
                    let rust_type = Self::type_to_string(&field.ty);
                    let is_nullable = rust_type.starts_with("Option<");
                    let is_primary_key = Self::is_field_primary_key(&field.attrs);
                    result.push(FieldInfo {
                        name,
                        rust_type,
                        is_primary_key,
                        is_nullable,
                    });
                }
            }
        }
        result
    }
}

impl<'ast> Visit<'ast> for ModelVisitor {
    fn visit_item_struct(&mut self, node: &'ast ItemStruct) {
        if Self::has_model_derive(&node.attrs) {
            let name = node.ident.to_string();
            // The struct is typically "Model"; skip unless it's an entity model
            // (DeriveEntityModel is on the "Model" struct inside the entity module)
            if name == "Model" {
                // Capture parent module name from attributes instead
                let table = Self::extract_table_name(&node.attrs);
                let fields = Self::extract_fields(&node.fields);
                self.models.push(ModelInfo {
                    name: name.clone(),
                    module_name: String::new(), // Set later by scan_models
                    table_name: table,
                    fields,
                });
            }
        }
        syn::visit::visit_item_struct(self, node);
    }
}

// ---------------------------------------------------------------------------
// Model scanning
// ---------------------------------------------------------------------------

/// Scan `src/models/` for model files and extract metadata via syn AST parsing.
fn scan_models(project_root: &Path) -> Vec<(String, ModelInfo)> {
    let models_dir = project_root.join("src/models");
    if !models_dir.exists() || !models_dir.is_dir() {
        return Vec::new();
    }

    let mut results = Vec::new();

    for entry in WalkDir::new(&models_dir)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().is_some_and(|ext| ext == "rs"))
    {
        let file_stem = entry
            .path()
            .file_stem()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_default();

        // Skip mod.rs
        if file_stem == "mod" {
            continue;
        }

        let Ok(content) = fs::read_to_string(entry.path()) else {
            continue;
        };
        let Ok(syntax) = syn::parse_file(&content) else {
            continue;
        };

        let mut visitor = ModelVisitor::new();
        visitor.visit_file(&syntax);

        for mut model in visitor.models {
            // Entity files typically use plural table names (users.rs, todos.rs).
            // Singularize to get the model name (User, Todo) and use the singular
            // form as the snake_name key for generated file paths.
            let is_entity_file = entry
                .path()
                .parent()
                .and_then(|p| p.file_name())
                .is_some_and(|dir| dir == "entities");

            let singular_stem = if is_entity_file {
                singularize(&file_stem)
            } else {
                file_stem.clone()
            };

            // module_name is the actual Rust module path under crate::models::
            // For entity files, the re-export module matches the entity file name.
            model.module_name = file_stem.clone();

            let pascal_name = to_pascal_case(&singular_stem);
            model.name = pascal_name.clone();
            // If no table name was extracted, derive from file name
            if model.table_name.is_none() {
                model.table_name = Some(pluralize(&singular_stem));
            }
            results.push((singular_stem.clone(), model));
        }
    }

    results
}

/// Resolve which models to generate API for.
fn resolve_models(
    requested: &[String],
    all: bool,
    available: &[(String, ModelInfo)],
) -> Vec<(String, ModelInfo)> {
    if all {
        return available.to_vec();
    }

    let mut resolved = Vec::new();
    for name in requested {
        let snake = to_snake_case(name);
        let pascal = to_pascal_case(&snake);
        if let Some(found) = available
            .iter()
            .find(|(sn, mi)| *sn == snake || mi.name == pascal || mi.name == *name)
        {
            resolved.push(found.clone());
        } else {
            eprintln!(
                "{} Model '{}' not found in src/models/",
                style("Error:").red().bold(),
                name
            );
            std::process::exit(1);
        }
    }
    resolved
}

// ---------------------------------------------------------------------------
// Per-model code generation
// ---------------------------------------------------------------------------

/// Generate the API controller for a model.
fn generate_controller(snake_name: &str, model: &ModelInfo) {
    let api_dir = Path::new("src/api");
    if !api_dir.exists() {
        fs::create_dir_all(api_dir).expect("Failed to create src/api/ directory");
    }

    let file_path = api_dir.join(format!("{snake_name}_api.rs"));
    if file_path.exists() {
        println!(
            "   {} src/api/{snake_name}_api.rs (already exists)",
            style("skip").yellow()
        );
        return;
    }

    let pascal = &model.name;
    let plural_default = pluralize(snake_name);
    let plural = model.table_name.as_deref().unwrap_or(&plural_default);

    // Build set_field calls for store (non-PK, non-auto fields)
    let store_fields = build_store_fields(&model.fields);
    // Build optional set_field calls for update
    let update_fields = build_update_fields(&model.fields);

    let mod_name = &model.module_name;

    let content = format!(
        r#"//! {pascal} API controller
//!
//! Generated with `ferro make:api`

use ferro::{{handler, Request, Response, HttpResponse}};
use crate::models::{mod_name}::{{self, Entity as {pascal}}};
use sea_orm::{{EntityTrait, PaginatorTrait}};
use crate::resources::{snake_name}_resource::{pascal}Resource;
use crate::requests::{snake_name}_request::{{Create{pascal}Request, Update{pascal}Request}};

/// List {plural} with pagination
///
/// GET /api/v1/{plural}
#[handler]
pub async fn index(req: Request) -> Response {{
    let page: u64 = req.query_as_or("page", 1u64).max(1);
    let per_page: u64 = req.query_as_or("per_page", 15u64).clamp(1, 100);
    let db = ferro::DB::connection()
        .map_err(|e| HttpResponse::json(ferro::serde_json::json!({{"error": e.to_string()}})).status(500))?;
    let paginator = {pascal}::find().paginate(db.inner(), per_page);
    let total = paginator
        .num_items()
        .await
        .map_err(|e| HttpResponse::json(ferro::serde_json::json!({{"error": e.to_string()}})).status(500))?;
    let items = paginator
        .fetch_page(page - 1)
        .await
        .map_err(|e| HttpResponse::json(ferro::serde_json::json!({{"error": e.to_string()}})).status(500))?;
    let resources: Vec<{pascal}Resource> = items.into_iter().map({pascal}Resource::from).collect();
    let meta = ferro::PaginationMeta::new(page, per_page, total);
    Ok(ferro::ResourceCollection::paginated(resources, meta).to_response(&req))
}}

/// Show a single {snake_name}
///
/// GET /api/v1/{plural}/{{id}}
#[handler]
pub async fn show(req: Request, {snake_name}: {mod_name}::Model) -> Response {{
    Ok(ferro::Resource::to_wrapped_response(&{pascal}Resource::from({snake_name}), &req))
}}

/// Create a new {snake_name}
///
/// POST /api/v1/{plural}
#[handler]
pub async fn store(form: Create{pascal}Request) -> Response {{
    let model = {mod_name}::Model::create()
{store_fields}        .insert()
        .await
        .map_err(|e| HttpResponse::json(ferro::serde_json::json!({{"error": e.to_string()}})).status(500))?;
    Ok(HttpResponse::json(ferro::serde_json::json!({{"data": ferro::serde_json::json!({{
        "id": model.id
    }})}})).status(201))
}}

/// Update an existing {snake_name}
///
/// PUT /api/v1/{plural}/{{id}}
#[handler]
pub async fn update({snake_name}: {mod_name}::Model, form: Update{pascal}Request) -> Response {{
    let mut builder = {snake_name}.update();
{update_fields}    let updated = builder
        .save()
        .await
        .map_err(|e| HttpResponse::json(ferro::serde_json::json!({{"error": e.to_string()}})).status(500))?;
    Ok(HttpResponse::json(ferro::serde_json::json!({{"data": ferro::serde_json::json!({{
        "id": updated.id
    }})}})))
}}

/// Delete a {snake_name}
///
/// DELETE /api/v1/{plural}/{{id}}
#[handler]
pub async fn destroy({snake_name}: {mod_name}::Model) -> Response {{
    {snake_name}
        .delete()
        .await
        .map_err(|e| HttpResponse::json(ferro::serde_json::json!({{"error": e.to_string()}})).status(500))?;
    Ok(HttpResponse::json(ferro::serde_json::json!({{"message": "Deleted"}})).status(200))
}}
"#,
    );

    fs::write(&file_path, content).expect("Failed to write API controller file");
    println!(
        "   {} Created src/api/{snake_name}_api.rs",
        style("").green()
    );
}

/// Generate the API resource for a model.
fn generate_resource(snake_name: &str, model: &ModelInfo, exclude: &[String], include_all: bool) {
    let resources_dir = Path::new("src/resources");
    if !resources_dir.exists() {
        fs::create_dir_all(resources_dir).expect("Failed to create src/resources/ directory");
    }

    let file_path = resources_dir.join(format!("{snake_name}_resource.rs"));
    if file_path.exists() {
        println!(
            "   {} src/resources/{snake_name}_resource.rs (already exists)",
            style("skip").yellow()
        );
        return;
    }

    let pascal = &model.name;

    // Filter fields for the resource (excludes sensitive fields)
    let included_fields = filter_resource_fields(&model.fields, exclude, include_all);

    // Report excluded fields
    let excluded_names: Vec<&str> = model
        .fields
        .iter()
        .filter(|f| !included_fields.iter().any(|inc| inc.name == f.name))
        .map(|f| f.name.as_str())
        .collect();
    if !excluded_names.is_empty() {
        println!(
            "   {} Auto-excluded sensitive fields from {}Resource: {}",
            style("").blue(),
            pascal,
            excluded_names.join(", ")
        );
    }

    // Build resource fields and From impl assignments using filtered fields
    let resource_fields = build_resource_fields_filtered(&included_fields);
    let from_assignments = build_from_assignments_filtered(&included_fields);

    let mod_name = &model.module_name;

    let content = format!(
        r#"//! {pascal} API resource
//!
//! Generated with `ferro make:api`

use ferro::{{serde_json, Resource, ResourceMap, Request}};
use crate::models::{mod_name};

/// API representation of {pascal}.
pub struct {pascal}Resource {{
{resource_fields}
}}

impl Resource for {pascal}Resource {{
    fn to_resource(&self, _req: &Request) -> serde_json::Value {{
        let mut map = ResourceMap::new();
{from_assignments}        map.build()
    }}
}}

impl From<{mod_name}::Model> for {pascal}Resource {{
    fn from(model: {mod_name}::Model) -> Self {{
        Self {{
{model_to_resource}        }}
    }}
}}
"#,
        model_to_resource = build_model_to_resource_filtered(&included_fields),
    );

    fs::write(&file_path, content).expect("Failed to write API resource file");
    println!(
        "   {} Created src/resources/{snake_name}_resource.rs",
        style("").green()
    );
}

/// Generate request types for a model.
fn generate_request(snake_name: &str, model: &ModelInfo) {
    let requests_dir = Path::new("src/requests");
    if !requests_dir.exists() {
        fs::create_dir_all(requests_dir).expect("Failed to create src/requests/ directory");
    }

    let file_path = requests_dir.join(format!("{snake_name}_request.rs"));
    if file_path.exists() {
        println!(
            "   {} src/requests/{snake_name}_request.rs (already exists)",
            style("skip").yellow()
        );
        return;
    }

    let pascal = &model.name;

    let create_fields = build_create_request_fields(&model.fields);
    let update_fields = build_update_request_fields(&model.fields);

    let content = format!(
        r#"//! {pascal} API request types
//!
//! Generated with `ferro make:api`

use ferro::{{serde::Deserialize, FormRequest}};

/// Request body for creating a new {pascal}.
#[derive(Deserialize)]
pub struct Create{pascal}Request {{
{create_fields}}}

impl ferro::Validate for Create{pascal}Request {{
    fn validate(&self) -> Result<(), ferro::validator::ValidationErrors> {{
        Ok(())
    }}
}}

impl FormRequest for Create{pascal}Request {{}}

/// Request body for updating an existing {pascal} (all fields optional).
#[derive(Deserialize)]
pub struct Update{pascal}Request {{
{update_fields}}}

impl ferro::Validate for Update{pascal}Request {{
    fn validate(&self) -> Result<(), ferro::validator::ValidationErrors> {{
        Ok(())
    }}
}}

impl FormRequest for Update{pascal}Request {{}}
"#,
    );

    fs::write(&file_path, content).expect("Failed to write API request file");
    println!(
        "   {} Created src/requests/{snake_name}_request.rs",
        style("").green()
    );
}

// ---------------------------------------------------------------------------
// Field mapping helpers
// ---------------------------------------------------------------------------

/// Fields to skip in generated request/store/update code.
fn is_auto_field(field: &FieldInfo) -> bool {
    field.is_primary_key
        || field.name == "created_at"
        || field.name == "updated_at"
        || field.name == "deleted_at"
}

/// Build `.set_field(form.field)` lines for the store handler.
///
/// For nullable model fields, the create request has `Option<T>` while the
/// builder setter expects the inner type. We use `unwrap_or_default()` to
/// provide a sensible default when `None` is passed.
fn build_store_fields(fields: &[FieldInfo]) -> String {
    fields
        .iter()
        .filter(|f| !is_auto_field(f))
        .map(|f| {
            if f.is_nullable {
                format!(
                    "        .set_{name}(form.{name}.clone().unwrap_or_default())\n",
                    name = f.name
                )
            } else {
                format!("        .set_{}(form.{}.clone())\n", f.name, f.name)
            }
        })
        .collect()
}

/// Build conditional set_field lines for the update handler.
fn build_update_fields(fields: &[FieldInfo]) -> String {
    fields
        .iter()
        .filter(|f| !is_auto_field(f))
        .map(|f| {
            format!(
                "    if let Some(ref v) = form.{name} {{ builder = builder.set_{name}(v.clone()); }}\n",
                name = f.name
            )
        })
        .collect()
}

/// Build struct field definitions for the resource (filtered field list).
fn build_resource_fields_filtered(fields: &[&FieldInfo]) -> String {
    fields
        .iter()
        .map(|f| format!("    pub {}: {},", f.name, resource_rust_type(&f.rust_type)))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Build ResourceMap field calls for to_resource (filtered field list).
fn build_from_assignments_filtered(fields: &[&FieldInfo]) -> String {
    fields
        .iter()
        .map(|f| {
            format!(
                "        map = map.field(\"{name}\", serde_json::json!(self.{name}));\n",
                name = f.name
            )
        })
        .collect()
}

/// Build From<Model> field assignments (filtered field list).
fn build_model_to_resource_filtered(fields: &[&FieldInfo]) -> String {
    fields
        .iter()
        .map(|f| format!("            {name}: model.{name}.clone(),\n", name = f.name))
        .collect()
}

/// Build struct field definitions for all fields (unfiltered convenience wrapper).
#[cfg(test)]
fn build_resource_fields(fields: &[FieldInfo]) -> String {
    let refs: Vec<&FieldInfo> = fields.iter().collect();
    build_resource_fields_filtered(&refs)
}

/// Build ResourceMap field calls for all fields (unfiltered convenience wrapper).
#[cfg(test)]
fn build_from_assignments(fields: &[FieldInfo]) -> String {
    let refs: Vec<&FieldInfo> = fields.iter().collect();
    build_from_assignments_filtered(&refs)
}

/// Build From<Model> assignments for all fields (unfiltered convenience wrapper).
#[cfg(test)]
fn build_model_to_resource(fields: &[FieldInfo]) -> String {
    let refs: Vec<&FieldInfo> = fields.iter().collect();
    build_model_to_resource_filtered(&refs)
}

/// Build create request struct fields.
fn build_create_request_fields(fields: &[FieldInfo]) -> String {
    fields
        .iter()
        .filter(|f| !is_auto_field(f))
        .map(|f| {
            let rust_type = request_rust_type(&f.rust_type, f.is_nullable);
            format!("    pub {}: {},\n", f.name, rust_type)
        })
        .collect()
}

/// Build update request struct fields (all optional).
///
/// For model fields that are already `Option<T>`, the update request field is
/// `Option<T>` (not `Option<Option<T>>`). This means `None` = "don't change"
/// and `Some(value)` = "set to value". Explicitly setting a nullable field to
/// NULL requires custom code beyond the generated scaffold.
fn build_update_request_fields(fields: &[FieldInfo]) -> String {
    fields
        .iter()
        .filter(|f| !is_auto_field(f))
        .map(|f| {
            if f.is_nullable {
                // Already Option<T> in the model — keep as Option<T> in update request
                let rust_type = request_rust_type(&f.rust_type, true);
                format!("    pub {}: {},\n", f.name, rust_type)
            } else {
                let inner = request_rust_type(&f.rust_type, false);
                format!("    pub {}: Option<{}>,\n", f.name, inner)
            }
        })
        .collect()
}

/// Map a Rust type from the model to a suitable resource field type.
fn resource_rust_type(rust_type: &str) -> String {
    // Strip Option wrapper if present for display, keep as-is
    rust_type.to_string()
}

/// Map a model's Rust type to a request field type.
fn request_rust_type(rust_type: &str, is_nullable: bool) -> String {
    if is_nullable {
        // Already Option<T>, keep it
        return rust_type.to_string();
    }
    // Map DateTime types to String for request input
    if rust_type.contains("DateTime") || rust_type.contains("DateTimeUtc") {
        return "String".to_string();
    }
    if rust_type.contains("NaiveDate") || rust_type == "Date" {
        return "String".to_string();
    }
    rust_type.to_string()
}

// ---------------------------------------------------------------------------
// String utilities
// ---------------------------------------------------------------------------

fn to_snake_case(name: &str) -> String {
    let mut result = String::new();
    for (i, c) in name.chars().enumerate() {
        if c.is_uppercase() {
            if i > 0 {
                result.push('_');
            }
            result.push(c.to_ascii_lowercase());
        } else {
            result.push(c);
        }
    }
    result
}

fn to_pascal_case(name: &str) -> String {
    name.split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().chain(chars).collect(),
            }
        })
        .collect()
}

fn pluralize(name: &str) -> String {
    if name.ends_with('s') || name.ends_with('x') || name.ends_with("ch") || name.ends_with("sh") {
        format!("{name}es")
    } else if name.ends_with('y')
        && !name.ends_with("ay")
        && !name.ends_with("ey")
        && !name.ends_with("oy")
        && !name.ends_with("uy")
    {
        format!("{}ies", &name[..name.len() - 1])
    } else {
        format!("{name}s")
    }
}

/// Best-effort singularization of a plural English noun.
///
/// Handles common suffixes: -ies -> -y, -ses/-xes/-ches/-shes -> strip -es, -s -> strip.
fn singularize(name: &str) -> String {
    if name.ends_with("ies") && name.len() > 3 {
        // "categories" -> "category"
        format!("{}y", &name[..name.len() - 3])
    } else if name.ends_with("ses")
        || name.ends_with("xes")
        || name.ends_with("ches")
        || name.ends_with("shes")
    {
        // "statuses" -> "status", "boxes" -> "box"
        name[..name.len() - 2].to_string()
    } else if name.ends_with('s') && !name.ends_with("ss") {
        // "users" -> "user", "todos" -> "todo"
        name[..name.len() - 1].to_string()
    } else {
        name.to_string()
    }
}

// ---------------------------------------------------------------------------
/// Read the project name from `./Cargo.toml`, falling back to "my-app".
fn read_app_name() -> String {
    fs::read_to_string("Cargo.toml")
        .ok()
        .and_then(|content| {
            for line in content.lines() {
                let trimmed = line.trim();
                if trimmed.starts_with("name") {
                    if let Some(value) = trimmed.split('=').nth(1) {
                        let name = value.trim().trim_matches('"').trim_matches('\'');
                        if !name.is_empty() {
                            return Some(name.to_string());
                        }
                    }
                }
            }
            None
        })
        .unwrap_or_else(|| "my-app".to_string())
}

// Public entry point (Task 1: model detection + per-model generation only)
// ---------------------------------------------------------------------------

/// Run the `make:api` command.
///
/// Generates API controllers, resources, and request types for the specified
/// models (or all models if `--all` is set).
pub fn run(models: Vec<String>, all: bool, yes: bool, exclude: Vec<String>, include_all: bool) {
    if models.is_empty() && !all {
        eprintln!(
            "{} Specify model names or use --all to scaffold API for all models",
            style("Error:").red().bold()
        );
        eprintln!("  Usage: ferro make:api User Post");
        eprintln!("  Usage: ferro make:api --all");
        std::process::exit(1);
    }

    let project_root = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
    let available = scan_models(&project_root);

    if available.is_empty() {
        eprintln!(
            "{} No models found in src/models/. Create models first with `ferro make:scaffold`.",
            style("Error:").red().bold()
        );
        std::process::exit(1);
    }

    let selected = resolve_models(&models, all, &available);

    if selected.is_empty() {
        eprintln!("{} No matching models found", style("Error:").red().bold());
        std::process::exit(1);
    }

    // Confirmation prompt unless --yes
    if !yes {
        let names: Vec<&str> = selected.iter().map(|(_, m)| m.name.as_str()).collect();
        println!(
            "\n{} Scaffold API for: {}",
            style("?").cyan().bold(),
            names.join(", ")
        );
        let confirmed = dialoguer::Confirm::new()
            .with_prompt("Proceed with generation?")
            .default(true)
            .interact()
            .unwrap_or(false);
        if !confirmed {
            println!("Aborted.");
            return;
        }
    }

    println!(
        "\n{} Generating API scaffold...\n",
        style("").cyan().bold()
    );

    let mut generated_files: Vec<String> = Vec::new();

    for (snake_name, model) in &selected {
        println!("  {} {}", style("Model:").bold(), style(&model.name).cyan());
        generate_controller(snake_name, model);
        generate_resource(snake_name, model, &exclude, include_all);
        generate_request(snake_name, model);
        generated_files.push(format!("src/api/{snake_name}_api.rs"));
        generated_files.push(format!("src/resources/{snake_name}_resource.rs"));
        generated_files.push(format!("src/requests/{snake_name}_request.rs"));
        println!();
    }

    // Generate infrastructure files
    generate_api_mod(&selected);
    generate_api_routes(&selected);
    generate_api_docs();
    generate_resources_mod(&selected);
    generate_requests_mod(&selected);
    generate_api_key_migration();
    generate_api_key_model();
    generate_api_key_provider();

    // Print comprehensive post-scaffold guidance
    let model_names: Vec<&str> = selected.iter().map(|(_, m)| m.name.as_str()).collect();
    let app_name = read_app_name();

    println!();
    println!(
        "  {}",
        style("═══════════════════════════════════════════════").bold()
    );
    println!(
        "  {} {}",
        style("API scaffold complete! Generated for:").bold(),
        style(model_names.join(", ")).cyan().bold()
    );
    println!(
        "  {}",
        style("═══════════════════════════════════════════════").bold()
    );

    println!("\n  Generated files:");
    for (snake_name, _) in &selected {
        println!("    Controllers:  src/api/{snake_name}_api.rs");
        println!("    Resources:    src/resources/{snake_name}_resource.rs");
        println!("    Requests:     src/requests/{snake_name}_request.rs");
    }
    println!("    Routes:       src/api/routes.rs");
    println!("    Docs:         src/api/docs.rs");
    println!("    API Keys:     src/models/api_key.rs, src/providers/api_key_provider.rs");
    println!("    Migration:    src/migrations/m..._create_api_keys_table.rs");

    println!(
        "\n  {}",
        style("───────────────────────────────────────────────").dim()
    );
    println!("  {}", style("Setup Steps").bold());
    println!(
        "  {}",
        style("───────────────────────────────────────────────").dim()
    );

    println!("\n  1. Wire up routes in src/main.rs:");
    println!("       {}", style("mod api;").cyan());
    println!("       // In route registration:");
    println!("       {}", style("api::routes::api_routes()").cyan());
    println!("       {}", style("api::docs::docs_routes()").cyan());
    println!();
    println!("  2. Register the API key provider:");
    println!(
        "       {}",
        style("App::bind::<dyn ApiKeyProvider>(Box::new(ApiKeyProviderImpl::new()));").cyan()
    );
    println!();
    println!("  3. Run the migration:");
    println!("       {}", style("ferro db:migrate").cyan());
    println!();
    println!("  4. Generate an API key:");
    println!("       {}", style(r#"ferro make:api-key "My App""#).cyan());
    println!();
    println!("  5. Verify the API works:");
    println!(
        "       {}",
        style("ferro api:check --api-key fe_live_...").cyan()
    );

    println!(
        "\n  {}",
        style("───────────────────────────────────────────────").dim()
    );
    println!("  {}", style("MCP Integration").bold());
    println!(
        "  {}",
        style("───────────────────────────────────────────────").dim()
    );

    println!("\n  To connect this API to an AI agent via MCP, add to your");
    println!("  MCP host configuration:");

    println!(
        "\n  {} (~/.claude/claude_desktop_config.json):",
        style("Claude Desktop").bold()
    );
    println!("    {{");
    println!("      \"mcpServers\": {{");
    println!("        \"{app_name}-api\": {{");
    println!("          \"command\": \"ferro-api-mcp\",");
    println!("          \"args\": [");
    println!("            \"--spec-url\", \"http://localhost:8080/api/openapi.json\",");
    println!("            \"--api-key\", \"fe_live_...\"");
    println!("          ]");
    println!("        }}");
    println!("      }}");
    println!("    }}");

    println!("\n  {} (~/.claude.json):", style("Claude Code").bold());
    println!("    {{");
    println!("      \"mcpServers\": {{");
    println!("        \"{app_name}-api\": {{");
    println!("          \"command\": \"ferro-api-mcp\",");
    println!("          \"args\": [");
    println!("            \"--spec-url\", \"http://localhost:8080/api/openapi.json\",");
    println!("            \"--api-key\", \"fe_live_...\"");
    println!("          ]");
    println!("        }}");
    println!("      }}");
    println!("    }}");

    println!(
        "\n  Docs: {}",
        style("https://docs.ferro-rs.dev/features/api-mcp.html").underlined()
    );
    println!(
        "  {}",
        style("═══════════════════════════════════════════════").bold()
    );
    println!();
}

// ---------------------------------------------------------------------------
// Infrastructure file generation (called from run)
// ---------------------------------------------------------------------------

/// Generate src/api/mod.rs with module declarations.
fn generate_api_mod(models: &[(String, ModelInfo)]) {
    let api_dir = Path::new("src/api");
    if !api_dir.exists() {
        fs::create_dir_all(api_dir).expect("Failed to create src/api/ directory");
    }

    let mod_path = api_dir.join("mod.rs");
    if mod_path.exists() {
        // Append new model modules if they're not already declared
        let existing = fs::read_to_string(&mod_path).unwrap_or_default();
        let mut additions = String::new();
        for (snake_name, _) in models {
            let decl = format!("pub mod {snake_name}_api;");
            if !existing.contains(&decl) {
                additions.push_str(&decl);
                additions.push('\n');
            }
        }
        // Ensure routes and docs modules are declared
        if !existing.contains("pub mod routes;") {
            additions.push_str("pub mod routes;\n");
        }
        if !existing.contains("pub mod docs;") {
            additions.push_str("pub mod docs;\n");
        }
        if !additions.is_empty() {
            let updated = format!("{existing}{additions}");
            fs::write(&mod_path, updated).expect("Failed to update src/api/mod.rs");
            println!("   {} Updated src/api/mod.rs", style("").green());
        } else {
            println!(
                "   {} src/api/mod.rs (already up-to-date)",
                style("skip").yellow()
            );
        }
    } else {
        let mut content = String::from("// Auto-generated API modules\n");
        for (snake_name, _) in models {
            content.push_str(&format!("pub mod {snake_name}_api;\n"));
        }
        content.push_str("pub mod routes;\n");
        content.push_str("pub mod docs;\n");
        fs::write(&mod_path, content).expect("Failed to write src/api/mod.rs");
        println!("   {} Created src/api/mod.rs", style("").green());
    }
}

/// Generate src/api/routes.rs with route registration.
fn generate_api_routes(models: &[(String, ModelInfo)]) {
    let file_path = Path::new("src/api/routes.rs");
    if file_path.exists() {
        println!(
            "   {} src/api/routes.rs (already exists)",
            style("skip").yellow()
        );
        return;
    }

    let mut route_blocks = String::new();
    for (snake_name, model) in models {
        let plural_default = pluralize(snake_name);
        let plural = model.table_name.as_deref().unwrap_or(&plural_default);
        let pk = model
            .fields
            .iter()
            .find(|f| f.is_primary_key)
            .map(|f| f.name.as_str())
            .unwrap_or("id");

        route_blocks.push_str(&format!(
            r#"
            // {pascal} CRUD
            get!("/{plural}", {snake_name}_api::index).name("api.{plural}.index"),
            post!("/{plural}", {snake_name}_api::store).name("api.{plural}.store"),
            get!("/{plural}/:{pk}", {snake_name}_api::show).name("api.{plural}.show"),
            put!("/{plural}/:{pk}", {snake_name}_api::update).name("api.{plural}.update"),
            delete!("/{plural}/:{pk}", {snake_name}_api::destroy).name("api.{plural}.destroy"),
"#,
            pascal = model.name,
        ));
    }

    let content = format!(
        r#"//! API route registration
//!
//! Generated with `ferro make:api`

use ferro::*;
use crate::api::*;

pub fn api_routes() -> GroupDef {{
    group!("/api/v1", {{{route_blocks}
    }})
        .middleware(ApiKeyMiddleware::new())
        .middleware(Throttle::named("api"))
}}
"#,
    );

    fs::write(file_path, content).expect("Failed to write src/api/routes.rs");
    println!("   {} Created src/api/routes.rs", style("").green());
}

/// Generate src/api/docs.rs with OpenAPI documentation handlers.
fn generate_api_docs() {
    let file_path = Path::new("src/api/docs.rs");
    if file_path.exists() {
        println!(
            "   {} src/api/docs.rs (already exists)",
            style("skip").yellow()
        );
        return;
    }

    let content = r#"//! API documentation routes
//!
//! Generated with `ferro make:api`

use ferro::*;

pub fn docs_routes() -> GroupDef {
    group!("/api", {
        get!("/docs", api_docs).name("api.docs"),
        get!("/openapi.json", openapi_json).name("api.openapi"),
    })
}

#[handler]
pub async fn api_docs() -> Response {
    let config = OpenApiConfig {
        title: ferro::env("APP_NAME", "API".to_string()),
        version: "1.0.0".to_string(),
        description: Some("Auto-generated API documentation".to_string()),
        api_prefix: "/api/".to_string(),
    };
    let routes = get_registered_routes();
    let resp = openapi_docs_response(&config, &routes);
    Ok(resp)
}

#[handler]
pub async fn openapi_json() -> Response {
    let config = OpenApiConfig {
        title: ferro::env("APP_NAME", "API".to_string()),
        version: "1.0.0".to_string(),
        description: Some("Auto-generated API documentation".to_string()),
        api_prefix: "/api/".to_string(),
    };
    let routes = get_registered_routes();
    let resp = openapi_json_response(&config, &routes);
    Ok(resp)
}
"#;

    fs::write(file_path, content).expect("Failed to write src/api/docs.rs");
    println!("   {} Created src/api/docs.rs", style("").green());
}

/// Create or update src/resources/mod.rs to include generated resource modules.
fn generate_resources_mod(models: &[(String, ModelInfo)]) {
    let resources_dir = Path::new("src/resources");
    if !resources_dir.exists() {
        return;
    }

    let mod_path = resources_dir.join("mod.rs");
    if mod_path.exists() {
        let existing = fs::read_to_string(&mod_path).unwrap_or_default();
        let mut additions = String::new();
        for (snake_name, _) in models {
            let decl = format!("pub mod {snake_name}_resource;");
            if !existing.contains(&decl) {
                additions.push_str(&decl);
                additions.push('\n');
            }
        }
        if !additions.is_empty() {
            let updated = format!("{existing}{additions}");
            fs::write(&mod_path, updated).expect("Failed to update src/resources/mod.rs");
            println!("   {} Updated src/resources/mod.rs", style("").green());
        }
    } else {
        let mut content = String::new();
        for (snake_name, _) in models {
            content.push_str(&format!("pub mod {snake_name}_resource;\n"));
        }
        fs::write(&mod_path, content).expect("Failed to write src/resources/mod.rs");
        println!("   {} Created src/resources/mod.rs", style("").green());
    }
}

/// Create or update src/requests/mod.rs to include generated request modules.
fn generate_requests_mod(models: &[(String, ModelInfo)]) {
    let requests_dir = Path::new("src/requests");
    if !requests_dir.exists() {
        fs::create_dir_all(requests_dir).expect("Failed to create src/requests/ directory");
    }

    let mod_path = requests_dir.join("mod.rs");
    if mod_path.exists() {
        let existing = fs::read_to_string(&mod_path).unwrap_or_default();
        let mut additions = String::new();
        for (snake_name, _) in models {
            let decl = format!("pub mod {snake_name}_request;");
            if !existing.contains(&decl) {
                additions.push_str(&decl);
                additions.push('\n');
            }
        }
        if !additions.is_empty() {
            let updated = format!("{existing}{additions}");
            fs::write(&mod_path, updated).expect("Failed to update src/requests/mod.rs");
            println!("   {} Updated src/requests/mod.rs", style("").green());
        }
    } else {
        let mut content = String::new();
        for (snake_name, _) in models {
            content.push_str(&format!("pub mod {snake_name}_request;\n"));
        }
        fs::write(&mod_path, content).expect("Failed to write src/requests/mod.rs");
        println!("   {} Created src/requests/mod.rs", style("").green());
    }
}

/// Generate the API keys migration.
fn generate_api_key_migration() {
    let migrations_dir = if Path::new("src/migrations").exists() {
        Path::new("src/migrations")
    } else if Path::new("src/database/migrations").exists() {
        Path::new("src/database/migrations")
    } else {
        println!(
            "   {} migrations directory not found, skipping migration generation",
            style("warn").yellow()
        );
        return;
    };

    // Check if migration already exists
    if let Ok(entries) = fs::read_dir(migrations_dir) {
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().to_string();
            if name.contains("create_api_keys_table") {
                println!(
                    "   {} API keys migration (already exists)",
                    style("skip").yellow()
                );
                return;
            }
        }
    }

    let timestamp = chrono::Utc::now().format("%Y%m%d%H%M%S").to_string();
    let migration_name = format!("m{timestamp}_create_api_keys_table");
    let file_name = format!("{migration_name}.rs");
    let file_path = migrations_dir.join(&file_name);

    let content = r#"use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(ApiKeys::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(ApiKeys::Id)
                            .big_integer()
                            .not_null()
                            .auto_increment()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(ApiKeys::Name).string().not_null())
                    .col(ColumnDef::new(ApiKeys::Prefix).string_len(16).not_null())
                    .col(ColumnDef::new(ApiKeys::HashedKey).string_len(64).not_null())
                    .col(ColumnDef::new(ApiKeys::Scopes).text().null())
                    .col(ColumnDef::new(ApiKeys::LastUsedAt).timestamp_with_time_zone().null())
                    .col(ColumnDef::new(ApiKeys::ExpiresAt).timestamp_with_time_zone().null())
                    .col(ColumnDef::new(ApiKeys::RevokedAt).timestamp_with_time_zone().null())
                    .col(
                        ColumnDef::new(ApiKeys::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_api_keys_prefix")
                    .table(ApiKeys::Table)
                    .col(ApiKeys::Prefix)
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(ApiKeys::Table).to_owned())
            .await
    }
}

#[derive(Iden)]
pub enum ApiKeys {
    Table,
    Id,
    Name,
    Prefix,
    HashedKey,
    Scopes,
    LastUsedAt,
    ExpiresAt,
    RevokedAt,
    CreatedAt,
}
"#
    .to_string();

    fs::write(&file_path, content).expect("Failed to write migration file");

    // Update migrations mod.rs
    update_migrations_mod(&migration_name);

    println!(
        "   {} Created {}/{}",
        style("").green(),
        migrations_dir.display(),
        file_name
    );
}

/// Update the migrations mod.rs to include the new migration.
fn update_migrations_mod(migration_name: &str) {
    let mod_path = if Path::new("src/migrations/mod.rs").exists() {
        Path::new("src/migrations/mod.rs")
    } else if Path::new("src/database/migrations/mod.rs").exists() {
        Path::new("src/database/migrations/mod.rs")
    } else {
        return;
    };

    let content = fs::read_to_string(mod_path).unwrap_or_default();
    let mod_declaration = format!("pub mod {migration_name};");
    if content.contains(&mod_declaration) {
        return;
    }

    // Find where to insert (after existing pub mod m* lines)
    let mut lines: Vec<String> = content.lines().map(String::from).collect();
    let mut insert_index = 0;
    for (i, line) in lines.iter().enumerate() {
        if line.starts_with("pub mod m") {
            insert_index = i + 1;
        }
    }
    lines.insert(insert_index, mod_declaration.clone());

    // Add to Migrator vec
    let migrator_addition = format!("            Box::new({migration_name}::Migration),");
    let mut result = lines.join("\n");

    if result.contains("vec![]") {
        result = result.replace("vec![]", &format!("vec![\n{migrator_addition}\n        ]"));
    } else if result.contains("vec![") {
        let mut final_result = String::new();
        let mut in_migrations = false;
        let mut bracket_depth = 0;

        for line in result.lines() {
            if line.contains("fn migrations()") {
                in_migrations = true;
            }
            if in_migrations {
                if line.contains("vec![") {
                    bracket_depth += 1;
                }
                if line.trim() == "]" && bracket_depth == 1 {
                    final_result.push_str(&migrator_addition);
                    final_result.push('\n');
                    bracket_depth = 0;
                    in_migrations = false;
                }
            }
            final_result.push_str(line);
            final_result.push('\n');
        }
        result = final_result;
    }

    fs::write(mod_path, result).expect("Failed to update migrations mod.rs");
}

/// Generate src/models/api_key.rs.
fn generate_api_key_model() {
    let models_dir = Path::new("src/models");
    if !models_dir.exists() {
        fs::create_dir_all(models_dir).expect("Failed to create src/models/ directory");
    }

    let file_path = models_dir.join("api_key.rs");
    if file_path.exists() {
        println!(
            "   {} src/models/api_key.rs (already exists)",
            style("skip").yellow()
        );
        return;
    }

    let content = r#"//! API key model

use ferro::database::{Model as DatabaseModel, ModelMut, QueryBuilder};
use ferro::serde::Serialize;
use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize)]
#[sea_orm(table_name = "api_keys")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    pub name: String,
    pub prefix: String,
    pub hashed_key: String,
    pub scopes: Option<String>,
    pub last_used_at: Option<DateTimeUtc>,
    pub expires_at: Option<DateTimeUtc>,
    pub revoked_at: Option<DateTimeUtc>,
    pub created_at: DateTimeUtc,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}

impl DatabaseModel for Entity {}
impl ModelMut for Entity {}

pub type ApiKey = Model;

impl Model {
    pub fn query() -> QueryBuilder<Entity> {
        QueryBuilder::new()
    }
}
"#;

    fs::write(&file_path, content).expect("Failed to write API key model file");

    // Update models mod.rs
    let mod_path = models_dir.join("mod.rs");
    if mod_path.exists() {
        let existing = fs::read_to_string(&mod_path).unwrap_or_default();
        if !existing.contains("pub mod api_key;") {
            let updated = format!("{existing}pub mod api_key;\n");
            fs::write(&mod_path, updated).expect("Failed to update models mod.rs");
        }
    }

    println!("   {} Created src/models/api_key.rs", style("").green());
}

/// Generate src/providers/api_key_provider.rs.
fn generate_api_key_provider() {
    let providers_dir = Path::new("src/providers");
    if !providers_dir.exists() {
        fs::create_dir_all(providers_dir).expect("Failed to create src/providers/ directory");
    }

    let file_path = providers_dir.join("api_key_provider.rs");
    if file_path.exists() {
        println!(
            "   {} src/providers/api_key_provider.rs (already exists)",
            style("skip").yellow()
        );
        return;
    }

    let content = r#"//! API key provider implementation
//!
//! Generated with `ferro make:api`

use ferro::{async_trait, serde_json, ApiKeyInfo, ApiKeyProvider, verify_api_key_hash};
use crate::models::api_key::{self, Entity as ApiKey};
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};

/// Database-backed API key provider.
///
/// Register this as a service in your bootstrap:
/// ```rust,ignore
/// App::bind::<dyn ApiKeyProvider>(Box::new(ApiKeyProviderImpl));
/// ```
pub struct ApiKeyProviderImpl;

#[async_trait]
impl ApiKeyProvider for ApiKeyProviderImpl {
    async fn verify_key(&self, raw_key: &str) -> Result<ApiKeyInfo, ()> {
        let prefix = &raw_key[..16.min(raw_key.len())];

        let db = ferro::DB::connection().map_err(|_| ())?;
        let record = ApiKey::find()
            .filter(api_key::Column::Prefix.eq(prefix))
            .one(db.inner())
            .await
            .map_err(|_| ())?
            .ok_or(())?;

        // Check revocation
        if record.revoked_at.is_some() {
            return Err(());
        }

        // Check expiry
        if let Some(expires_at) = record.expires_at {
            if expires_at < chrono::Utc::now() {
                return Err(());
            }
        }

        // Constant-time hash verification
        if !verify_api_key_hash(raw_key, &record.hashed_key) {
            return Err(());
        }

        let scopes: Vec<String> = record
            .scopes
            .as_deref()
            .and_then(|s| serde_json::from_str(s).ok())
            .unwrap_or_default();

        Ok(ApiKeyInfo {
            id: record.id,
            name: record.name,
            scopes,
        })
    }
}
"#;

    fs::write(&file_path, content).expect("Failed to write API key provider file");
    println!(
        "   {} Created src/providers/api_key_provider.rs",
        style("").green()
    );
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a realistic test model with mixed field types.
    fn test_model() -> ModelInfo {
        ModelInfo {
            name: "User".to_string(),
            module_name: "users".to_string(),
            table_name: Some("users".to_string()),
            fields: vec![
                FieldInfo {
                    name: "id".to_string(),
                    rust_type: "i32".to_string(),
                    is_primary_key: true,
                    is_nullable: false,
                },
                FieldInfo {
                    name: "name".to_string(),
                    rust_type: "String".to_string(),
                    is_primary_key: false,
                    is_nullable: false,
                },
                FieldInfo {
                    name: "email".to_string(),
                    rust_type: "String".to_string(),
                    is_primary_key: false,
                    is_nullable: false,
                },
                FieldInfo {
                    name: "bio".to_string(),
                    rust_type: "Option<String>".to_string(),
                    is_primary_key: false,
                    is_nullable: true,
                },
                FieldInfo {
                    name: "is_active".to_string(),
                    rust_type: "bool".to_string(),
                    is_primary_key: false,
                    is_nullable: false,
                },
                FieldInfo {
                    name: "created_at".to_string(),
                    rust_type: "String".to_string(),
                    is_primary_key: false,
                    is_nullable: false,
                },
                FieldInfo {
                    name: "updated_at".to_string(),
                    rust_type: "String".to_string(),
                    is_primary_key: false,
                    is_nullable: false,
                },
            ],
        }
    }

    // -----------------------------------------------------------------------
    // String utility tests
    // -----------------------------------------------------------------------

    #[test]
    fn singularize_regular_s() {
        assert_eq!(singularize("users"), "user");
        assert_eq!(singularize("todos"), "todo");
        assert_eq!(singularize("posts"), "post");
    }

    #[test]
    fn singularize_ies() {
        assert_eq!(singularize("categories"), "category");
        assert_eq!(singularize("companies"), "company");
    }

    #[test]
    fn singularize_ses_xes() {
        assert_eq!(singularize("statuses"), "status");
        assert_eq!(singularize("boxes"), "box");
    }

    #[test]
    fn singularize_ches_shes() {
        assert_eq!(singularize("matches"), "match");
        assert_eq!(singularize("dishes"), "dish");
    }

    #[test]
    fn singularize_already_singular() {
        assert_eq!(singularize("user"), "user");
        assert_eq!(singularize("address"), "address"); // ends with ss
    }

    #[test]
    fn pluralize_basic() {
        assert_eq!(pluralize("user"), "users");
        assert_eq!(pluralize("todo"), "todos");
    }

    #[test]
    fn pluralize_special_endings() {
        assert_eq!(pluralize("status"), "statuses");
        assert_eq!(pluralize("box"), "boxes");
        assert_eq!(pluralize("category"), "categories");
    }

    #[test]
    fn to_pascal_case_basic() {
        assert_eq!(to_pascal_case("user"), "User");
        assert_eq!(to_pascal_case("api_key"), "ApiKey");
        assert_eq!(to_pascal_case("blog_post"), "BlogPost");
    }

    #[test]
    fn to_snake_case_basic() {
        assert_eq!(to_snake_case("User"), "user");
        assert_eq!(to_snake_case("ApiKey"), "api_key");
        assert_eq!(to_snake_case("BlogPost"), "blog_post");
    }

    // -----------------------------------------------------------------------
    // Auto field detection
    // -----------------------------------------------------------------------

    #[test]
    fn auto_field_detects_primary_key() {
        let field = FieldInfo {
            name: "id".to_string(),
            rust_type: "i32".to_string(),
            is_primary_key: true,
            is_nullable: false,
        };
        assert!(is_auto_field(&field));
    }

    #[test]
    fn auto_field_detects_timestamps() {
        for name in ["created_at", "updated_at", "deleted_at"] {
            let field = FieldInfo {
                name: name.to_string(),
                rust_type: "String".to_string(),
                is_primary_key: false,
                is_nullable: false,
            };
            assert!(is_auto_field(&field), "{name} should be auto-field");
        }
    }

    #[test]
    fn auto_field_skips_regular_fields() {
        let field = FieldInfo {
            name: "email".to_string(),
            rust_type: "String".to_string(),
            is_primary_key: false,
            is_nullable: false,
        };
        assert!(!is_auto_field(&field));
    }

    // -----------------------------------------------------------------------
    // Controller template tests
    // -----------------------------------------------------------------------

    #[test]
    fn controller_uses_sync_db_connection() {
        // The controller template contains the DB::connection() call pattern.
        // Verify it never uses .await (DB::connection is sync).
        let template = "ferro::DB::connection()\n        .map_err";
        assert!(
            !template.contains("connection().await"),
            "DB::connection() must not use .await (sync call)"
        );
    }

    #[test]
    fn controller_store_fields_skip_auto() {
        let model = test_model();
        let store = build_store_fields(&model.fields);
        assert!(!store.contains("set_id("), "PK should be skipped");
        assert!(
            !store.contains("set_created_at("),
            "created_at should be skipped"
        );
        assert!(
            !store.contains("set_updated_at("),
            "updated_at should be skipped"
        );
        assert!(store.contains("set_name(form.name.clone())"));
        assert!(store.contains("set_email(form.email.clone())"));
        assert!(store.contains("set_is_active(form.is_active.clone())"));
    }

    #[test]
    fn controller_store_handles_nullable() {
        let model = test_model();
        let store = build_store_fields(&model.fields);
        assert!(
            store.contains("set_bio(form.bio.clone().unwrap_or_default())"),
            "nullable field should use unwrap_or_default"
        );
    }

    #[test]
    fn controller_update_fields_use_conditional_set() {
        let model = test_model();
        let update = build_update_fields(&model.fields);
        assert!(update.contains("if let Some(ref v) = form.name"));
        assert!(update.contains("builder = builder.set_name(v.clone())"));
        assert!(
            !update.contains("set_id("),
            "PK should be skipped in update"
        );
    }

    #[test]
    fn controller_update_fields_skip_timestamps() {
        let model = test_model();
        let update = build_update_fields(&model.fields);
        assert!(!update.contains("set_created_at("));
        assert!(!update.contains("set_updated_at("));
    }

    // -----------------------------------------------------------------------
    // Resource template tests
    // -----------------------------------------------------------------------

    #[test]
    fn resource_fields_include_all_fields() {
        let model = test_model();
        let fields = build_resource_fields(&model.fields);
        assert!(fields.contains("pub id: i32"));
        assert!(fields.contains("pub name: String"));
        assert!(fields.contains("pub bio: Option<String>"));
        assert!(fields.contains("pub created_at: String"));
    }

    #[test]
    fn resource_from_assignments_all_fields() {
        let model = test_model();
        let assignments = build_from_assignments(&model.fields);
        assert!(assignments.contains("map.field(\"id\""));
        assert!(assignments.contains("map.field(\"name\""));
        assert!(assignments.contains("map.field(\"bio\""));
    }

    #[test]
    fn resource_model_to_resource_clones_all() {
        let model = test_model();
        let assigns = build_model_to_resource(&model.fields);
        assert!(assigns.contains("id: model.id.clone()"));
        assert!(assigns.contains("email: model.email.clone()"));
        assert!(assigns.contains("bio: model.bio.clone()"));
    }

    // -----------------------------------------------------------------------
    // Request template tests
    // -----------------------------------------------------------------------

    #[test]
    fn create_request_skips_auto_fields() {
        let model = test_model();
        let fields = build_create_request_fields(&model.fields);
        assert!(!fields.contains("pub id:"));
        assert!(!fields.contains("pub created_at:"));
        assert!(!fields.contains("pub updated_at:"));
        assert!(fields.contains("pub name: String"));
        assert!(fields.contains("pub email: String"));
    }

    #[test]
    fn create_request_preserves_nullable() {
        let model = test_model();
        let fields = build_create_request_fields(&model.fields);
        assert!(fields.contains("pub bio: Option<String>"));
    }

    #[test]
    fn update_request_wraps_in_option() {
        let model = test_model();
        let fields = build_update_request_fields(&model.fields);
        assert!(fields.contains("pub name: Option<String>"));
        assert!(fields.contains("pub email: Option<String>"));
        assert!(fields.contains("pub is_active: Option<bool>"));
    }

    #[test]
    fn update_request_no_double_option() {
        let model = test_model();
        let fields = build_update_request_fields(&model.fields);
        // bio is already Option<String> — should stay Option<String>, not Option<Option<String>>
        assert!(fields.contains("pub bio: Option<String>"));
        assert!(
            !fields.contains("Option<Option<"),
            "nullable fields should not be double-wrapped"
        );
    }

    // -----------------------------------------------------------------------
    // Regression: known bad patterns must be absent
    // -----------------------------------------------------------------------

    #[test]
    fn no_connection_await_in_store_fields() {
        let model = test_model();
        let store = build_store_fields(&model.fields);
        assert!(!store.contains("connection().await"));
    }

    #[test]
    fn no_serde_json_value_vec() {
        // The controller template should use Vec<{Resource}>, not Vec<serde_json::Value>.
        // We verify by checking that the known template format string uses the typed vec.
        let template_fragment = "Vec<{pascal}Resource>";
        assert!(!template_fragment.contains("Vec<serde_json::Value>"));
    }

    // -----------------------------------------------------------------------
    // Model resolution and name derivation
    // -----------------------------------------------------------------------

    #[test]
    fn resolve_models_by_singular_name() {
        let available = vec![(
            "user".to_string(),
            ModelInfo {
                name: "User".to_string(),
                module_name: "users".to_string(),
                table_name: Some("users".to_string()),
                fields: vec![],
            },
        )];
        let result = resolve_models(&["User".to_string()], false, &available);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].1.name, "User");
    }

    #[test]
    fn resolve_models_by_snake_case() {
        let available = vec![(
            "blog_post".to_string(),
            ModelInfo {
                name: "BlogPost".to_string(),
                module_name: "blog_posts".to_string(),
                table_name: Some("blog_posts".to_string()),
                fields: vec![],
            },
        )];
        let result = resolve_models(&["blog_post".to_string()], false, &available);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].1.name, "BlogPost");
    }

    #[test]
    fn resolve_models_all_flag() {
        let available = vec![
            (
                "user".to_string(),
                ModelInfo {
                    name: "User".to_string(),
                    module_name: "users".to_string(),
                    table_name: Some("users".to_string()),
                    fields: vec![],
                },
            ),
            (
                "todo".to_string(),
                ModelInfo {
                    name: "Todo".to_string(),
                    module_name: "todos".to_string(),
                    table_name: Some("todos".to_string()),
                    fields: vec![],
                },
            ),
        ];
        let result = resolve_models(&[], true, &available);
        assert_eq!(result.len(), 2);
    }

    // -----------------------------------------------------------------------
    // Type mapping
    // -----------------------------------------------------------------------

    #[test]
    fn request_rust_type_datetime_becomes_string() {
        assert_eq!(request_rust_type("DateTime", false), "String");
        assert_eq!(request_rust_type("DateTimeUtc", false), "String");
        assert_eq!(request_rust_type("NaiveDate", false), "String");
    }

    #[test]
    fn request_rust_type_nullable_passthrough() {
        assert_eq!(request_rust_type("Option<String>", true), "Option<String>");
    }

    #[test]
    fn request_rust_type_regular_passthrough() {
        assert_eq!(request_rust_type("String", false), "String");
        assert_eq!(request_rust_type("i32", false), "i32");
        assert_eq!(request_rust_type("bool", false), "bool");
    }

    // -----------------------------------------------------------------------
    // filter_resource_fields tests
    // -----------------------------------------------------------------------

    fn make_field(name: &str) -> FieldInfo {
        FieldInfo {
            name: name.to_string(),
            rust_type: "String".to_string(),
            is_primary_key: false,
            is_nullable: false,
        }
    }

    #[test]
    fn filter_excludes_password_hash_by_default() {
        let fields = vec![
            make_field("id"),
            make_field("email"),
            make_field("password_hash"),
        ];
        let result = filter_resource_fields(&fields, &[], false);
        let names: Vec<&str> = result.iter().map(|f| f.name.as_str()).collect();
        assert!(names.contains(&"id"));
        assert!(names.contains(&"email"));
        assert!(!names.contains(&"password_hash"));
    }

    #[test]
    fn filter_keeps_non_sensitive_fields() {
        let fields = vec![
            make_field("id"),
            make_field("email"),
            make_field("name"),
            make_field("created_at"),
        ];
        let result = filter_resource_fields(&fields, &[], false);
        assert_eq!(result.len(), 4);
    }

    #[test]
    fn filter_custom_exclude_removes_field() {
        let fields = vec![make_field("id"), make_field("email"), make_field("name")];
        let exclude = vec!["email".to_string()];
        let result = filter_resource_fields(&fields, &exclude, false);
        let names: Vec<&str> = result.iter().map(|f| f.name.as_str()).collect();
        assert!(!names.contains(&"email"));
        assert!(names.contains(&"id"));
        assert!(names.contains(&"name"));
    }

    #[test]
    fn filter_include_all_keeps_sensitive_fields() {
        let fields = vec![
            make_field("id"),
            make_field("password_hash"),
            make_field("hashed_key"),
            make_field("secret"),
        ];
        let result = filter_resource_fields(&fields, &[], true);
        assert_eq!(result.len(), 4);
    }

    #[test]
    fn filter_case_insensitive_matching() {
        let fields = vec![
            make_field("Password_Hash"),
            make_field("SECRET"),
            make_field("email"),
        ];
        let result = filter_resource_fields(&fields, &[], false);
        let names: Vec<&str> = result.iter().map(|f| f.name.as_str()).collect();
        assert!(!names.contains(&"Password_Hash"));
        assert!(!names.contains(&"SECRET"));
        assert!(names.contains(&"email"));
    }

    #[test]
    fn filter_exact_match_only() {
        // "token" should exclude "token" but NOT "created_at" or "token_time"
        let fields = vec![
            make_field("token"),
            make_field("created_at"),
            make_field("token_time"),
        ];
        let result = filter_resource_fields(&fields, &[], false);
        let names: Vec<&str> = result.iter().map(|f| f.name.as_str()).collect();
        assert!(
            !names.contains(&"token"),
            "exact match 'token' should be excluded"
        );
        assert!(
            names.contains(&"created_at"),
            "unrelated field should remain"
        );
        assert!(
            names.contains(&"token_time"),
            "substring match should NOT be excluded"
        );
    }

    #[test]
    fn filter_include_all_still_respects_custom_exclude() {
        // --include-all disables auto-exclusion but --exclude still works
        let fields = vec![
            make_field("password_hash"),
            make_field("email"),
            make_field("name"),
        ];
        let exclude = vec!["email".to_string()];
        let result = filter_resource_fields(&fields, &exclude, true);
        let names: Vec<&str> = result.iter().map(|f| f.name.as_str()).collect();
        assert!(
            names.contains(&"password_hash"),
            "include_all keeps sensitive fields"
        );
        assert!(!names.contains(&"email"), "custom exclude still works");
        assert!(names.contains(&"name"));
    }

    #[test]
    fn filter_all_sensitive_patterns_excluded() {
        let fields: Vec<FieldInfo> = SENSITIVE_FIELD_PATTERNS
            .iter()
            .map(|p| make_field(p))
            .collect();
        let result = filter_resource_fields(&fields, &[], false);
        assert!(
            result.is_empty(),
            "all sensitive patterns should be excluded, got: {:?}",
            result.iter().map(|f| &f.name).collect::<Vec<_>>()
        );
    }
}