puerto 0.32.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-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
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
//! Name and shape validation shared by the CLI parser and `puerto validar`.
//!
//! These two used to diverge: `parse_field_arg` checked snake_case and nothing else, while
//! `run_validate` re-implemented its own predicates. Anything they both missed — a field called
//! `id`, a field called `type`, an entity called `Error` — reached the generators and produced
//! Rust that does not compile, with the error surfacing in the *generated* project rather than at
//! the command that caused it.
//!
//! Everything here is a pure name predicate. Type-registry checks live in `generators::types`.

use crate::generators::layout;
use crate::puerto_toml::{Field, ValueObjectDefinition};

/// Fields every generated entity already has. A `[[entidad.campos]]` entry with one of these names
/// emits the struct field twice (E0124).
pub const SYSTEM_FIELDS: &[&str] = &["id", "creado_en", "actualizado_en", "borrado", "borrado_en"];

/// Rust keywords, strict and reserved. Field names become struct fields and entity names become
/// module names, so either can land on one.
pub const RUST_KEYWORDS: &[&str] = &[
    "as", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn",
    "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
    "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe",
    "use", "where", "while", "async", "await", "abstract", "become", "box", "do", "final", "gen",
    "macro", "override", "priv", "try", "typeof", "unsized", "virtual", "yield",
];

/// PostgreSQL reserved key words (the "reserved" and "reserved (can be function or type)"
/// categories of the PostgreSQL key word table). Field names become unquoted column names in the
/// generated migration and queries, where any of these is a syntax error — `desc TEXT` broke
/// `sqlx migrate run`. Checked only in `--db` projects.
pub const SQL_RESERVED_WORDS: &[&str] = &[
    "all",
    "analyse",
    "analyze",
    "and",
    "any",
    "array",
    "as",
    "asc",
    "asymmetric",
    "authorization",
    "binary",
    "both",
    "case",
    "cast",
    "check",
    "collate",
    "collation",
    "column",
    "concurrently",
    "constraint",
    "create",
    "cross",
    "current_catalog",
    "current_date",
    "current_role",
    "current_schema",
    "current_time",
    "current_timestamp",
    "current_user",
    "default",
    "deferrable",
    "desc",
    "distinct",
    "do",
    "else",
    "end",
    "except",
    "false",
    "fetch",
    "for",
    "foreign",
    "freeze",
    "from",
    "full",
    "grant",
    "group",
    "having",
    "ilike",
    "in",
    "initially",
    "inner",
    "intersect",
    "into",
    "is",
    "isnull",
    "join",
    "lateral",
    "leading",
    "left",
    "like",
    "limit",
    "localtime",
    "localtimestamp",
    "natural",
    "not",
    "notnull",
    "null",
    "offset",
    "on",
    "only",
    "or",
    "order",
    "outer",
    "overlaps",
    "placing",
    "primary",
    "references",
    "returning",
    "right",
    "select",
    "session_user",
    "similar",
    "some",
    "symmetric",
    "system_user",
    "table",
    "tablesample",
    "then",
    "to",
    "trailing",
    "true",
    "union",
    "unique",
    "user",
    "using",
    "variadic",
    "verbose",
    "when",
    "where",
    "window",
    "with",
];

/// Inner types a shared `[[objeto_valor]]` may wrap.
pub const SHARED_VO_ALLOWED_INNER_TYPES: &[&str] =
    &["String", "i64", "bool", "f64", "Uuid", "DateTime<Utc>"];

/// Type names in scope in generated code. An entity named after one of these produces a struct
/// that shadows it in the same file.
const RESERVED_TYPE_NAMES: &[&str] = &[
    "Self", "String", "Option", "Vec", "Box", "Result", "HashMap", "Uuid", "DateTime", "Utc",
    "Arc", "Error",
];

/// Context names the generated project already occupies: an entity's snake case name is its
/// context, `contextos/{snake}/` (ADR-0023).
const RESERVED_MODULE_NAMES: &[&str] = &[
    "correo", // contextos/correo — the project's mails
];

/// snake_case: lowercase letters, digits and underscores, starting with a letter.
///
/// A leading `_` is rejected: the docs and the error message both say "not starting with a digit,
/// snake_case", and a leading underscore means "deliberately unused" to every Rust reader.
pub fn is_valid_field_name(name: &str) -> bool {
    let mut chars = name.chars();
    match chars.next() {
        Some(c) if c.is_ascii_lowercase() => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}

/// PascalCase: an uppercase letter followed by alphanumerics.
pub fn is_pascal_case(name: &str) -> bool {
    let mut chars = name.chars();
    match chars.next() {
        Some(c) if c.is_ascii_uppercase() => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric())
}

/// Full check for a `[[entidad.campos]]` name.
pub fn validate_field_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("el nombre del campo está vacío".to_string());
    }
    if !is_valid_field_name(name) {
        return Err(format!(
            "nombre de campo inválido '{name}'. Va en snake_case (minúsculas, dígitos y guiones \
             bajos, y empieza por una minúscula)"
        ));
    }
    if SYSTEM_FIELDS.contains(&name) {
        return Err(format!(
            "el nombre de campo '{name}' está reservado: toda entidad ya tiene {}. Quítalo de la \
             lista de campos",
            SYSTEM_FIELDS.join(", ")
        ));
    }
    if RUST_KEYWORDS.contains(&name) {
        return Err(format!(
            "el nombre de campo '{name}' es una palabra clave de Rust y no puede ser un campo de un \
             struct. Elige otro nombre"
        ));
    }
    Ok(())
}

/// A field name that is also a PostgreSQL reserved word — only an error in a `--db` project.
pub fn validate_sql_field_name(name: &str) -> Result<(), String> {
    if SQL_RESERVED_WORDS.contains(&name) {
        return Err(format!(
            "el nombre de campo '{name}' es una palabra reservada de SQL y no puede ser el nombre \
             de una columna. Elige otro nombre (p. ej. '{name}_valor')"
        ));
    }
    Ok(())
}

/// Two fields with the same name are one struct field defined twice (E0124).
pub fn validate_unique_field_names(fields: &[Field]) -> Result<(), String> {
    let mut seen: Vec<&str> = vec![];
    for f in fields {
        if seen.contains(&f.name.as_str()) {
            return Err(format!(
                "el campo '{}' está repetido: cada campo tiene su propio nombre",
                f.name
            ));
        }
        seen.push(&f.name);
    }
    Ok(())
}

/// A use case action becomes a file and module name, and is PascalCased into type names.
pub fn validate_use_case_name(action: &str) -> Result<(), String> {
    if !is_valid_field_name(action) {
        return Err(format!(
            "nombre de caso de uso inválido '{action}'. Va en snake_case (minúsculas, dígitos y \
             guiones bajos, y empieza por una minúscula), p. ej. 'archivar_producto'"
        ));
    }
    if RUST_KEYWORDS.contains(&action) {
        return Err(format!(
            "el caso de uso '{action}' es una palabra clave de Rust. Elige otro nombre"
        ));
    }
    Ok(())
}

/// The modules of a domain crate and the methods of a CRUD entity: a transition's verb is both a
/// module (`dominio/src/<verb>.rs`) and a method (`impl <Entity> { fn <verb> }`).
const TRANSITION_TAKEN: &[&str] = &[
    "crear",
    "obtener",
    "listar",
    "actualizar",
    "borrar",
    "validar",
    "new",
    "from_repositorio",
    "modelo",
    "errores",
    "repositorio",
    "valores",
    "eventos",
    "unit_of_work",
    "pruebas",
];

/// A transition's verb (27.12): snake_case, and none of the names its entity already uses.
pub fn validate_transition_verb(verb: &str) -> Result<(), String> {
    if !is_valid_field_name(verb) {
        return Err(format!(
            "verbo inválido '{verb}'. Va en snake_case e infinitivo, p. ej. 'cancelar' o \
             'poner_a_la_venta'"
        ));
    }
    if RUST_KEYWORDS.contains(&verb) {
        return Err(format!(
            "el verbo '{verb}' es una palabra clave de Rust. Elige otro"
        ));
    }
    if TRANSITION_TAKEN.contains(&verb) {
        return Err(format!(
            "el verbo '{verb}' ya es un caso de uso CRUD, un método o un módulo del dominio de \
             la entidad. Elige otro"
        ));
    }
    Ok(())
}

/// A `[[consumidor]]` name becomes a module (`presentacion/worker/src/consumidores/<name>.rs`), a type
/// (`NotifyNewProduct`) and the `db` transport's consumer column.
pub fn validate_consumer_name(name: &str) -> Result<(), String> {
    if !is_valid_field_name(name) {
        return Err(format!(
            "nombre de consumidor inválido '{name}'. Va en snake_case (minúsculas, dígitos y \
             guiones bajos, y empieza por una minúscula), p. ej. 'avisar_producto_nuevo'"
        ));
    }
    if RUST_KEYWORDS.contains(&name) {
        return Err(format!(
            "el consumidor '{name}' es una palabra clave de Rust. Elige otro nombre"
        ));
    }
    Ok(())
}

/// A `[[correo]]` name becomes two modules (`domain::mail::<name>`, `mail::<name>`), a template
/// folder and the types `{Name}Mail` / `{Name}Mailer`.
pub fn validate_mail_name(name: &str) -> Result<(), String> {
    if !is_valid_field_name(name) {
        return Err(format!(
            "nombre de correo inválido '{name}'. Va en snake_case (minúsculas, dígitos y guiones \
             bajos, y empieza por una minúscula), p. ej. 'bienvenida'"
        ));
    }
    if RUST_KEYWORDS.contains(&name) {
        return Err(format!(
            "el correo '{name}' es una palabra clave de Rust. Elige otro nombre"
        ));
    }
    Ok(())
}

/// The inner type of a shared `[[objeto_valor]]`.
pub fn validate_shared_vo_inner_type(inner_type: &str) -> Result<(), String> {
    if !SHARED_VO_ALLOWED_INNER_TYPES.contains(&inner_type) {
        return Err(format!(
            "el tipo interno '{inner_type}' no vale para un objeto valor compartido (valen: {}; \
             'DateTime' sirve de atajo)",
            SHARED_VO_ALLOWED_INNER_TYPES.join(", ")
        ));
    }
    Ok(())
}

/// What a composite value object's field may be, or its `Option`: what `nucleo` names without a
/// dependency of its own (it has only `thiserror`).
pub const COMPOSITE_PART_TYPES: &[&str] = &["String", "i64", "bool", "f64"];

/// A composite value object (Fase 31: `Direccion { calle, ciudad, cp }`): its fields and nothing
/// else. Each is a plain or `opt:` primitive — one column — with only a name, a type and a label,
/// and no two share a name. `new` is its constructor, so no field's getter may take that name.
pub fn validate_composite_vo(vo: &ValueObjectDefinition) -> Vec<String> {
    let mut errors = vec![];
    if !vo.inner_type.is_empty() {
        errors.push(format!(
            "tiene campos y el tipo '{}': un objeto valor compuesto no tiene tipo",
            vo.inner_type
        ));
    }
    if vo.class.is_some() || vo.example.is_some() {
        errors.push(
            "un objeto valor compuesto no lleva clase ni ejemplo: sus tests usan los valores del \
             registro de cada campo"
                .to_string(),
        );
    }
    for (i, f) in vo.fields.iter().enumerate() {
        if let Err(e) = validate_field_name(&f.name) {
            errors.push(e);
        }
        if f.name == "new" {
            errors.push(
                "un campo no puede llamarse 'new': es el constructor del objeto valor".to_string(),
            );
        }
        let base = f
            .field_type
            .strip_prefix("Option<")
            .and_then(|t| t.strip_suffix('>'))
            .unwrap_or(&f.field_type);
        if !COMPOSITE_PART_TYPES.contains(&base) {
            errors.push(format!(
                "el campo '{}' es un '{}': un campo de un objeto valor compuesto es un primitivo \
                 ({}) o su opt:",
                f.name,
                f.field_type,
                COMPOSITE_PART_TYPES.join(", ")
            ));
        }
        if f.unique
            || f.private
            || f.generated
            || f.value_object.is_some()
            || f.references.is_some()
            || f.default.is_some()
            || f.texts.is_some()
        {
            errors.push(format!(
                "el campo '{}' solo lleva nombre, tipo y etiqueta: un campo de un objeto valor \
                 compuesto no es único, ni privado, ni un objeto valor, ni una referencia, ni lo \
                 pone el servidor",
                f.name
            ));
        }
        if vo.fields[..i].iter().any(|g| g.name == f.name) {
            errors.push(format!("el campo '{}' está repetido", f.name));
        }
    }
    errors
}

/// An entity's owner (27.18): a plain `Uuid` field of an auth project, and none of the use cases that
/// write or read one row is public — there would be no caller to compare with.
pub fn validate_owner(
    snake: &str,
    field: &Field,
    auth: bool,
    public: &[String],
) -> Result<(), String> {
    if !auth {
        return Err(
            "--propietario necesita un proyecto con auth (`puerto nuevo --auth`): el propietario \
             es quien llama"
                .into(),
        );
    }
    let name = &field.name;
    if field.field_type != "Uuid"
        || field.value_object.is_some()
        || field.references.is_some()
        || field.default.is_some()
        || field.generated
    {
        return Err(format!(
            "el propietario '{name}' tiene que ser un campo Uuid sin objeto valor, referencia, \
             por_defecto ni generado"
        ));
    }
    for action in ["create", "get", "update", "delete"] {
        let uc = crate::generators::naming::crud_use_case(action, snake);
        if public.contains(&uc) {
            return Err(format!(
                "'{uc}' es público, pero la entidad tiene propietario: sin sesión no hay a quién \
                 comparar con '{name}'"
            ));
        }
    }
    Ok(())
}

/// A field the server sets (27.17): a `por_defecto` is a variant of its enum or a literal of its
/// `String` (not blank), `i64`, `f64` or `bool`; a `generado` is a unique `String` or its value
/// object, never an enum; a field is not both, nor a reference.
pub fn validate_server_set(field: &Field) -> Result<(), String> {
    let name = &field.name;
    if field.generated && field.default.is_some() {
        return Err(format!(
            "el campo '{name}' es generado y tiene un por_defecto: elige uno de los dos"
        ));
    }
    let set = field.generated || field.default.is_some();
    if set && field.references.is_some() {
        return Err(format!(
            "el campo '{name}' es una referencia: no la pone el servidor"
        ));
    }
    if field.generated
        && (field.field_type != "String"
            || !field.unique
            || crate::generators::types::is_enum_vo(field))
    {
        return Err(format!(
            "el campo '{name}' no puede ser generado: solo un String único (o su objeto valor, no \
             un enum)"
        ));
    }
    if let Some(value) = &field.default {
        let valid = if crate::generators::types::is_enum_vo(field) {
            field
                .enum_variants
                .as_deref()
                .is_some_and(|variants| variants.contains(value))
        } else {
            validate_vo_example(&field.field_type, value).is_ok()
        };
        if !valid {
            return Err(format!(
                "el por_defecto '{value}' del campo '{name}' no es {}",
                if crate::generators::types::is_enum_vo(field) {
                    "una de sus variantes".to_string()
                } else {
                    format!("un valor de tipo '{}'", field.field_type)
                }
            ));
        }
    }
    Ok(())
}

/// A value object's class (27.16): `enum`, or one with a rule, on the primitive that rule reads.
pub fn validate_vo_class(class: &str, inner_type: &str) -> Result<(), String> {
    if class == "enum" {
        return Ok(());
    }
    match crate::puerto_toml::VO_CLASSES
        .iter()
        .find(|(c, _)| *c == class)
    {
        None => Err(format!(
            "la clase '{class}' no existe (valen: enum, {})",
            crate::puerto_toml::VO_CLASSES
                .iter()
                .map(|(c, _)| *c)
                .collect::<Vec<_>>()
                .join(", ")
        )),
        Some((_, ty)) if *ty != inner_type => Err(format!(
            "la clase '{class}' va sobre un {ty}, no sobre '{inner_type}'"
        )),
        Some(_) => Ok(()),
    }
}

/// A shared value object's `ejemplo` (27.15): only for `String` (not blank), `i64`, `f64`
/// (finite) and `bool`, and read as that type — it becomes a literal in the generated tests.
pub fn validate_vo_example(inner_type: &str, example: &str) -> Result<(), String> {
    let valid = match inner_type {
        "String" => !example.trim().is_empty(),
        "i64" => example.parse::<i64>().is_ok(),
        "f64" => example.parse::<f64>().is_ok_and(f64::is_finite),
        "bool" => matches!(example, "true" | "false"),
        _ => {
            return Err(format!(
                "un ejemplo solo vale en un objeto valor String, i64, f64 o bool, no en \
                 '{inner_type}'"
            ));
        }
    };
    if !valid {
        return Err(format!(
            "el ejemplo '{example}' no es un valor de tipo '{inner_type}'"
        ));
    }
    Ok(())
}

/// The `ejemplo` of a field (28.3): only on a local value object over a `String`, an `i64`, an
/// `f64` or a `bool` — not an enum, an `Option`/`Vec` (their tests use none) nor a shared one
/// (its `[[objeto_valor]] ejemplo`) — and a value of that type.
pub fn validate_own_example(
    field: &Field,
    shared_vos: &[ValueObjectDefinition],
) -> Result<(), String> {
    let Some(example) = &field.own_example else {
        return Ok(());
    };
    let name = &field.name;
    if field.value_object.is_none() || field.references.is_some() {
        return Err(format!(
            "ejemplo: '{name}' no tiene objeto valor; un primitivo ya pasa con el valor de sus tests"
        ));
    }
    if crate::generators::types::is_enum_vo(field) {
        return Err(format!(
            "ejemplo: '{name}' es un enum: sus tests ya usan su primera variante"
        ));
    }
    if field.field_type.starts_with("Option<") || field.field_type.starts_with("Vec<") {
        return Err(format!(
            "ejemplo: '{name}' es un Option o un Vec: sus tests no le dan valor"
        ));
    }
    if shared_vos
        .iter()
        .any(|vo| field.value_object.as_ref() == Some(&vo.name))
    {
        return Err(format!(
            "ejemplo: '{name}' usa un objeto valor compartido: su ejemplo es el de su \
             [[objeto_valor]] (`puerto generar objeto-valor … --ejemplo`)"
        ));
    }
    validate_vo_example(&crate::generators::types::vo_inner_type(field), example)
        .map_err(|e| format!("ejemplo: '{name}': {e}"))
}

/// Full check for an entity name, in the PascalCase form the user typed.
pub fn validate_entity_name(pascal: &str) -> Result<(), String> {
    if pascal.is_empty() {
        return Err("el nombre de la entidad está vacío".to_string());
    }
    if !is_pascal_case(pascal) {
        return Err(format!(
            "nombre de entidad inválido '{pascal}'. Va en PascalCase (una mayúscula seguida de \
             letras y dígitos)"
        ));
    }
    if RESERVED_TYPE_NAMES.contains(&pascal) {
        return Err(format!(
            "la entidad '{pascal}' choca con un tipo que usa el código generado. Elige otro nombre"
        ));
    }
    let snake = crate::generators::naming::pascal_to_snake(pascal);
    if RUST_KEYWORDS.contains(&snake.as_str()) {
        return Err(format!(
            "la entidad '{pascal}' da el módulo '{snake}', que es una palabra clave de Rust. Elige \
             otro nombre"
        ));
    }
    if RESERVED_MODULE_NAMES.contains(&snake.as_str()) {
        return Err(format!(
            "la entidad '{pascal}' da el contexto '{snake}', que el proyecto generado ya usa. \
             Elige otro nombre"
        ));
    }
    Ok(())
}

/// Full check for a value object name — local or shared.
pub fn validate_vo_name(vo_name: &str) -> Result<(), String> {
    if vo_name.is_empty() {
        return Err("el nombre del objeto valor está vacío".to_string());
    }
    if !is_pascal_case(vo_name) {
        return Err(format!(
            "nombre de objeto valor inválido '{vo_name}'. Va en PascalCase (una mayúscula seguida \
             de letras y dígitos)"
        ));
    }
    if RESERVED_TYPE_NAMES.contains(&vo_name) {
        return Err(format!(
            "el objeto valor '{vo_name}' choca con un tipo que usa el código generado. Elige otro \
             nombre"
        ));
    }
    Ok(())
}

/// Enum VO variants: PascalCase and distinct. Two identical variants are `enum` arms defined
/// twice (E0428).
pub fn validate_enum_variants(variants: &[String]) -> Result<(), String> {
    if variants.is_empty() {
        return Err("el objeto valor enum no tiene variantes".to_string());
    }
    let mut seen: Vec<&str> = vec![];
    for v in variants {
        if !is_pascal_case(v) {
            return Err(format!(
                "variante de enum inválida '{v}'. Va en PascalCase (una mayúscula seguida de letras y \
                 dígitos)"
            ));
        }
        if seen.contains(&v.as_str()) {
            return Err(format!(
                "la variante '{v}' está repetida: cada variante tiene su propio nombre"
            ));
        }
        seen.push(v);
    }
    Ok(())
}

/// Cross-field checks that need the whole list: one `value_objects.rs` is written per entity, so
/// two fields naming the same VO must agree on its inner type, and a local VO must not contradict
/// a shared one.
pub fn validate_vo_coherence(
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> Vec<String> {
    let mut errors = vec![];
    let mut declared: Vec<(&str, &str)> = vec![];

    for field in fields {
        let Some(vo_name) = field.value_object.as_deref() else {
            continue;
        };
        // Enum VOs carry their shape in `enum_variants`, not in `field_type` (always "String").
        let inner = if field.value_object_kind.as_deref() == Some("enum") {
            "enum"
        } else {
            field.field_type.as_str()
        };

        // Fase 31: a composite one is used as it is, required, and its columns name no other
        // field.
        if !field.parts.is_empty() {
            if field.field_type != vo_name {
                errors.push(format!(
                    "el campo '{}' es un '{}': un objeto valor compuesto es obligatorio y se usa tal \
                     cual, {}:{vo_name}",
                    field.name, field.field_type, field.name
                ));
            }
            if field.unique {
                errors.push(format!(
                    "el campo '{}' es un objeto valor compuesto: no puede ser único",
                    field.name
                ));
            }
            for column in crate::generators::types::columns(field) {
                let taken = fields
                    .iter()
                    .filter(|other| other.name != field.name)
                    .flat_map(crate::generators::types::columns)
                    .any(|c| c.name == column.name);
                if taken {
                    errors.push(format!(
                        "la columna '{}' del campo '{}' ya es el nombre de otro campo",
                        column.name, field.name
                    ));
                }
            }
            continue;
        }

        if let Some((_, previous)) = declared.iter().find(|(n, _)| *n == vo_name) {
            if *previous != inner {
                errors.push(format!(
                    "el objeto valor '{vo_name}' se declara dos veces con tipos internos distintos \
                     ('{previous}' y '{inner}'): un mismo valores.rs no puede definir los dos"
                ));
            }
        } else {
            declared.push((vo_name, inner));
        }

        if let Some(shared) = shared_vos.iter().find(|v| v.name == vo_name)
            && inner != "enum"
            && shared.inner_type != inner
        {
            errors.push(format!(
                "el objeto valor '{vo_name}' está declarado en [[objeto_valor]] con el tipo \
                     '{}', pero el campo '{}' lo usa como '{inner}'",
                shared.inner_type, field.name
            ));
        }
    }

    errors
}

/// Every per-field check that does not need the type registry, for one parsed field.
pub fn validate_field(field: &Field) -> Result<(), String> {
    validate_field_name(&field.name)?;
    if let Some(vo_name) = field.value_object.as_deref() {
        validate_vo_name(vo_name)?;
    }
    if let Some(variants) = &field.enum_variants {
        validate_enum_variants(variants)?;
    }
    if field.references.is_some() {
        validate_reference_shape(field)?;
    }
    if let Some(label) = &field.label
        && !is_screen_text(label)
    {
        return Err(format!(
            "la etiqueta del campo '{}' no puede estar vacía ni llevar comillas, `\\` o saltos \
                 de línea: {label:?}",
            field.name
        ));
    }
    if let Some(texts) = &field.texts {
        if !crate::generators::types::is_enum_vo(field) {
            return Err(format!(
                "los textos del campo '{}' son lo que se lee de cada variante de un enum, y no es \
                 un enum",
                field.name
            ));
        }
        let variants = field.enum_variants.as_deref().unwrap_or_default();
        for (variant, text) in texts {
            if !variants.contains(variant) {
                return Err(format!(
                    "los textos del campo '{}' nombran '{variant}', que no es una de sus variantes \
                     ({})",
                    field.name,
                    variants.join(", ")
                ));
            }
            if !is_screen_text(text) {
                return Err(format!(
                    "los textos del campo '{}': el de '{variant}' no puede estar vacío ni llevar \
                     comillas, `\\` o saltos de línea: {text:?}",
                    field.name
                ));
            }
        }
    }
    Ok(())
}

/// A text the screens write into a string literal: not blank, nothing that would end it.
fn is_screen_text(text: &str) -> bool {
    !text.trim().is_empty() && !text.contains(['"', '\\', '\n', '\r'])
}

/// A reference field on its own (ADR-0022): a PascalCase target, the id's type, not also a value
/// object, and `unique` (one-to-one) only when it is required.
fn validate_reference_shape(field: &Field) -> Result<(), String> {
    let name = &field.name;
    let target = field.references.as_deref().unwrap_or_default();
    if !is_pascal_case(target) {
        return Err(format!(
            "el campo '{name}' referencia '{target}': un nombre de entidad va en PascalCase"
        ));
    }
    if !matches!(
        field.field_type.as_str(),
        "Uuid" | "Option<Uuid>" | "Vec<Uuid>"
    ) {
        return Err(format!(
            "el campo '{name}' referencia {target}, pero su tipo es '{}': una referencia guarda un \
             id, Uuid, Option<Uuid> o Vec<Uuid>",
            field.field_type
        ));
    }
    if field.value_object.is_some() {
        return Err(format!(
            "el campo '{name}' referencia {target} y además nombra un objeto_valor: el tipo de una \
             referencia es el id de {target}"
        ));
    }
    if field.unique && field.field_type.starts_with("Option<") {
        return Err(format!(
            "el campo '{name}' es una referencia opcional y no puede ser único"
        ));
    }
    if field.unique && field.field_type.starts_with("Vec<") {
        return Err(format!(
            "el campo '{name}' es un vec:ref, un conjunto de ids: no puede ser único"
        ));
    }
    if field.field_type.starts_with("Vec<")
        && (field.private || field.generated || field.owner || field.default.is_some())
    {
        return Err(format!(
            "el campo '{name}' es un vec:ref: no es privado, ni lo pone el servidor, ni es el \
             propietario"
        ));
    }
    Ok(())
}

/// The references of entity `pascal`, against the manifest (ADR-0022): each target is another
/// declared CRUD entity, the entity itself when optional (Fase 29), or the auth projects'
/// `Usuario` (Fase 30), which `puerto nuevo --auth` wrote and no `[[entidad]]` declares.
pub fn validate_references(
    pascal: &str,
    fields: &[Field],
    config: &crate::puerto_toml::PuertoConfig,
) -> Vec<String> {
    use crate::generators::naming::{is_crud_entity, pascal_to_snake};

    let mut errors = vec![];
    for field in fields {
        let Some(target) = field.references.as_deref() else {
            continue;
        };
        let name = &field.name;
        // A self reference (Fase 29): the entity is the one being written, and its first row has
        // no parent.
        if target == pascal {
            // A `vec:ref` (Fase 32) to itself is an empty set on the first row.
            if field.field_type == "Uuid" {
                errors.push(format!(
                    "el campo '{name}' referencia a su propia entidad, {target}: una autorreferencia \
                     es opcional, porque la primera fila no tiene a quién apuntar — \
                     `{name}:ref:opt:{target}`"
                ));
            }
            continue;
        }
        if config.project.has_auth() && validate_auth_entity_name(target).is_err() {
            if target != USER_ENTITY {
                errors.push(format!(
                    "el campo '{name}' referencia {target}, que no es una entidad: en un proyecto \
                     con auth, la persona es `{name}:ref:{USER_ENTITY}`"
                ));
            }
            continue;
        }
        match config.entity.iter().find(|e| e.name == target) {
            None => errors.push(format!(
                "el campo '{name}' referencia {target}, que no está declarada en puerto.toml: antes, \
                 `puerto generar scaffold {target}`"
            )),
            Some(entity) if !is_crud_entity(&pascal_to_snake(target), &entity.use_cases) => errors
                .push(format!(
                    "el campo '{name}' referencia {target}, que no es una entidad CRUD: solo una \
                     entidad con sus cinco casos de uso del scaffold tiene un tipo de id y una tabla"
                )),
            Some(_) => {}
        }
    }
    if errors.is_empty()
        && let Some(cycle) = reference_cycle(pascal, fields, config)
    {
        errors.push(format!(
            "{}: esta referencia cierra un ciclo. Cada contexto tiene sus propios crates, y Cargo \
             no compila crates que dependen unos de otros en círculo (ADR-0023 § 3): quita una de \
             las referencias",
            cycle.join(" → ")
        ));
    }
    // Fase 32: a join table's names are Postgres identifiers, which it truncates past 63 bytes —
    // and a truncated constraint no longer matches its `ClaveForanea`.
    if config.project.db {
        use crate::generators::naming::pluralize;
        let snake = pascal_to_snake(pascal);
        let tables: Vec<String> = config
            .entity
            .iter()
            .map(|e| pluralize(&pascal_to_snake(&e.name)))
            .collect();
        for field in fields
            .iter()
            .filter(|f| crate::generators::types::is_vec_reference(f))
        {
            let join = crate::generators::types::join_table(&snake, field);
            for id in [
                &join.table,
                &join.owner_constraint,
                &join.target_constraint,
                &join.index,
            ] {
                if id.len() > 63 {
                    errors.push(format!(
                        "el campo '{}': '{id}' pasa de 63 bytes, lo más largo que admite Postgres \
                         en un nombre: acorta el campo",
                        field.name
                    ));
                }
            }
            if tables.contains(&join.table) {
                errors.push(format!(
                    "el campo '{}': su tabla intermedia, '{}', es la tabla de otra entidad",
                    field.name, join.table
                ));
            }
        }
    }
    errors
}

/// The references, followed from `pascal` (with `fields`, its fields to be) through the other
/// entities' declared ones, back to `pascal`: `["Order", "Customer", "Order"]`, or none.
fn reference_cycle(
    pascal: &str,
    fields: &[Field],
    config: &crate::puerto_toml::PuertoConfig,
) -> Option<Vec<String>> {
    let targets = |entity: &str| -> Vec<String> {
        let fields = if entity == pascal {
            fields
        } else {
            match config.entity.iter().find(|e| e.name == entity) {
                Some(e) => e.fields.as_slice(),
                None => &[],
            }
        };
        // A self reference is no dependency between crates (Fase 29).
        fields
            .iter()
            .filter_map(|f| f.references.clone())
            .filter(|t| t != entity)
            .collect()
    };
    // Depth first, one path at a time; `seen` stops at an entity already explored.
    let mut seen: Vec<String> = vec![];
    let mut stack: Vec<Vec<String>> = vec![vec![pascal.to_string()]];
    while let Some(path) = stack.pop() {
        let last = path.last().cloned().unwrap_or_default();
        for target in targets(&last) {
            if target == pascal {
                let mut cycle = path.clone();
                cycle.push(target);
                return Some(cycle);
            }
            if !seen.contains(&target) {
                seen.push(target.clone());
                let mut next = path.clone();
                next.push(target);
                stack.push(next);
            }
        }
    }
    None
}

/// [`validate_references`], then each target's code on disk: its model (the id type) and, in a
/// `--db` project, its `create_<snake>_table` migration — written earlier, so the foreign key
/// resolves when migrations run in order. Checked by the commands that write an entity.
pub fn validate_references_before_writing(
    pascal: &str,
    fields: &[Field],
    config: &crate::puerto_toml::PuertoConfig,
    base: &std::path::Path,
) -> Result<(), String> {
    use crate::generators::naming::pascal_to_snake;

    let mut errors = validate_references(pascal, fields, config);
    if errors.is_empty() {
        // `Usuario` is `puerto nuevo --auth`'s, not a scaffold's (Fase 30).
        let user = config.project.has_auth().then_some(USER_ENTITY);
        for target in fields
            .iter()
            .filter_map(|f| f.references.as_deref())
            .filter(|t| *t != pascal && Some(*t) != user)
        {
            let snake = pascal_to_snake(target);
            let model = base.join(layout::domain_file(&snake, "modelo"));
            let suffix = format!("_crear_tabla_{snake}.sql");
            let migrated = !config.project.db
                || std::fs::read_dir(base.join(layout::MIGRATIONS_DIR))
                    .into_iter()
                    .flatten()
                    .flatten()
                    .any(|e| e.file_name().to_string_lossy().ends_with(&suffix));
            if !model.exists() || !migrated {
                errors.push(format!(
                    "{pascal} referencia {target}, que aún no tiene código: ejecuta antes \
                     `puerto generar scaffold {target}`"
                ));
            }
        }
    }
    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors.join("\n  "))
    }
}

/// The transports `[proyecto] eventos` can name (ADR-0018 § 4).
pub const EVENT_TRANSPORTS: &[&str] = &["db", "kafka"];

/// The route of the app under a portada: `/` and lowercase segments (`/panel`, `/app/v2`), never
/// `/` alone: that is the portada's.
pub fn validate_app_path(path: &str) -> Result<(), String> {
    let segments: Vec<&str> = match path.strip_prefix('/') {
        Some(rest) => rest.split('/').collect(),
        None => vec![],
    };
    let valid = !segments.is_empty()
        && segments.iter().all(|s| {
            !s.is_empty()
                && s.chars()
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
        });
    if valid {
        return Ok(());
    }
    Err(format!(
        "la ruta de la app '{path}' no vale: empieza por `/` y sigue con minúsculas, dígitos y `-` \
         (p. ej. /panel); `/` a secas es de la portada"
    ))
}

pub fn validate_events_transport(transport: &str) -> Result<(), String> {
    if EVENT_TRANSPORTS.contains(&transport) {
        return Ok(());
    }
    Err(format!(
        "transporte de eventos desconocido '{transport}'. Usa uno de estos: {}",
        EVENT_TRANSPORTS.join(", ")
    ))
}

/// A custom event of entity `snake`, checked against the ones it already declares: snake_case,
/// none of the CRUD events, and a `{Entity}Event` variant of its own (`product_published` and
/// `published` would both be `Published`).
pub fn validate_event_name(snake: &str, event: &str, declared: &[String]) -> Result<(), String> {
    use crate::generators::naming::{crud_events, event_variant};

    if !is_valid_field_name(event) {
        return Err(format!(
            "nombre de evento inválido '{event}'. Va en snake_case y en participio, p. ej. \
             '{snake}_publicado'"
        ));
    }
    let variant = event_variant(snake, event);
    if variant == "Self" {
        return Err(format!("el evento '{event}' daría la variante `Self`"));
    }
    if let Some((_, crud)) = crud_events(snake)
        .into_iter()
        .find(|(crud_variant, crud)| crud == event || *crud_variant == variant)
    {
        return Err(format!(
            "el evento '{event}' choca con '{crud}', que ya registra cada escritura de la entidad"
        ));
    }
    if let Some(existing) = declared
        .iter()
        .find(|d| *d == event || event_variant(snake, d) == variant)
    {
        return Err(format!(
            "el evento '{event}' ya está declarado (como '{existing}')"
        ));
    }
    Ok(())
}

/// The modes `[proyecto] auth` can name (ADR-0021 § 1).
pub const AUTH_MODES: &[&str] = &["oidc", "local"];

pub fn validate_auth_mode(mode: &str) -> Result<(), String> {
    if AUTH_MODES.contains(&mode) {
        return Ok(());
    }
    Err(format!(
        "modo de auth desconocido '{mode}'. Usa uno de estos: {}",
        AUTH_MODES.join(", ")
    ))
}

/// Names an auth project already occupies: its `usuario` context with the `Usuario` entity it is
/// created with, and the APIs of `GET /me` (`ApiMe`) and `/auth/*` (`ApiAuth`).
const AUTH_RESERVED_MODULE_NAMES: &[&str] = &["usuario", "me", "auth"];

/// The entity of an auth project's `usuario` context: what `ref:Usuario` points at (Fase 30).
pub const USER_ENTITY: &str = "Usuario";

/// The entity names an auth project cannot scaffold, on top of [`validate_entity_name`].
pub fn validate_auth_entity_name(pascal: &str) -> Result<(), String> {
    let snake = crate::generators::naming::pascal_to_snake(pascal);
    if AUTH_RESERVED_MODULE_NAMES.contains(&snake.as_str()) {
        return Err(format!(
            "la entidad '{pascal}' da el contexto '{snake}', que un proyecto con auth ya usa (el \
             contexto usuario, la entidad Usuario, GET /me, /auth). Elige otro nombre"
        ));
    }
    Ok(())
}

/// `[a-z][a-z0-9_:-]*` — what `#[requiere_rol]` accepts (`admin`, `billing:read`, `team-lead`).
pub fn validate_role_name(role: &str) -> Result<(), String> {
    let mut chars = role.chars();
    let valid = chars.next().is_some_and(|c| c.is_ascii_lowercase())
        && chars
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | ':' | '-'));
    if !valid {
        return Err(format!(
            "rol inválido '{role}'. Usa minúsculas, dígitos, '_', ':' y '-', y empieza por una \
             letra (p. ej. 'admin', 'facturas:leer')"
        ));
    }
    Ok(())
}

/// An entity's `unicos`: each group names two or more of its own fields, once each, none of them
/// an `Option`, a `Vec` or a map (a null never collides in a unique index; a list or a map is not
/// what a row is told apart by), and no group is listed twice. Its `orden`: each key (`-` for
/// descending) names one of its own plain, required fields, once.
pub fn validate_entity_shape(entity: &crate::puerto_toml::Entity) -> Vec<String> {
    let fields = crate::generators::effective_fields(&entity.fields);
    let mut errors = vec![];
    let mut seen: Vec<Vec<&String>> = vec![];
    for group in &entity.uniques {
        let shown = group.join(", ");
        if group.len() < 2 {
            errors.push(format!(
                "unicos: [{shown}] necesita al menos dos campos; para uno solo, `unico = true` en el \
                 campo"
            ));
        }
        for (i, name) in group.iter().enumerate() {
            match fields.iter().find(|f| &f.name == name) {
                None => errors.push(format!(
                    "unicos: '{name}' no es un campo de {}",
                    entity.name
                )),
                Some(f)
                    if f.field_type.starts_with("Option<")
                        || f.field_type.starts_with("Vec<")
                        || f.field_type.starts_with("HashMap<")
                        || crate::generators::types::is_composite_vo(f) =>
                {
                    errors.push(format!(
                        "unicos: '{name}' es un {}: un único lleva campos simples y obligatorios",
                        f.field_type
                    ));
                }
                Some(_) => {}
            }
            if group[..i].contains(name) {
                errors.push(format!("unicos: [{shown}] nombra '{name}' dos veces"));
            }
        }
        let mut sorted: Vec<&String> = group.iter().collect();
        sorted.sort();
        if seen.contains(&sorted) {
            errors.push(format!("unicos: [{shown}] está dos veces"));
        }
        seen.push(sorted);
    }
    for f in fields.iter().filter(|f| f.private) {
        let text = matches!(f.field_type.as_str(), "String" | "Option<String>");
        // A reference is a `Uuid`: never text.
        if !text || crate::generators::types::is_enum_vo(f) {
            errors.push(format!(
                "privado: '{}' es un {}: un campo privado es texto (String, Option<String> o un \
                 objeto valor sobre uno de ellos, que no sea enum)",
                f.name, f.field_type
            ));
        }
    }
    for (i, key) in entity.order.iter().enumerate() {
        let name = key.strip_prefix('-').unwrap_or(key);
        match fields.iter().find(|f| f.name == name) {
            None if name.is_empty() => errors.push(format!(
                "orden: '{key}' no nombra ningún campo: un campo, o `-` y un campo para el orden \
                 descendente"
            )),
            None => errors.push(format!("orden: '{name}' no es un campo de {}", entity.name)),
            Some(f)
                if f.field_type.starts_with("Option<")
                    || f.field_type.starts_with("Vec<")
                    || f.field_type.starts_with("HashMap<")
                    || crate::generators::types::is_composite_vo(f) =>
            {
                errors.push(format!(
                    "orden: '{name}' es un {}: una lista se ordena por campos simples y obligatorios",
                    f.field_type
                ));
            }
            Some(_) => {}
        }
        let earlier = entity.order[..i]
            .iter()
            .any(|k| k.strip_prefix('-').unwrap_or(k) == name);
        if earlier {
            errors.push(format!("orden: nombra '{name}' dos veces"));
        }
    }
    errors
}

/// An entity's `public` and `roles`: each names one of its use cases, a public route requires no
/// role, and every role is a role name.
pub fn validate_entity_access(entity: &crate::puerto_toml::Entity) -> Vec<String> {
    let mut errors = vec![];
    let names_use_case = |uc: &String| entity.use_cases.contains(uc);
    for (i, uc) in entity.public.iter().enumerate() {
        if !names_use_case(uc) {
            errors.push(format!(
                "publicos: '{uc}' no es uno de los casos de uso de la entidad"
            ));
        }
        if entity.public[..i].contains(uc) {
            errors.push(format!("publicos: '{uc}' está dos veces"));
        }
    }
    for (uc, roles) in &entity.roles {
        if !names_use_case(uc) {
            errors.push(format!(
                "roles: '{uc}' no es uno de los casos de uso de la entidad"
            ));
        }
        if entity.public.contains(uc) {
            errors.push(format!(
                "'{uc}' es público y a la vez exige un rol: una ruta pública no tiene llamante que \
                 comprobar"
            ));
        }
        if roles.is_empty() {
            errors.push(format!(
                "roles: '{uc}' no exige ningún rol: quítalo o nombra uno"
            ));
        }
        for role in roles {
            if let Err(e) = validate_role_name(role) {
                errors.push(format!("roles: '{uc}': {e}"));
            }
        }
    }
    // 27.13: an internal use case has no route — nothing to open, nothing to guard.
    let crud = crate::generators::naming::crud_use_cases(
        &crate::generators::naming::pascal_to_snake(&entity.name),
    );
    for uc in &entity.internal {
        if !names_use_case(uc) {
            errors.push(format!(
                "internos: '{uc}' no es uno de los casos de uso de la entidad"
            ));
        } else if crud.contains(uc) {
            errors.push(format!(
                "internos: '{uc}' es un caso de uso CRUD: su ruta está en rutas.rs"
            ));
        }
        if entity.public.contains(uc) || entity.roles.contains_key(uc) {
            errors.push(format!(
                "'{uc}' es interno: no tiene ruta, así que no va en publicos ni en roles"
            ));
        }
    }
    // 28.2: what only the role reaches is something the owner would reach otherwise.
    let owner_checked =
        crate::generators::auth::owner_checked_use_cases(&crate::puerto_toml::Entity {
            role_only: vec![],
            ..entity.clone()
        });
    for (i, uc) in entity.role_only.iter().enumerate() {
        if entity.owner.is_none() {
            errors.push(format!(
                "solo_rol: '{uc}': la entidad no tiene propietario (--propietario); sin él, una \
                 ruta con rol ya solo deja pasar a quien lo tiene"
            ));
            continue;
        }
        if !owner_checked.contains(uc) {
            errors.push(format!(
                "solo_rol: '{uc}' no es obtener, listar, actualizar, borrar ni una transición con \
                 ruta: solo en ellos pasa el propietario"
            ));
        }
        if entity.roles.get(uc).is_none_or(|roles| roles.is_empty()) {
            errors.push(format!(
                "solo_rol: '{uc}' no exige ningún rol en roles: nadie podría llamarlo. Dale uno \
                 con --rol {uc}=<rol>"
            ));
        }
        if entity.role_only[..i].contains(uc) {
            errors.push(format!("solo_rol: '{uc}' está dos veces"));
        }
    }
    errors
}

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

    #[test]
    fn an_owner_is_a_plain_uuid_of_an_auth_project_whose_rows_are_never_public() {
        let owner = |f: Field| validate_owner("entrada", &f, true, &[]);
        let uuid = Field {
            name: "comprador_id".into(),
            field_type: "Uuid".into(),
            ..Default::default()
        };
        assert!(owner(uuid.clone()).is_ok());
        for wrong in [
            Field {
                field_type: "String".into(),
                ..uuid.clone()
            },
            Field {
                value_object: Some("Comprador".into()),
                ..uuid.clone()
            },
            Field {
                references: Some("Cliente".into()),
                ..uuid.clone()
            },
            Field {
                default: Some("x".into()),
                ..uuid.clone()
            },
            Field {
                generated: true,
                ..uuid.clone()
            },
        ] {
            assert!(owner(wrong.clone()).is_err(), "{wrong:?}");
        }
        assert!(
            validate_owner("entrada", &uuid, false, &[]).is_err(),
            "no auth"
        );
        assert!(validate_owner("entrada", &uuid, true, &["obtener_entrada".into()]).is_err());
        assert!(validate_owner("entrada", &uuid, true, &["listar_entradas".into()]).is_ok());
    }

    #[test]
    fn rejects_system_field_names() {
        for name in SYSTEM_FIELDS {
            assert!(
                validate_field_name(name).is_err(),
                "'{name}' must be rejected"
            );
        }
    }

    #[test]
    fn rejects_rust_keyword_field_names() {
        assert!(validate_field_name("type").is_err());
        assert!(validate_field_name("match").is_err());
        assert!(validate_field_name("move").is_err());
    }

    #[test]
    fn rejects_leading_underscore_field_name() {
        assert!(validate_field_name("_hidden").is_err());
    }

    #[test]
    fn accepts_ordinary_field_names() {
        assert!(validate_field_name("title").is_ok());
        assert!(validate_field_name("unit_price_2").is_ok());
    }

    #[test]
    fn rejects_entity_names_that_collide_with_generated_code() {
        assert!(validate_entity_name("Error").is_err());
        assert!(validate_entity_name("String").is_err());
        assert!(validate_entity_name("Correo").is_err()); // contextos/correo holds the mails
        assert!(validate_entity_name("Type").is_err()); // module would be `type`
        assert!(validate_entity_name("Product").is_ok());
    }

    #[test]
    fn rejects_duplicate_enum_variants() {
        let variants = vec!["Active".to_string(), "Active".to_string()];
        assert!(validate_enum_variants(&variants).is_err());
    }

    #[test]
    fn rejects_same_vo_name_with_two_inner_types() {
        let fields = vec![
            Field {
                name: "a".into(),
                field_type: "String".into(),
                value_object: Some("Code".into()),
                ..Default::default()
            },
            Field {
                name: "b".into(),
                field_type: "i64".into(),
                value_object: Some("Code".into()),
                ..Default::default()
            },
        ];
        assert_eq!(validate_vo_coherence(&fields, &[]).len(), 1);
    }

    #[test]
    fn accepts_same_vo_name_with_matching_inner_type() {
        let fields = vec![
            Field {
                name: "a".into(),
                field_type: "String".into(),
                value_object: Some("Code".into()),
                ..Default::default()
            },
            Field {
                name: "b".into(),
                field_type: "String".into(),
                value_object: Some("Code".into()),
                ..Default::default()
            },
        ];
        assert!(validate_vo_coherence(&fields, &[]).is_empty());
    }

    #[test]
    fn rejects_a_field_that_uses_a_shared_vo_with_another_inner_type() {
        let shared = vec![ValueObjectDefinition {
            name: "Email".into(),
            inner_type: "String".into(),
            ..Default::default()
        }];
        let fields = vec![Field {
            name: "email".into(),
            field_type: "i64".into(),
            value_object: Some("Email".into()),
            ..Default::default()
        }];

        let errors = validate_vo_coherence(&fields, &shared);

        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(errors[0].contains("Email"));
    }

    #[test]
    fn accepts_a_field_that_uses_a_shared_vo_with_its_inner_type() {
        let shared = vec![ValueObjectDefinition {
            name: "Email".into(),
            inner_type: "String".into(),
            ..Default::default()
        }];
        let fields = vec![Field {
            name: "email".into(),
            field_type: "String".into(),
            value_object: Some("Email".into()),
            ..Default::default()
        }];

        assert!(validate_vo_coherence(&fields, &shared).is_empty());
    }

    #[test]
    fn accepts_an_enum_vo_named_like_a_shared_vo() {
        // Enum VOs are always `String`-typed in the manifest; their shape lives in the variants.
        let shared = vec![ValueObjectDefinition {
            name: "Status".into(),
            inner_type: "i64".into(),
            ..Default::default()
        }];
        let fields = vec![Field {
            name: "status".into(),
            field_type: "String".into(),
            value_object: Some("Status".into()),
            value_object_kind: Some("enum".into()),
            enum_variants: Some(vec!["Active".into()]),
            ..Default::default()
        }];

        assert!(validate_vo_coherence(&fields, &shared).is_empty());
    }
    // ── Phase 16.4: auth ─────────────────────────────────────────────────────

    #[test]
    fn should_accept_the_auth_modes_and_reject_any_other() {
        assert!(validate_auth_mode("oidc").is_ok());
        assert!(validate_auth_mode("local").is_ok());
        for mode in ["", "OIDC", "auth0", "keycloak"] {
            assert!(validate_auth_mode(mode).is_err(), "{mode}");
        }
    }

    #[test]
    fn should_reserve_the_auth_modules_when_naming_an_entity_of_an_auth_project() {
        for name in ["Usuario", "Me", "Auth"] {
            assert!(validate_auth_entity_name(name).is_err(), "{name}");
        }
        for name in ["Usuarios", "UsuarioPerfil", "User", "Author", "Producto"] {
            assert!(validate_auth_entity_name(name).is_ok(), "{name}");
        }
    }

    #[test]
    fn should_accept_role_names_the_macro_accepts() {
        for role in ["admin", "a", "billing:read", "team-lead", "level_2"] {
            assert!(validate_role_name(role).is_ok(), "{role}");
        }
        for role in ["", "Admin", "1admin", "ad min", "_admin", "admin!"] {
            assert!(validate_role_name(role).is_err(), "{role}");
        }
    }

    fn product(public: &[&str], roles: &[(&str, &[&str])]) -> crate::puerto_toml::Entity {
        crate::puerto_toml::Entity {
            name: "Product".into(),
            use_cases: vec!["crear_product".into(), "listar_products".into()],
            public: public.iter().map(|s| s.to_string()).collect(),
            roles: roles
                .iter()
                .map(|(uc, roles)| {
                    (
                        uc.to_string(),
                        roles.iter().map(|r| r.to_string()).collect(),
                    )
                })
                .collect(),
            ..Default::default()
        }
    }

    #[test]
    fn should_accept_public_and_roles_when_they_name_distinct_use_cases() {
        let entity = product(&["listar_products"], &[("crear_product", &["admin"])]);
        assert_eq!(validate_entity_access(&entity), Vec::<String>::new());
    }

    #[test]
    fn should_reject_public_and_roles_when_they_name_no_use_case_of_the_entity() {
        let entity = product(&["obtener_product"], &[("borrar_product", &["admin"])]);
        let errors = validate_entity_access(&entity);
        assert_eq!(errors.len(), 2, "{errors:?}");
        assert!(
            errors[0].contains("'obtener_product' no es uno de"),
            "{errors:?}"
        );
        assert!(
            errors[1].contains("'borrar_product' no es uno de"),
            "{errors:?}"
        );
    }

    #[test]
    fn should_reject_a_use_case_when_it_is_both_public_and_role_protected() {
        let entity = product(&["crear_product"], &[("crear_product", &["admin"])]);
        let errors = validate_entity_access(&entity);
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(
            errors[0].contains("es público y a la vez exige un rol"),
            "{errors:?}"
        );
    }

    #[test]
    fn should_reject_roles_when_they_are_empty_or_not_role_names() {
        let errors = validate_entity_access(&product(&[], &[("crear_product", &[])]));
        assert!(errors[0].contains("no exige ningún rol"), "{errors:?}");
        let errors = validate_entity_access(&product(&[], &[("crear_product", &["Admin"])]));
        assert!(errors[0].contains("rol inválido 'Admin'"), "{errors:?}");
    }

    #[test]
    fn should_reject_a_public_use_case_when_it_is_listed_twice() {
        let errors = validate_entity_access(&product(&["listar_products", "listar_products"], &[]));
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(errors[0].contains("está dos veces"), "{errors:?}");
    }

    #[test]
    fn should_name_the_cycle_a_reference_would_close() {
        // Arrange: Customer → Region already; Region gains a reference back to Customer.
        let reference = |name: &str, target: &str| Field {
            name: name.to_string(),
            field_type: "Uuid".to_string(),
            references: Some(target.to_string()),
            ..Field::default()
        };
        let crud = |name: &str, snake: &str, _plural: &str, fields: Vec<Field>| {
            crate::puerto_toml::Entity {
                name: name.to_string(),
                use_cases: crate::generators::naming::crud_use_cases(snake),
                fields,
                ..Default::default()
            }
        };
        let config = crate::puerto_toml::PuertoConfig {
            entity: vec![
                crud(
                    "Customer",
                    "customer",
                    "customers",
                    vec![reference("region_id", "Region")],
                ),
                crud("Region", "region", "regions", vec![]),
            ],
            ..Default::default()
        };

        // Act
        let errors = validate_references("Region", &[reference("owner_id", "Customer")], &config);

        // Assert
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(
            errors[0].starts_with("Region → Customer → Region"),
            "{}",
            errors[0]
        );
    }
}