autumn-cli 0.9.0

CLI tool for the Autumn web framework
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
//! TOML-based generator configuration for `autumn generate scaffold`.
//!
//! Reads `[scaffold.ResourceName]` sections from a project-local TOML file
//! so scaffold metadata can be checked in and reproduced without long CLI
//! invocations.
//!
//! # File format
//!
//! ```toml
//! [scaffold.Bookmark]
//! fields      = ["url:String", "title:String", "tag:String", "alive:bool"]
//! indexes     = ["url", "tag"]
//! validations = ["url=url", "title=length:min=1,max=200"]
//! defaults    = ["alive=true"]
//! queries     = ["find_by_tag:tag", "find_by_alive:alive"]
//! ```
//!
//! # Precedence
//!
//! CLI flags win. If the caller passes any values for a repeated flag (e.g.
//! `--index`), those values completely replace the corresponding TOML list.
//! Fields (positional arguments) follow the same rule: non-empty CLI fields
//! shadow TOML fields.

/// The conventional config file name that `autumn generate` auto-discovers in
/// the project root. Also used as the default path for `--config`.
pub const GENERATE_CONFIG_FILENAME: &str = "autumn.generate.toml";

use std::collections::HashMap;
use std::path::Path;

use serde::Deserialize;

use super::GenerateError;
use super::dsl::IdType;
use super::model::ModelOptions;
use super::naming::pascal;
use super::scaffold::ScaffoldOptions;

/// One resource's scaffold metadata from a TOML config file.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[allow(clippy::struct_excessive_bools)]
pub struct ScaffoldConfigEntry {
    #[serde(default)]
    pub fields: Vec<String>,
    #[serde(default)]
    pub indexes: Vec<String>,
    #[serde(default)]
    pub uniques: Vec<String>,
    #[serde(default)]
    pub validations: Vec<String>,
    #[serde(default)]
    pub defaults: Vec<String>,
    #[serde(default)]
    pub queries: Vec<String>,
    #[serde(default)]
    pub soft_delete: bool,
    #[serde(default)]
    pub api: bool,
    #[serde(default)]
    pub sharded: bool,
    #[serde(default)]
    pub shard_key: Option<String>,
    #[serde(default)]
    pub live: bool,
    /// Primary-key type for this resource (`"uuid"` or `"bigint"`).
    /// Inherits from `[generate] id` when absent.
    #[serde(default)]
    pub id: Option<String>,
    /// Emit per-field inline validation endpoints and `hx-post` attributes on
    /// form inputs.
    #[serde(default)]
    pub live_validation: bool,
    /// Opt out of generating a record-level authorization `Policy`/`Scope`
    /// (issue #1125).
    #[serde(default)]
    pub no_policy: bool,
    /// Bind this resource to a parent as its child (issue #1323) — the
    /// TOML equivalent of `--belongs-to Post`.
    #[serde(default)]
    pub belongs_to: Option<String>,
    /// Maintain a `{child}_count` column on the parent (issue #1325).
    #[serde(default)]
    pub counter_cache: Option<bool>,
    /// Text field names to make full-text searchable (issue #1319): emits
    /// `#[searchable]` on the model, `searchable` on the repository, the
    /// `search_vector` migration, and a wired search box in the index view.
    #[serde(default)]
    pub searchable: Vec<String>,
    /// Emit i18n-ready views (issue #1349) — the TOML equivalent of `--i18n`.
    #[serde(default)]
    pub i18n: bool,
    /// Emit the CSV import surface (issue #1393) — the TOML equivalent of
    /// `--import`.
    #[serde(default)]
    pub import: bool,
}

/// Project-level generator defaults, read from `[generate]` in the config file.
///
/// `deny_unknown_fields` so a typo inside `[generate]` (e.g. `ide = "uuid"` or
/// `id_type = "uuid"`) is a hard error rather than being silently ignored and
/// falling back to the default key type. This applies to both the strict
/// `--config` path and the lenient defaults-only reads (which validate the
/// `[generate]` table even while ignoring `[scaffold.*]` sections).
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct GenerateDefaults {
    /// Default primary-key type (`"uuid"` or `"bigint"`).
    #[serde(default)]
    id: Option<String>,
}

// `deny_unknown_fields` so a mistyped top-level table (e.g. `[scafold.Post]`
// instead of `[scaffold.Post]`, or `[genrate]`) is a hard error when the file is
// used as an explicit `--config` scaffold source, rather than being silently
// ignored and producing a fieldless resource. Defaults-only reads use the
// lenient `GenerateDefaultsConfig` view instead.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct GeneratorConfig {
    #[serde(default)]
    scaffold: HashMap<String, ScaffoldConfigEntry>,
    #[serde(default)]
    generate: GenerateDefaults,
}

/// A defaults-only view of the config file. Reads the `[generate]` table and
/// ignores the *contents* of `[scaffold.*]` sections, so a defaults-only read
/// (e.g. `generate model`, or auto-discovered scaffold) does not fail on an
/// unrelated per-resource recipe that has a typo or an unsupported key — those
/// are only validated when the recipe is actually used via `--config`.
///
/// `deny_unknown_fields` still rejects *other* mistyped top-level tables/keys
/// (e.g. `[genrate]` or a stray top-level `id`) so a project-default typo is a
/// hard error rather than being silently dropped (which would fall back to the
/// default key type). The `scaffold` field is declared only so those recipe
/// tables are accepted-but-unvalidated; its contents are intentionally unused.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct GenerateDefaultsConfig {
    #[serde(default)]
    generate: GenerateDefaults,
    #[serde(default)]
    #[allow(dead_code)]
    scaffold: HashMap<String, toml::Value>,
}

/// Read and parse the whole generator config file at `config_path`.
///
/// # Errors
///
/// - [`GenerateError::Io`] if the file cannot be read.
/// - [`GenerateError::Config`] if the file is not valid TOML.
fn parse_config(config_path: &Path) -> Result<GeneratorConfig, GenerateError> {
    let content = std::fs::read_to_string(config_path)
        .map_err(|e| std::io::Error::new(e.kind(), format!("{}: {e}", config_path.display())))?;
    toml::from_str(&content).map_err(|e| {
        GenerateError::Config(format!("invalid TOML in {}: {e}", config_path.display()))
    })
}

/// Read the scaffold config entry for `resource_name` from `config_path`.
///
/// Returns `None` when the file is valid TOML but has no
/// `[scaffold.ResourceName]` section for the requested name.
///
/// The `[generate] id` project default is propagated into the returned entry's
/// `id` field so that callers do not need to handle the two-level default
/// separately.
///
/// # Errors
///
/// - [`GenerateError::Io`] if the file cannot be read.
/// - [`GenerateError::Config`] if the file is not valid TOML.
pub fn read_scaffold_config(
    config_path: &Path,
    resource_name: &str,
) -> Result<Option<ScaffoldConfigEntry>, GenerateError> {
    let mut config = parse_config(config_path)?;
    // Normalize to PascalCase so `bookmark` and `Bookmark` both match
    // `[scaffold.Bookmark]`, consistent with how the generator itself handles
    // resource names passed on the CLI.
    let mut entry = config.scaffold.remove(&pascal(resource_name));
    // Propagate [generate] id default when the per-resource section doesn't override it.
    if let Some(e) = entry.as_mut()
        && e.id.is_none()
    {
        e.id = config.generate.id;
    }
    Ok(entry)
}

/// Read ONLY the project-level `[generate]` defaults from `config_path` into a
/// scaffold entry, ignoring any per-resource `[scaffold.*]` sections.
///
/// Used for an **auto-discovered** `autumn.generate.toml` (no explicit
/// `--config`): a checked-in `[scaffold.Post]` recipe must NOT silently apply
/// to an ordinary `autumn generate scaffold Post …` invocation. Only the
/// project-wide defaults (the `id` type) are contributed; the per-resource
/// recipe is honoured solely when the user opts in with `--config`.
///
/// # Errors
///
/// - [`GenerateError::Io`] if the file cannot be read.
/// - [`GenerateError::Config`] if the file is not valid TOML.
pub fn read_generate_defaults_entry(
    config_path: &Path,
) -> Result<ScaffoldConfigEntry, GenerateError> {
    Ok(ScaffoldConfigEntry {
        id: read_generate_id(config_path)?,
        ..ScaffoldConfigEntry::default()
    })
}

/// Resolve a scaffold entry from an **explicit** `--config <path>`.
///
/// This preserves typo protection: when the requested
/// `[scaffold.ResourceName]` section is absent it errors, *unless*
///
/// - the file defines no `[scaffold.*]` sections at all (a pure `[generate]`
///   defaults file — there is nothing to typo), or
/// - the caller supplied fields on the CLI (the scaffold definition comes from
///   the command line, and the config is only consulted for defaults).
///
/// In those two cases it returns a default entry carrying the `[generate] id`
/// project default.
///
/// # Errors
///
/// - [`GenerateError::Io`] if the file cannot be read.
/// - [`GenerateError::Config`] if the file is not valid TOML, or the requested
///   section is missing and neither exception applies.
pub fn read_explicit_scaffold_config(
    config_path: &Path,
    resource_name: &str,
    cli_has_fields: bool,
) -> Result<ScaffoldConfigEntry, GenerateError> {
    // The `[scaffold.X]` section (with `[generate] id` already propagated).
    if let Some(entry) = read_scaffold_config(config_path, resource_name)? {
        return Ok(entry);
    }
    // Section absent: allow the project-default fallback only when there is no
    // scaffold table to have mistyped, or the CLI carries the field list.
    let config = parse_config(config_path)?;
    if config.scaffold.is_empty() || cli_has_fields {
        return Ok(ScaffoldConfigEntry {
            id: config.generate.id,
            ..ScaffoldConfigEntry::default()
        });
    }
    Err(GenerateError::Config(format!(
        "no [scaffold.{}] section found in {}",
        pascal(resource_name),
        config_path.display()
    )))
}

/// Read the raw project-level `[generate] id` string from `config_path`, if set.
///
/// Parses only the `[generate]` table (via [`GenerateDefaultsConfig`]), so an
/// unrelated `[scaffold.*]` recipe with a typo does not break defaults-only
/// reads.
///
/// # Errors
///
/// - [`GenerateError::Io`] if the file cannot be read.
/// - [`GenerateError::Config`] if the file is not valid TOML.
fn read_generate_id(config_path: &Path) -> Result<Option<String>, GenerateError> {
    let content = std::fs::read_to_string(config_path)
        .map_err(|e| std::io::Error::new(e.kind(), format!("{}: {e}", config_path.display())))?;
    let config: GenerateDefaultsConfig = toml::from_str(&content).map_err(|e| {
        GenerateError::Config(format!("invalid TOML in {}: {e}", config_path.display()))
    })?;
    Ok(config.generate.id)
}

/// Read the project-level `[generate]` defaults from `config_path`, returning
/// the `IdType` default if one is set.
///
/// # Errors
///
/// - [`GenerateError::Io`] if the file cannot be read.
/// - [`GenerateError::Config`] if the file is not valid TOML or `id` is invalid.
pub fn read_generate_defaults(config_path: &Path) -> Result<IdType, GenerateError> {
    read_generate_id(config_path)?.map_or_else(|| Ok(IdType::default()), |s| IdType::parse(&s))
}

/// Merge a TOML config entry with CLI-supplied values.
///
/// For each key, if the caller supplied a non-empty CLI slice that value set
/// replaces the TOML list; otherwise the TOML list is kept.
///
/// The `cli_id` parameter follows the precedence rule:
///   `--id` CLI > `[scaffold.X] id` TOML > `[generate] id` TOML > `BigSerial`.
///
/// # Errors
/// Returns [`GenerateError::Config`] if any `--id` value is unrecognised.
#[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)]
pub fn merge_config_with_cli(
    config: ScaffoldConfigEntry,
    cli_fields: &[String],
    cli_indexes: &[String],
    cli_uniques: &[String],
    cli_validations: &[String],
    cli_defaults: &[String],
    cli_queries: &[String],
    cli_soft_delete: bool,
    cli_api: bool,
    cli_sharded: bool,
    cli_shard_key: Option<&str>,
    cli_live: bool,
    cli_id: Option<&str>,
    cli_live_validation: bool,
    cli_no_policy: bool,
    cli_belongs_to: Option<&str>,
    cli_counter_cache: bool,
    cli_searchable: &[String],
    cli_i18n: bool,
    cli_import: bool,
) -> Result<(Vec<String>, ScaffoldOptions), GenerateError> {
    let pick = |cli: &[String], toml: Vec<String>| -> Vec<String> {
        if cli.is_empty() { toml } else { cli.to_vec() }
    };
    let fields = pick(cli_fields, config.fields);
    let indexes = pick(cli_indexes, config.indexes);
    let uniques = pick(cli_uniques, config.uniques);
    let validations = pick(cli_validations, config.validations);
    let defaults = pick(cli_defaults, config.defaults);
    let queries = pick(cli_queries, config.queries);
    let searchable = pick(cli_searchable, config.searchable);
    // CLI flag wins; TOML config enables it when present.
    let soft_delete = cli_soft_delete || config.soft_delete;
    let api = cli_api || config.api;
    let sharded = cli_sharded || config.sharded;
    let shard_key = cli_shard_key.map(str::to_owned).or(config.shard_key);
    let live = cli_live || config.live;
    let live_validation = cli_live_validation || config.live_validation;
    let no_policy = cli_no_policy || config.no_policy;
    let belongs_to = cli_belongs_to.map(str::to_owned).or(config.belongs_to);
    let counter_cache = cli_counter_cache || config.counter_cache.unwrap_or(false);
    let i18n = cli_i18n || config.i18n;
    let import = cli_import || config.import;
    // Precedence: CLI > per-resource TOML > project-default TOML > BigSerial.
    let id_type = if let Some(s) = cli_id {
        IdType::parse(s)?
    } else if let Some(ref s) = config.id {
        IdType::parse(s)?
    } else {
        IdType::default()
    };
    Ok((
        fields,
        ScaffoldOptions {
            model: ModelOptions {
                indexes,
                uniques,
                validations,
                defaults,
                soft_delete,
                sharded,
                shard_key,
                id_type,
                searchable,
            },
            queries,
            api,
            live,
            live_validation,
            no_policy,
            belongs_to,
            counter_cache,
            i18n,
            import,
        },
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn write_config(tmp: &TempDir, content: &str) -> std::path::PathBuf {
        let path = tmp.path().join("autumn.generate.toml");
        fs::write(&path, content).unwrap();
        path
    }

    // ── read_scaffold_config ──────────────────────────────────────────────

    #[test]
    fn parse_valid_scaffold_config() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            r#"
[scaffold.Bookmark]
fields      = ["url:String", "title:String", "tag:String", "alive:bool"]
indexes     = ["url", "tag"]
validations = ["url=url", "title=length:min=1,max=200"]
defaults    = ["alive=true"]
queries     = ["find_by_tag:tag", "find_by_alive:alive"]
"#,
        );

        let entry = read_scaffold_config(&path, "Bookmark")
            .unwrap()
            .expect("Bookmark section must be present");

        assert_eq!(
            entry.fields,
            vec!["url:String", "title:String", "tag:String", "alive:bool"]
        );
        assert_eq!(entry.indexes, vec!["url", "tag"]);
        assert_eq!(
            entry.validations,
            vec!["url=url", "title=length:min=1,max=200"]
        );
        assert_eq!(entry.defaults, vec!["alive=true"]);
        assert_eq!(
            entry.queries,
            vec!["find_by_tag:tag", "find_by_alive:alive"]
        );
    }

    #[test]
    fn parse_minimal_config_with_fields_only() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "[scaffold.Post]\nfields = [\"title:String\"]\n");

        let entry = read_scaffold_config(&path, "Post").unwrap().unwrap();
        assert_eq!(entry.fields, vec!["title:String"]);
        assert!(entry.indexes.is_empty());
        assert!(entry.validations.is_empty());
        assert!(entry.defaults.is_empty());
        assert!(entry.queries.is_empty());
    }

    #[test]
    fn snake_case_name_matches_pascal_case_toml_section() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "[scaffold.Bookmark]\nfields = [\"url:String\"]\n");

        // CLI input `bookmark` (snake_case) must find `[scaffold.Bookmark]`.
        let entry = read_scaffold_config(&path, "bookmark")
            .unwrap()
            .expect("snake_case name should resolve to PascalCase section");
        assert_eq!(entry.fields, vec!["url:String"]);
    }

    #[test]
    fn unknown_key_returns_config_error() {
        let tmp = TempDir::new().unwrap();
        // `index` is the wrong key; the correct key is `indexes`.
        let path = write_config(
            &tmp,
            "[scaffold.Post]\nfields = [\"title:String\"]\nindex = [\"title\"]\n",
        );

        let err = read_scaffold_config(&path, "Post").unwrap_err();
        assert!(
            matches!(err, GenerateError::Config(_)),
            "misspelled key should return Config error, got: {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("index"),
            "error should mention the unknown key; got: {msg}"
        );
    }

    #[test]
    fn missing_section_returns_none() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "[scaffold.Post]\nfields = [\"title:String\"]\n");

        let result = read_scaffold_config(&path, "Bookmark").unwrap();
        assert!(result.is_none(), "unknown resource should return None");
    }

    #[test]
    fn invalid_toml_returns_config_error() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "not valid toml {{{{");

        let err = read_scaffold_config(&path, "Bookmark").unwrap_err();
        assert!(
            matches!(err, GenerateError::Config(_)),
            "expected Config error, got: {err:?}"
        );
    }

    #[test]
    fn missing_file_returns_io_error() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("nonexistent.toml");

        let err = read_scaffold_config(&path, "Bookmark").unwrap_err();
        assert!(
            matches!(err, GenerateError::Io(_)),
            "expected Io error for missing file, got: {err:?}"
        );
    }

    // ── read_explicit_scaffold_config (typo protection, issue #1400) ───────

    #[test]
    fn explicit_config_uses_matching_section() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "[scaffold.Post]\nfields = [\"title:String\"]\n");
        let entry = read_explicit_scaffold_config(&path, "Post", false).unwrap();
        assert_eq!(entry.fields, vec!["title:String"]);
    }

    #[test]
    fn explicit_config_missing_section_among_others_errors_without_cli_fields() {
        // Typo protection: the file defines a scaffold resource, but not the
        // requested one, and the CLI supplied no fields → likely a typo.
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "[scaffold.Other]\nfields = [\"name:String\"]\n");
        let err = read_explicit_scaffold_config(&path, "Post", false).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("no [scaffold.Post] section"),
            "missing section with other sections present must error: {msg}"
        );
    }

    #[test]
    fn explicit_config_missing_section_ok_with_cli_fields() {
        // CLI supplies the field list, so the missing section is not fatal; the
        // [generate] id default still applies.
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            "[generate]\nid = \"uuid\"\n\n[scaffold.Other]\nfields = [\"name:String\"]\n",
        );
        let entry = read_explicit_scaffold_config(&path, "Post", true).unwrap();
        assert_eq!(entry.id.as_deref(), Some("uuid"));
        assert!(entry.fields.is_empty());
    }

    #[test]
    fn unknown_key_inside_generate_table_errors() {
        // A typo under [generate] must not be silently ignored (which would
        // fall back to BigSerial despite the user intending uuid).
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "[generate]\nide = \"uuid\"\n");
        let err = read_generate_defaults(&path).unwrap_err();
        assert!(
            matches!(err, GenerateError::Config(_)),
            "unknown [generate] key must error, got: {err:?}"
        );
        // The same applies to the defaults-only entry reader and the strict path.
        assert!(read_generate_defaults_entry(&path).is_err());
        assert!(read_scaffold_config(&path, "Post").is_err());
    }

    #[test]
    fn defaults_only_read_rejects_misspelled_top_level_table() {
        // A typo'd defaults table ([genrate]) or a stray top-level `id` key must
        // not be silently dropped (which would fall back to BigSerial despite the
        // user intending uuid). [scaffold.*] recipes stay ignored.
        for bad in [
            "[genrate]\nid = \"uuid\"\n",
            "id = \"uuid\"\n",
            "[generate]\nid = \"uuid\"\n\n[scafold.Post]\nfields = [\"x:String\"]\n",
        ] {
            let tmp = TempDir::new().unwrap();
            let path = write_config(&tmp, bad);
            assert!(
                read_generate_defaults(&path).is_err(),
                "defaults-only read must reject misspelled top-level config: {bad:?}"
            );
        }
    }

    #[test]
    fn defaults_only_read_tolerates_malformed_scaffold_recipe() {
        // A checked-in [scaffold.*] recipe with an unsupported/typo'd key must
        // NOT break defaults-only reads (generate model / auto-discovered
        // scaffold), which only consult [generate].
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            "[generate]\nid = \"uuid\"\n\n\
             [scaffold.Post]\nfields = [\"title:String\"]\nindex = [\"title\"]\n",
        );
        // `index` is an unknown key for ScaffoldConfigEntry (deny_unknown_fields),
        // so a full parse would fail — but the defaults-only readers must not.
        assert_eq!(read_generate_defaults(&path).unwrap(), IdType::Uuid);
        assert_eq!(
            read_generate_defaults_entry(&path).unwrap().id.as_deref(),
            Some("uuid")
        );
        // The strict, recipe-using reader still rejects the malformed section.
        assert!(read_scaffold_config(&path, "Post").is_err());
    }

    #[test]
    fn generate_defaults_entry_ignores_per_resource_recipe() {
        // Auto-discovery must contribute only [generate] defaults, never a
        // per-resource [scaffold.X] recipe's fields/booleans.
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            "[generate]\nid = \"uuid\"\n\n\
             [scaffold.Post]\nfields = [\"name:String\"]\napi = true\nsharded = true\n",
        );
        let entry = read_generate_defaults_entry(&path).unwrap();
        assert_eq!(
            entry.id.as_deref(),
            Some("uuid"),
            "[generate] id must carry over"
        );
        assert!(
            entry.fields.is_empty(),
            "per-resource fields must be ignored"
        );
        assert!(!entry.api, "per-resource api must be ignored");
        assert!(!entry.sharded, "per-resource sharded must be ignored");
    }

    #[test]
    fn explicit_config_misspelled_scaffold_table_errors() {
        // A mistyped top-level table name ([scafold.Post]) must not be silently
        // ignored as if the file were a pure [generate] defaults file.
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "[scafold.Post]\nfields = [\"title:String\"]\n");
        let err = read_explicit_scaffold_config(&path, "Post", false).unwrap_err();
        assert!(
            matches!(err, GenerateError::Config(_)),
            "misspelled top-level table must error, got: {err:?}"
        );
        // Defaults-only reads also reject a misspelled top-level table, so a
        // project-default typo is never silently dropped.
        assert!(read_generate_defaults(&path).is_err());
    }

    #[test]
    fn explicit_config_pure_generate_file_is_lenient() {
        // A file with no [scaffold.*] sections is a pure defaults file: there is
        // nothing to mistype, so a missing section is fine even without fields.
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "[generate]\nid = \"uuid\"\n");
        let entry = read_explicit_scaffold_config(&path, "Post", false).unwrap();
        assert_eq!(entry.id.as_deref(), Some("uuid"));
    }

    // ── merge_config_with_cli ─────────────────────────────────────────────

    fn bookmark_entry() -> ScaffoldConfigEntry {
        ScaffoldConfigEntry {
            fields: vec!["url:String".into(), "tag:String".into()],
            indexes: vec!["url".into()],
            uniques: vec![],
            validations: vec!["url=url".into()],
            defaults: vec![],
            queries: vec!["find_by_url:url".into()],
            soft_delete: false,
            api: false,
            sharded: false,
            shard_key: None,
            live: false,
            id: None,
            live_validation: false,
            no_policy: false,
            belongs_to: None,
            counter_cache: None,
            searchable: vec![],
            i18n: false,
            import: false,
        }
    }

    fn merge(entry: ScaffoldConfigEntry) -> (Vec<String>, ScaffoldOptions) {
        merge_config_with_cli(
            entry,
            &[],
            &[],
            &[],
            &[],
            &[],
            &[],
            false,
            false,
            false,
            None,
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap()
    }

    #[test]
    fn merge_uses_toml_when_all_cli_empty() {
        let (fields, opts) = merge(bookmark_entry());
        assert_eq!(fields, vec!["url:String", "tag:String"]);
        assert_eq!(opts.model.indexes, vec!["url"]);
        assert_eq!(opts.model.validations, vec!["url=url"]);
        assert!(opts.model.defaults.is_empty());
        assert_eq!(opts.queries, vec!["find_by_url:url"]);
    }

    #[test]
    fn merge_cli_fields_override_toml_fields() {
        let (fields, _) = merge_config_with_cli(
            bookmark_entry(),
            &["title:String".into(), "body:Text".into()],
            &[],
            &[],
            &[],
            &[],
            &[],
            false,
            false,
            false,
            None,
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert_eq!(fields, vec!["title:String", "body:Text"]);
    }

    #[test]
    fn merge_cli_indexes_override_toml_indexes() {
        let (_, opts) = merge_config_with_cli(
            bookmark_entry(),
            &[],
            &["tag".into()],
            &[],
            &[],
            &[],
            &[],
            false,
            false,
            false,
            None,
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert_eq!(opts.model.indexes, vec!["tag"]);
    }

    #[test]
    fn merge_cli_validations_override_toml_validations() {
        let (_, opts) = merge_config_with_cli(
            bookmark_entry(),
            &[],
            &[],
            &[],
            &["url=email".into()],
            &[],
            &[],
            false,
            false,
            false,
            None,
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert_eq!(opts.model.validations, vec!["url=email"]);
    }

    #[test]
    fn merge_cli_defaults_override_toml_defaults() {
        let mut entry = bookmark_entry();
        entry.defaults = vec!["url=example.com".into()];
        let (_, opts) = merge_config_with_cli(
            entry,
            &[],
            &[],
            &[],
            &[],
            &["tag=general".into()],
            &[],
            false,
            false,
            false,
            None,
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert_eq!(opts.model.defaults, vec!["tag=general"]);
    }

    #[test]
    fn merge_cli_queries_override_toml_queries() {
        let (_, opts) = merge_config_with_cli(
            bookmark_entry(),
            &[],
            &[],
            &[],
            &[],
            &[],
            &["find_by_tag:tag".into()],
            false,
            false,
            false,
            None,
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert_eq!(opts.queries, vec!["find_by_tag:tag"]);
    }

    #[test]
    fn merge_empty_cli_keeps_empty_toml() {
        let entry = ScaffoldConfigEntry::default();
        let (fields, opts) = merge_config_with_cli(
            entry,
            &[],
            &[],
            &[],
            &[],
            &[],
            &[],
            false,
            false,
            false,
            None,
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert!(fields.is_empty());
        assert!(opts.model.indexes.is_empty());
        assert!(opts.model.validations.is_empty());
        assert!(opts.model.defaults.is_empty());
        assert!(opts.queries.is_empty());
    }

    #[test]
    fn merge_cli_soft_delete_flag_wins() {
        let (_, opts) = merge_config_with_cli(
            bookmark_entry(),
            &[],
            &[],
            &[],
            &[],
            &[],
            &[],
            true,
            false,
            false,
            None,
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert!(
            opts.model.soft_delete,
            "cli_soft_delete=true must set soft_delete on the merged options"
        );
    }

    #[test]
    fn merge_toml_soft_delete_propagates() {
        let mut entry = bookmark_entry();
        entry.soft_delete = true;
        let (_, opts) = merge(entry);
        assert!(
            opts.model.soft_delete,
            "soft_delete=true in TOML config must propagate when CLI flag is false"
        );
    }

    #[test]
    fn merge_soft_delete_false_when_both_unset() {
        let (_, opts) = merge(bookmark_entry());
        assert!(
            !opts.model.soft_delete,
            "soft_delete must be false when neither CLI nor TOML sets it"
        );
    }

    #[test]
    fn parse_scaffold_config_with_soft_delete() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            "[scaffold.Article]\nfields = [\"title:String\"]\nsoft_delete = true\n",
        );
        let entry = read_scaffold_config(&path, "Article")
            .unwrap()
            .expect("Article section must be present");
        assert!(
            entry.soft_delete,
            "soft_delete = true in TOML must be parsed into ScaffoldConfigEntry"
        );
    }

    #[test]
    fn merge_cli_api_flag_wins() {
        let (_, opts) = merge_config_with_cli(
            bookmark_entry(),
            &[],
            &[],
            &[],
            &[],
            &[],
            &[],
            false,
            true,
            false,
            None,
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert!(opts.api);
    }

    #[test]
    fn merge_toml_api_propagates() {
        let mut entry = bookmark_entry();
        entry.api = true;
        let (_, opts) = merge(entry);
        assert!(opts.api);
    }

    #[test]
    fn parse_scaffold_config_with_api() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            "[scaffold.Article]\nfields = [\"title:String\"]\napi = true\n",
        );
        let entry = read_scaffold_config(&path, "Article")
            .unwrap()
            .expect("Article section must be present");
        assert!(
            entry.api,
            "api = true in TOML must be parsed into ScaffoldConfigEntry"
        );
    }

    #[test]
    fn merge_cli_sharded_flag_wins() {
        let (_, opts) = merge_config_with_cli(
            bookmark_entry(),
            &[],
            &[],
            &[],
            &[],
            &[],
            &[],
            false,
            false,
            true,
            None,
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert!(
            opts.model.sharded,
            "cli_sharded=true must set sharded on the merged options"
        );
    }

    #[test]
    fn merge_toml_sharded_propagates() {
        let mut entry = bookmark_entry();
        entry.sharded = true;
        let (_, opts) = merge(entry);
        assert!(
            opts.model.sharded,
            "sharded=true in TOML config must propagate when CLI flag is false"
        );
    }

    #[test]
    fn merge_shard_key_cli_overrides_toml() {
        let mut entry = bookmark_entry();
        entry.shard_key = Some("tenant_id".into());
        let (_, opts) = merge_config_with_cli(
            entry,
            &[],
            &[],
            &[],
            &[],
            &[],
            &[],
            false,
            false,
            false,
            Some("user_id"),
            false,
            None,
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert_eq!(
            opts.model.shard_key.as_deref(),
            Some("user_id"),
            "CLI shard_key must override TOML shard_key"
        );
    }

    #[test]
    fn merge_shard_key_toml_used_when_no_cli() {
        let mut entry = bookmark_entry();
        entry.shard_key = Some("org_id".into());
        let (_, opts) = merge(entry);
        assert_eq!(
            opts.model.shard_key.as_deref(),
            Some("org_id"),
            "TOML shard_key must propagate when no CLI shard_key is given"
        );
    }

    #[test]
    fn parse_scaffold_config_with_sharded() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            "[scaffold.Account]\nfields = [\"tenant_id:i64\"]\nsharded = true\nshard_key = \"tenant_id\"\n",
        );
        let entry = read_scaffold_config(&path, "Account")
            .unwrap()
            .expect("Account section must be present");
        assert!(
            entry.sharded,
            "sharded = true in TOML must be parsed into ScaffoldConfigEntry"
        );
        assert_eq!(
            entry.shard_key.as_deref(),
            Some("tenant_id"),
            "shard_key in TOML must be parsed into ScaffoldConfigEntry"
        );
    }

    // ── id_type (issue #1400) ──────────────────────────────────────────────

    #[test]
    fn merge_cli_id_uuid_sets_uuid_id_type() {
        let (_, opts) = merge_config_with_cli(
            bookmark_entry(),
            &[],
            &[],
            &[],
            &[],
            &[],
            &[],
            false,
            false,
            false,
            None,
            false,
            Some("uuid"),
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert_eq!(
            opts.model.id_type,
            IdType::Uuid,
            "cli --id uuid must set Uuid id_type"
        );
    }

    #[test]
    fn merge_toml_id_uuid_propagates() {
        let mut entry = bookmark_entry();
        entry.id = Some("uuid".into());
        let (_, opts) = merge(entry);
        assert_eq!(
            opts.model.id_type,
            IdType::Uuid,
            "[scaffold.X] id = 'uuid' must propagate"
        );
    }

    #[test]
    fn merge_cli_id_overrides_toml_id() {
        let mut entry = bookmark_entry();
        entry.id = Some("uuid".into());
        let (_, opts) = merge_config_with_cli(
            entry,
            &[],
            &[],
            &[],
            &[],
            &[],
            &[],
            false,
            false,
            false,
            None,
            false,
            Some("bigint"),
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap();
        assert_eq!(
            opts.model.id_type,
            IdType::BigSerial,
            "CLI --id bigint must override TOML id = 'uuid'"
        );
    }

    #[test]
    fn merge_default_id_type_is_bigserial() {
        let (_, opts) = merge(bookmark_entry());
        assert_eq!(
            opts.model.id_type,
            IdType::BigSerial,
            "default id_type must be BigSerial (AC4)"
        );
    }

    #[test]
    fn merge_cli_bad_id_returns_error() {
        let err = merge_config_with_cli(
            bookmark_entry(),
            &[],
            &[],
            &[],
            &[],
            &[],
            &[],
            false,
            false,
            false,
            None,
            false,
            Some("guid"),
            false,
            false,
            None,
            false,
            &[],
            false,
            false,
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("guid"),
            "error must mention the bad value: {msg}"
        );
        assert!(
            msg.contains("uuid"),
            "error must list accepted values: {msg}"
        );
    }

    #[test]
    fn project_default_id_propagates_via_generate_section() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            "[generate]\nid = \"uuid\"\n\n[scaffold.Post]\nfields = [\"title:String\"]\n",
        );
        let defaults_id = read_generate_defaults(&path).unwrap();
        assert_eq!(
            defaults_id,
            IdType::Uuid,
            "[generate] id = 'uuid' must be read as Uuid"
        );
    }

    #[test]
    fn project_default_propagates_into_scaffold_entry() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            "[generate]\nid = \"uuid\"\n\n[scaffold.Post]\nfields = [\"title:String\"]\n",
        );
        let entry = read_scaffold_config(&path, "Post").unwrap().unwrap();
        assert_eq!(
            entry.id.as_deref(),
            Some("uuid"),
            "[generate] id must propagate into scaffold entry id when unset"
        );
    }

    #[test]
    fn per_resource_id_overrides_project_default() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            "[generate]\nid = \"uuid\"\n\n[scaffold.Post]\nfields = [\"title:String\"]\nid = \"bigint\"\n",
        );
        let entry = read_scaffold_config(&path, "Post").unwrap().unwrap();
        assert_eq!(
            entry.id.as_deref(),
            Some("bigint"),
            "per-resource id must not be overridden by [generate] default"
        );
    }
}