shaperail-codegen 0.12.1

YAML parser, validator, and code generator for Shaperail
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
use shaperail_core::{FieldType, HttpMethod, ResourceDefinition, WASM_HOOK_PREFIX};

/// A semantic validation error for a resource definition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
    pub message: String,
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

/// Validate a parsed `ResourceDefinition` for semantic correctness.
///
/// Returns a list of all validation errors found. An empty list means the
/// resource is valid.
pub fn validate_resource(rd: &ResourceDefinition) -> Vec<ValidationError> {
    let mut errors = Vec::new();
    let res = &rd.resource;

    // Resource name must not be empty
    if res.is_empty() {
        errors.push(err("resource name must not be empty"));
    }

    // Version must be >= 1
    if rd.version == 0 {
        errors.push(err(&format!("resource '{res}': version must be >= 1")));
    }

    // Schema must have at least one field
    if rd.schema.is_empty() {
        errors.push(err(&format!(
            "resource '{res}': schema must have at least one field"
        )));
    }

    // Must have exactly one primary key
    let primary_count = rd.schema.values().filter(|f| f.primary).count();
    if primary_count == 0 {
        errors.push(err(&format!(
            "resource '{res}': schema must have a primary key field"
        )));
    } else if primary_count > 1 {
        errors.push(err(&format!(
            "resource '{res}': schema must have exactly one primary key, found {primary_count}"
        )));
    }

    // Per-field validation
    for (name, field) in &rd.schema {
        // Enum type requires values
        if field.field_type == FieldType::Enum && field.values.is_none() {
            errors.push(err(&format!(
                "resource '{res}': field '{name}' is type enum but has no values"
            )));
        }

        // Non-enum type should not have values
        if field.field_type != FieldType::Enum && field.values.is_some() {
            errors.push(err(&format!(
                "resource '{res}': field '{name}' has values but is not type enum"
            )));
        }

        // Ref field must be uuid type
        if field.reference.is_some() && field.field_type != FieldType::Uuid {
            errors.push(err(&format!(
                "resource '{res}': field '{name}' has ref but is not type uuid"
            )));
        }

        // Ref format must be "resource.field"
        if let Some(ref reference) = field.reference {
            if !reference.contains('.') {
                errors.push(err(&format!(
                    "resource '{res}': field '{name}' ref must be in 'resource.field' format, got '{reference}'"
                )));
            }
        }

        // Array type requires items
        if field.field_type == FieldType::Array && field.items.is_none() {
            errors.push(err(&format!(
                "resource '{res}': field '{name}' is type array but has no items"
            )));
        }

        // Element-level rules for items
        if let Some(items_spec) = &field.items {
            // No nested arrays — clearer error than the generic deny_unknown_fields.
            if items_spec.field_type == FieldType::Array {
                errors.push(err(&format!(
                    "resource '{res}': field '{name}' has nested array items; use type: json for nested arrays"
                )));
            }

            // Enum items require values: [...]
            if items_spec.field_type == FieldType::Enum && items_spec.values.is_none() {
                errors.push(err(&format!(
                    "resource '{res}': field '{name}' has enum items but no values; add `values: [...]` to items"
                )));
            }

            // format only valid for string element type
            if items_spec.format.is_some() && items_spec.field_type != FieldType::String {
                errors.push(err(&format!(
                    "resource '{res}': field '{name}' has items.format but items.type is not string"
                )));
            }

            // ref only valid on uuid element type
            if items_spec.reference.is_some() && items_spec.field_type != FieldType::Uuid {
                errors.push(err(&format!(
                    "resource '{res}': field '{name}' has items.ref but items.type is not uuid"
                )));
            }

            // ref must be in resource.field shape
            if let Some(reference) = &items_spec.reference {
                if !reference.contains('.') {
                    errors.push(err(&format!(
                        "resource '{res}': field '{name}' items.ref must be in 'resource.field' format, got '{reference}'"
                    )));
                }
            }
        }

        // Format only valid for string type
        if field.format.is_some() && field.field_type != FieldType::String {
            errors.push(err(&format!(
                "resource '{res}': field '{name}' has format but is not type string"
            )));
        }

        // Primary key should be generated or required
        if field.primary && !field.generated && !field.required {
            errors.push(err(&format!(
                "resource '{res}': primary key field '{name}' must be generated or required"
            )));
        }

        // Transient field constraints — `transient: true` means input-only, never persisted.
        // Combinations that imply persistence are nonsensical and rejected loudly.
        if field.transient {
            if field.primary {
                errors.push(err(&format!(
                    "resource '{res}': field '{name}' cannot be both transient and primary"
                )));
            }
            if field.generated {
                errors.push(err(&format!(
                    "resource '{res}': field '{name}' cannot be both transient and generated"
                )));
            }
            if field.reference.is_some() {
                errors.push(err(&format!(
                    "resource '{res}': field '{name}' cannot be both transient and have a ref (foreign keys imply persistence)"
                )));
            }
            if field.unique {
                errors.push(err(&format!(
                    "resource '{res}': field '{name}' cannot be both transient and unique (unique constraints require persistence)"
                )));
            }
            if field.default.is_some() {
                errors.push(err(&format!(
                    "resource '{res}': field '{name}' cannot be both transient and have a default (defaults apply to stored columns)"
                )));
            }
        }
    }

    // Transient fields must appear in at least one endpoint's `input:` list — otherwise
    // they're unreachable: never populated, never validated, never seen anywhere.
    let transient_fields: Vec<&String> = rd
        .schema
        .iter()
        .filter(|(_, f)| f.transient)
        .map(|(name, _)| name)
        .collect();
    if !transient_fields.is_empty() {
        let referenced: std::collections::HashSet<&str> = rd
            .endpoints
            .as_ref()
            .map(|eps| {
                eps.values()
                    .filter_map(|ep| ep.input.as_ref())
                    .flat_map(|inputs| inputs.iter().map(|s| s.as_str()))
                    .collect()
            })
            .unwrap_or_default();
        for name in transient_fields {
            if !referenced.contains(name.as_str()) {
                errors.push(err(&format!(
                    "resource '{res}': transient field '{name}' is not declared in any endpoint's input: list (the field would be unreachable)"
                )));
            }
        }
    }

    // Tenant key validation (M18)
    if let Some(ref tenant_key) = rd.tenant_key {
        match rd.schema.get(tenant_key) {
            Some(field) => {
                if field.field_type != FieldType::Uuid {
                    errors.push(err(&format!(
                        "resource '{res}': tenant_key '{tenant_key}' must reference a uuid field, found {}",
                        field.field_type
                    )));
                }
            }
            None => {
                errors.push(err(&format!(
                    "resource '{res}': tenant_key '{tenant_key}' not found in schema"
                )));
            }
        }
    }

    // Endpoint validation
    if let Some(endpoints) = &rd.endpoints {
        for (action, ep) in endpoints {
            // method and path must be set (either explicitly or via convention defaults)
            if ep.method.is_none() {
                errors.push(err(&format!(
                    "resource '{res}': endpoint '{action}' has no method. Use a known action name (list, get, create, update, delete) or set method explicitly"
                )));
            }
            if ep.path.is_none() {
                errors.push(err(&format!(
                    "resource '{res}': endpoint '{action}' has no path. Use a known action name (list, get, create, update, delete) or set path explicitly"
                )));
            }

            // handler: is only valid on custom (non-convention) endpoints.
            // The runtime dispatches list/get/create/update/delete via the
            // standard CRUD path, so a handler: declaration on those keys
            // would be silently ignored at codegen time.
            if let Some(e) = validate_handler_only_on_custom(res, action, ep) {
                errors.push(e);
            }

            if let Some(controller) = &ep.controller {
                // controller: is only valid on conventional CRUD endpoints.
                if let Some(e) = validate_controller_only_on_crud(res, action, ep) {
                    errors.push(e);
                }

                if let Some(before) = &controller.before {
                    if before.is_empty() {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' has an empty controller.before name"
                        )));
                    }
                    validate_controller_name(res, action, "before", before, &mut errors);
                }
                if let Some(after) = &controller.after {
                    if after.is_empty() {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' has an empty controller.after name"
                        )));
                    }
                    validate_controller_name(res, action, "after", after, &mut errors);
                }
            }

            if let Some(events) = &ep.events {
                for event in events {
                    if event.is_empty() {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' has an empty event name"
                        )));
                    }
                }
            }

            if let Some(jobs) = &ep.jobs {
                for job in jobs {
                    if job.is_empty() {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' has an empty job name"
                        )));
                    }
                }
            }

            // Input fields must exist in schema
            if let Some(input) = &ep.input {
                for field_name in input {
                    if !rd.schema.contains_key(field_name) {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' input field '{field_name}' not found in schema"
                        )));
                    }
                }
            }

            // Filter fields must exist in schema
            if let Some(filters) = &ep.filters {
                for field_name in filters {
                    if !rd.schema.contains_key(field_name) {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' filter field '{field_name}' not found in schema"
                        )));
                    }
                }
            }

            // Search fields must exist in schema
            if let Some(search) = &ep.search {
                for field_name in search {
                    if !rd.schema.contains_key(field_name) {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' search field '{field_name}' not found in schema"
                        )));
                    }
                }
            }

            // Sort fields must exist in schema
            if let Some(sort) = &ep.sort {
                for field_name in sort {
                    if !rd.schema.contains_key(field_name) {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' sort field '{field_name}' not found in schema"
                        )));
                    }
                }
            }

            // soft_delete requires deleted_at field in schema
            if ep.soft_delete && !rd.schema.contains_key("deleted_at") {
                errors.push(err(&format!(
                    "resource '{res}': endpoint '{action}' has soft_delete but schema has no 'deleted_at' field"
                )));
            }

            if let Some(upload) = &ep.upload {
                match ep.method.as_ref() {
                    Some(HttpMethod::Post | HttpMethod::Patch | HttpMethod::Put) => {}
                    Some(_) => errors.push(err(&format!(
                        "resource '{res}': endpoint '{action}' uses upload but method must be POST, PATCH, or PUT"
                    ))),
                    None => {} // already reported above
                }

                match rd.schema.get(&upload.field) {
                    Some(field) if field.field_type == FieldType::File => {}
                    Some(_) => errors.push(err(&format!(
                        "resource '{res}': endpoint '{action}' upload field '{}' must be type file",
                        upload.field
                    ))),
                    None => errors.push(err(&format!(
                        "resource '{res}': endpoint '{action}' upload field '{}' not found in schema",
                        upload.field
                    ))),
                }

                if !matches!(upload.storage.as_str(), "local" | "s3" | "gcs" | "azure") {
                    errors.push(err(&format!(
                        "resource '{res}': endpoint '{action}' upload storage '{}' is invalid",
                        upload.storage
                    )));
                }

                if !ep
                    .input
                    .as_ref()
                    .is_some_and(|fields| fields.iter().any(|field| field == &upload.field))
                {
                    errors.push(err(&format!(
                        "resource '{res}': endpoint '{action}' upload field '{}' must appear in input",
                        upload.field
                    )));
                }

                for (suffix, expected_types) in [
                    ("filename", &[FieldType::String][..]),
                    ("mime_type", &[FieldType::String][..]),
                    ("size", &[FieldType::Integer, FieldType::Bigint][..]),
                ] {
                    let companion = format!("{}_{}", upload.field, suffix);
                    if let Some(field) = rd.schema.get(&companion) {
                        if !expected_types.contains(&field.field_type) {
                            let expected = expected_types
                                .iter()
                                .map(ToString::to_string)
                                .collect::<Vec<_>>()
                                .join(" or ");
                            errors.push(err(&format!(
                                "resource '{res}': companion upload field '{companion}' must be type {expected}"
                            )));
                        }
                    }
                }
            }
        }
    }

    // Relation validation
    if let Some(relations) = &rd.relations {
        for (name, rel) in relations {
            use shaperail_core::RelationType;

            // belongs_to should have key
            if rel.relation_type == RelationType::BelongsTo && rel.key.is_none() {
                errors.push(err(&format!(
                    "resource '{res}': relation '{name}' is belongs_to but has no key"
                )));
            }

            // has_many/has_one should have foreign_key
            if matches!(
                rel.relation_type,
                RelationType::HasMany | RelationType::HasOne
            ) && rel.foreign_key.is_none()
            {
                errors.push(err(&format!(
                    "resource '{res}': relation '{name}' is {} but has no foreign_key",
                    rel.relation_type
                )));
            }

            // belongs_to key must exist in schema
            if let Some(key) = &rel.key {
                if !rd.schema.contains_key(key) {
                    errors.push(err(&format!(
                        "resource '{res}': relation '{name}' key '{key}' not found in schema"
                    )));
                }
            }
        }
    }

    // Index validation
    if let Some(indexes) = &rd.indexes {
        for (i, idx) in indexes.iter().enumerate() {
            if idx.fields.is_empty() {
                errors.push(err(&format!("resource '{res}': index {i} has no fields")));
            }
            for field_name in &idx.fields {
                if !rd.schema.contains_key(field_name) {
                    errors.push(err(&format!(
                        "resource '{res}': index {i} references field '{field_name}' not in schema"
                    )));
                }
            }
            if let Some(order) = &idx.order {
                if order != "asc" && order != "desc" {
                    errors.push(err(&format!(
                        "resource '{res}': index {i} has invalid order '{order}', must be 'asc' or 'desc'"
                    )));
                }
            }
        }
    }

    errors
}

/// Rejects `controller: { after: ... }` declarations on non-CRUD (custom) endpoints.
///
/// `before:` controllers are now permitted on custom endpoints — the runtime builds
/// a `Context` with auto-populated `tenant_id`, dispatches the before-hook, and
/// stashes the resulting `Context` into `req.extensions_mut()` so the custom handler
/// can read it.
///
/// `after:` controllers remain rejected on custom endpoints because the custom handler
/// owns the response shape — there is no `data:` envelope for the runtime to merge
/// `ctx.response_extras` into, and no consistent hook point after the handler returns.
fn validate_controller_only_on_crud(
    resource: &str,
    action: &str,
    endpoint: &shaperail_core::EndpointSpec,
) -> Option<ValidationError> {
    const CRUD_ACTIONS: &[&str] = &[
        "list",
        "get",
        "create",
        "update",
        "delete",
        "bulk_create",
        "bulk_delete",
    ];
    if CRUD_ACTIONS.contains(&action) {
        return None;
    }
    // Custom endpoint: allow before-only controller, reject after-controller.
    let has_after = endpoint
        .controller
        .as_ref()
        .and_then(|c| c.after.as_deref())
        .is_some();
    if has_after {
        return Some(err(&format!(
            "resource '{resource}': endpoint '{action}' declares `controller: {{ after: ... }}`, \
             but `after:` controllers are only valid on conventional CRUD endpoints \
             (list / get / create / update / delete / bulk_create / bulk_delete).\n\
             \n\
             Custom endpoints generate their own response via `handler:`, so the runtime \
             has no place to merge `ctx.response_extras` or pass through after-hook \
             mutations. Use a `before:` controller for shared setup (auth augmentation, \
             tenant scoping, request validation), and put response-shaping logic inside \
             the handler itself."
        )));
    }
    None
}

/// Rejects `handler:` declarations on convention endpoint action keys.
///
/// The runtime dispatches the convention actions (`list`, `get`, `create`,
/// `update`, `delete`) via the standard CRUD path. The codegen helper
/// `collect_custom_handlers` filters these out, so a `handler:` declaration
/// on a convention key is silently dropped — the user's function is never
/// registered, never compiled, and never called. Surface this as a hard
/// validation error with an actionable workaround.
fn validate_handler_only_on_custom(
    resource: &str,
    action: &str,
    endpoint: &shaperail_core::EndpointSpec,
) -> Option<ValidationError> {
    let handler = endpoint.handler.as_deref()?;
    if !crate::rust::HANDLER_CONVENTIONS.contains(&action) {
        return None;
    }
    Some(err(&format!(
        "resource '{resource}': endpoint '{action}' declares `handler: {handler}`, \
         but `handler:` is only valid on custom (non-convention) endpoints. \
         The convention actions list / get / create / update / delete are \
         dispatched by the runtime CRUD path; a `handler:` declaration on \
         them would be silently dropped at codegen time.\n\
         \n\
         To attach a custom handler at the same HTTP method+path, rename the \
         endpoint key to a non-convention action (e.g. `post_{resource}`) and \
         set `method:` and `path:` explicitly:\n\
         \n\
         endpoints:\n  \
           post_{resource}:\n    \
             method: POST\n    \
             path: /{resource}\n    \
             handler: {handler}\n\
         \n\
         To customize standard CRUD behavior without replacing the runtime \
         path, use `controller: {{ before: ... }}` for setup logic and \
         `controller: {{ after: ... }}` for response shaping."
    )))
}

/// Validates a controller name — either a Rust function name or a `wasm:` prefixed path.
fn validate_controller_name(
    res: &str,
    action: &str,
    phase: &str,
    name: &str,
    errors: &mut Vec<ValidationError>,
) {
    if let Some(wasm_path) = name.strip_prefix(WASM_HOOK_PREFIX) {
        if wasm_path.is_empty() {
            errors.push(err(&format!(
                "resource '{res}': endpoint '{action}' controller.{phase} has 'wasm:' prefix but no path"
            )));
        } else if !wasm_path.ends_with(".wasm") {
            errors.push(err(&format!(
                "resource '{res}': endpoint '{action}' controller.{phase} WASM path must end with '.wasm', got '{wasm_path}'"
            )));
        }
    }
}

fn err(message: &str) -> ValidationError {
    ValidationError {
        message: message.to_string(),
    }
}

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

    #[test]
    fn valid_resource_passes() {
        let yaml = include_str!("../../resources/users.yaml");
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.is_empty(), "Expected no errors, got: {errors:?}");
    }

    #[test]
    fn enum_without_values() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  status: { type: enum, required: true }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("type enum but has no values")));
    }

    #[test]
    fn ref_field_not_uuid() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  org_id: { type: string, ref: organizations.id }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("has ref but is not type uuid")));
    }

    #[test]
    fn missing_primary_key() {
        let yaml = r#"
resource: items
version: 1
schema:
  name: { type: string, required: true }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("must have a primary key")));
    }

    #[test]
    fn soft_delete_without_deleted_at() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  delete:
    method: DELETE
    path: /items/:id
    auth: [admin]
    soft_delete: true
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("soft_delete but schema has no 'deleted_at'")));
    }

    #[test]
    fn input_field_not_in_schema() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  create:
    method: POST
    path: /items
    auth: [admin]
    input: [name, nonexistent]
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("input field 'nonexistent' not found in schema")));
    }

    #[test]
    fn belongs_to_without_key() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
relations:
  org: { resource: organizations, type: belongs_to }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("belongs_to but has no key")));
    }

    #[test]
    fn has_many_without_foreign_key() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
relations:
  orders: { resource: orders, type: has_many }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("has_many but has no foreign_key")));
    }

    #[test]
    fn index_references_missing_field() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
indexes:
  - fields: [missing_field]
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("references field 'missing_field' not in schema")));
    }

    #[test]
    fn error_message_format() {
        let yaml = r#"
resource: users
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  role: { type: enum }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert_eq!(
            errors[0].message,
            "resource 'users': field 'role' is type enum but has no values"
        );
    }

    #[test]
    fn wasm_controller_valid_path() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  create:
    method: POST
    path: /items
    input: [name]
    controller: { before: "wasm:./plugins/my_validator.wasm" }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(
            errors.is_empty(),
            "Expected no errors for valid WASM controller, got: {errors:?}"
        );
    }

    #[test]
    fn wasm_controller_missing_extension() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  create:
    method: POST
    path: /items
    input: [name]
    controller: { before: "wasm:./plugins/my_validator" }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("WASM path must end with '.wasm'")));
    }

    #[test]
    fn wasm_controller_empty_path() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  create:
    method: POST
    path: /items
    input: [name]
    controller: { before: "wasm:" }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("'wasm:' prefix but no path")));
    }

    #[test]
    fn upload_endpoint_valid_when_file_field_declared() {
        let yaml = r#"
resource: assets
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  file: { type: file, required: true }
  file_filename: { type: string }
  file_mime_type: { type: string }
  file_size: { type: bigint }
  updated_at: { type: timestamp, generated: true }
endpoints:
  upload:
    method: POST
    path: /assets/upload
    input: [file]
    upload:
      field: file
      storage: local
      max_size: 5mb
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(
            errors.is_empty(),
            "Expected valid upload resource, got {errors:?}"
        );
    }

    #[test]
    fn upload_endpoint_requires_file_field() {
        let yaml = r#"
resource: assets
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  file_path: { type: string, required: true }
endpoints:
  upload:
    method: POST
    path: /assets/upload
    input: [file_path]
    upload:
      field: file_path
      storage: local
      max_size: 5mb
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("upload field 'file_path' must be type file")));
    }

    #[test]
    fn tenant_key_valid_uuid_field() {
        let yaml = r#"
resource: projects
version: 1
tenant_key: org_id
schema:
  id: { type: uuid, primary: true, generated: true }
  org_id: { type: uuid, ref: organizations.id, required: true }
  name: { type: string, required: true }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.is_empty(), "Expected no errors, got: {errors:?}");
    }

    #[test]
    fn tenant_key_missing_field() {
        let yaml = r#"
resource: projects
version: 1
tenant_key: org_id
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("tenant_key 'org_id' not found in schema")));
    }

    #[test]
    fn transient_field_valid() {
        let yaml = r#"
resource: users
version: 1
schema:
  id:            { type: uuid, primary: true, generated: true }
  password:      { type: string, transient: true, min: 12, required: true }
  password_hash: { type: string, required: true }
endpoints:
  create:
    method: POST
    path: /users
    input: [password]
    controller: { before: hash_password }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.is_empty(), "Expected no errors, got: {errors:?}");
    }

    #[test]
    fn transient_field_dead_when_not_in_input() {
        let yaml = r#"
resource: users
version: 1
schema:
  id:       { type: uuid, primary: true, generated: true }
  password: { type: string, transient: true, min: 12 }
endpoints:
  create:
    method: POST
    path: /users
    input: []
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("transient field 'password' is not declared in any endpoint's input")));
    }

    #[test]
    fn transient_field_rejects_primary() {
        let yaml = r#"
resource: users
version: 1
schema:
  bad: { type: uuid, transient: true, primary: true }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("cannot be both transient and primary")));
    }

    #[test]
    fn transient_field_rejects_generated() {
        let yaml = r#"
resource: users
version: 1
schema:
  id:  { type: uuid, primary: true, generated: true }
  bad: { type: timestamp, transient: true, generated: true }
endpoints:
  create:
    method: POST
    path: /users
    input: [bad]
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("cannot be both transient and generated")));
    }

    #[test]
    fn transient_field_rejects_ref() {
        let yaml = r#"
resource: users
version: 1
schema:
  id:  { type: uuid, primary: true, generated: true }
  bad: { type: uuid, transient: true, ref: orgs.id }
endpoints:
  create:
    method: POST
    path: /users
    input: [bad]
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("cannot be both transient and have a ref")));
    }

    #[test]
    fn transient_field_rejects_unique() {
        let yaml = r#"
resource: users
version: 1
schema:
  id:  { type: uuid, primary: true, generated: true }
  bad: { type: string, transient: true, unique: true }
endpoints:
  create:
    method: POST
    path: /users
    input: [bad]
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("cannot be both transient and unique")));
    }

    #[test]
    fn transient_field_rejects_default() {
        let yaml = r#"
resource: users
version: 1
schema:
  id:  { type: uuid, primary: true, generated: true }
  bad: { type: string, transient: true, default: "x" }
endpoints:
  create:
    method: POST
    path: /users
    input: [bad]
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("cannot be both transient and have a default")));
    }

    #[test]
    fn tenant_key_wrong_type() {
        let yaml = r#"
resource: projects
version: 1
tenant_key: org_name
schema:
  id: { type: uuid, primary: true, generated: true }
  org_name: { type: string, required: true }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("tenant_key 'org_name' must reference a uuid field")));
    }

    #[test]
    fn reject_after_controller_on_custom_endpoint() {
        let yaml = r#"
resource: agents
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
endpoints:
  regenerate_secret:
    method: POST
    path: /agents/:id/regenerate_secret
    auth: [admin]
    controller: { after: my_after }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(
            errors
                .iter()
                .any(|e| e.message.contains("declares `controller: { after: ... }`")),
            "expected a CustomEndpointWithAfterController error, got: {errors:?}"
        );
    }

    #[test]
    fn allow_before_controller_on_custom_endpoint() {
        let yaml = r#"
resource: agents
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
endpoints:
  regenerate_secret:
    method: POST
    path: /agents/:id/regenerate_secret
    auth: [admin]
    controller: { before: my_before }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(
            errors.is_empty(),
            "before:-only controller on a custom endpoint should validate clean, got: {errors:?}"
        );
    }

    #[test]
    fn allow_controller_on_crud_endpoints() {
        let yaml = r#"
resource: agents
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  create:
    method: POST
    path: /agents
    input: [name]
    controller: { before: my_before }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(
            !errors.iter().any(|e| e
                .message
                .contains("declares `controller:` but is a custom endpoint")),
            "create endpoint with controller should NOT trip the rule, got: {errors:?}"
        );
    }

    #[test]
    fn handler_on_convention_endpoint_rejected() {
        for action in &["list", "get", "create", "update", "delete"] {
            let yaml = format!(
                r#"
resource: items
version: 1
schema:
  id: {{ type: uuid, primary: true, generated: true }}
  name: {{ type: string, required: true }}
endpoints:
  {action}:
    handler: my_handler
"#
            );
            let rd = parse_resource(&yaml).unwrap();
            let errors = validate_resource(&rd);
            assert!(
                errors
                    .iter()
                    .any(|e| e.message.contains("`handler: my_handler`")
                        && e.message
                            .contains("only valid on custom (non-convention) endpoints")),
                "expected handler-on-convention error for action '{action}', got: {errors:?}"
            );
        }
    }

    #[test]
    fn handler_on_custom_endpoint_allowed() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  post_item:
    method: POST
    path: /items
    handler: create_item_custom
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(
            !errors
                .iter()
                .any(|e| e.message.contains("only valid on custom")),
            "custom endpoint with handler must not trip the rule, got: {errors:?}"
        );
    }

    #[test]
    fn convention_endpoint_without_handler_allowed() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  create:
    input: [name]
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(
            !errors
                .iter()
                .any(|e| e.message.contains("only valid on custom")),
            "convention endpoint without handler must not trip the rule, got: {errors:?}"
        );
    }

    fn array_field(items: shaperail_core::ItemsSpec) -> shaperail_core::FieldSchema {
        shaperail_core::FieldSchema {
            field_type: shaperail_core::FieldType::Array,
            primary: false,
            generated: false,
            required: false,
            unique: false,
            nullable: false,
            reference: None,
            min: None,
            max: None,
            format: None,
            values: None,
            default: None,
            sensitive: false,
            search: false,
            items: Some(items),
            transient: false,
        }
    }

    fn resource_with_array(
        name: &str,
        field: shaperail_core::FieldSchema,
    ) -> shaperail_core::ResourceDefinition {
        let mut schema = indexmap::IndexMap::new();
        schema.insert(name.to_string(), field);
        shaperail_core::ResourceDefinition {
            resource: "test".to_string(),
            version: 1,
            db: None,
            tenant_key: None,
            schema,
            endpoints: None,
            relations: None,
            indexes: None,
        }
    }

    #[test]
    fn items_nested_array_rejected() {
        let field = array_field(shaperail_core::ItemsSpec::of(
            shaperail_core::FieldType::Array,
        ));
        let rd = resource_with_array("nested", field);
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("nested array") || e.message.contains("type: json")));
    }

    #[test]
    fn items_enum_requires_values() {
        let field = array_field(shaperail_core::ItemsSpec::of(
            shaperail_core::FieldType::Enum,
        ));
        let rd = resource_with_array("flags", field);
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e.message.contains("values")));
    }

    #[test]
    fn items_format_only_on_string() {
        let mut items = shaperail_core::ItemsSpec::of(shaperail_core::FieldType::Integer);
        items.format = Some("email".to_string());
        let field = array_field(items);
        let rd = resource_with_array("nums", field);
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e.message.contains("format")));
    }

    #[test]
    fn items_ref_requires_uuid() {
        let mut items = shaperail_core::ItemsSpec::of(shaperail_core::FieldType::String);
        items.reference = Some("organizations.id".to_string());
        let field = array_field(items);
        let rd = resource_with_array("badrefs", field);
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("ref") && e.message.contains("uuid")));
    }

    #[test]
    fn items_ref_format_must_be_resource_dot_field() {
        let mut items = shaperail_core::ItemsSpec::of(shaperail_core::FieldType::Uuid);
        items.reference = Some("organizations".to_string()); // missing .id
        let field = array_field(items);
        let rd = resource_with_array("orgs", field);
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e.message.contains("resource.field")));
    }

    #[test]
    fn items_uuid_ref_valid() {
        let mut items = shaperail_core::ItemsSpec::of(shaperail_core::FieldType::Uuid);
        items.reference = Some("organizations.id".to_string());
        let field = array_field(items);
        let rd = resource_with_array("tags", field);
        let errors = validate_resource(&rd);
        // No errors related to this field.
        assert!(errors.iter().all(|e| !e.message.contains("tags")));
    }
}