apiplant-core 0.1.0

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

use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::Path;

/// A fully-parsed resource definition.
#[derive(Debug, Clone, Deserialize)]
pub struct Resource {
    #[serde(rename = "resource")]
    pub meta: ResourceMeta,
    /// Ordered map so generated columns/endpoints are deterministic.
    #[serde(default)]
    pub fields: BTreeMap<String, Field>,
    #[serde(default)]
    pub permissions: Permissions,
    /// Named functions to run around each CRUD operation.
    #[serde(default)]
    pub hooks: Hooks,
    /// Optional auth configuration; only meaningful on the `user` resource.
    #[serde(default)]
    pub auth: Option<AuthSpec>,
    /// How (and whether) this resource appears in the generated admin dashboard.
    #[serde(default)]
    pub admin: ResourceAdmin,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ResourceMeta {
    pub name: String,
    /// Physical table name; defaults to `apiplant_<name>` when omitted.
    pub table: Option<String>,
    /// Add `created_at` / `updated_at` columns (default true).
    #[serde(default = "yes")]
    pub timestamps: bool,
    /// Column used for `owner` permission checks (default `owner_id`).
    #[serde(default = "default_owner_field")]
    pub owner_field: String,
    /// Tenancy: `organization` (default — rows belong to an org and are isolated)
    /// or `global` (shared across the whole deployment).
    #[serde(default = "default_scope")]
    pub scope: Scope,
}

fn yes() -> bool {
    true
}
fn default_owner_field() -> String {
    "owner_id".to_string()
}
fn default_scope() -> Scope {
    Scope::Organization
}

impl Resource {
    /// Physical table name.
    pub fn table_name(&self) -> String {
        self.meta
            .table
            .clone()
            .unwrap_or_else(|| format!("apiplant_{}", self.meta.name))
    }

    /// The function bound to a lifecycle event, if any.
    pub fn hook(&self, event: HookEvent) -> Option<&str> {
        self.hooks.get(event)
    }

    /// The function bound to an auth event, if any. Only meaningful on the
    /// `user` resource, which owns the built-in auth endpoints.
    pub fn auth_hook(&self, event: AuthEvent) -> Option<&str> {
        self.hooks.get_auth(event)
    }

    /// Validate internal consistency (called after loading).
    pub fn validate(&self) -> crate::Result<()> {
        for (event, function) in self.hooks.iter() {
            if function.trim().is_empty() {
                return Err(crate::Error::Schema {
                    resource: self.meta.name.clone(),
                    message: format!("hook `{}` names an empty function", event.as_str()),
                });
            }
        }
        for (event, function) in self.hooks.auth_iter() {
            if function.trim().is_empty() {
                return Err(crate::Error::Schema {
                    resource: self.meta.name.clone(),
                    message: format!("hook `{}` names an empty function", event.as_str()),
                });
            }
            // Only `user` has auth endpoints to hook, so the same key on any
            // other resource is a function that would never be called.
            if self.meta.name != "user" {
                return Err(crate::Error::Schema {
                    resource: self.meta.name.clone(),
                    message: format!(
                        "hook `{}` only exists on the `user` resource, which owns the auth endpoints",
                        event.as_str()
                    ),
                });
            }
        }
        for (fname, field) in &self.fields {
            if fname == "id" {
                return Err(crate::Error::Schema {
                    resource: self.meta.name.clone(),
                    message: "`id` is reserved and added automatically".into(),
                });
            }
            if field.ty == FieldType::Reference && field.references.is_none() {
                return Err(crate::Error::Schema {
                    resource: self.meta.name.clone(),
                    message: format!("field `{fname}` is a reference without `references`"),
                });
            }
            if field.admin.format != ContentFormat::Plain
                && !matches!(field.ty, FieldType::Text | FieldType::String)
            {
                return Err(crate::Error::Schema {
                    resource: self.meta.name.clone(),
                    message: format!(
                        "field `{fname}` sets [admin] format = \"{}\" but is not a text field",
                        field.admin.format.as_str()
                    ),
                });
            }
        }
        // `[admin]` is presentation, so a typo here is silent rather than
        // dangerous — but it is still a typo, and naming a column that does not
        // exist is never what anyone meant.
        for column in &self.admin.columns {
            if !self.fields.contains_key(column) && column != "id" {
                return Err(crate::Error::Schema {
                    resource: self.meta.name.clone(),
                    message: format!("[admin] columns names unknown field `{column}`"),
                });
            }
        }
        for (key, declared) in [
            ("display_field", &self.admin.display_field),
            ("search_field", &self.admin.search_field),
        ] {
            if let Some(field) = declared {
                let Some(declared_field) = self.fields.get(field) else {
                    return Err(crate::Error::Schema {
                        resource: self.meta.name.clone(),
                        message: format!("[admin] {key} names unknown field `{field}`"),
                    });
                };
                // The search box matches substrings, which only a text column
                // can do — a search field of another type would be a box that
                // answers 400 to every keystroke.
                if key == "search_field"
                    && !matches!(declared_field.ty, FieldType::String | FieldType::Text)
                {
                    return Err(crate::Error::Schema {
                        resource: self.meta.name.clone(),
                        message: format!(
                            "[admin] search_field names `{field}`, which is not a text field and cannot be searched"
                        ),
                    });
                }
            }
        }
        Ok(())
    }

    /// Human label for a single record, e.g. `"Purchase order"`.
    pub fn admin_label(&self) -> String {
        self.admin
            .label
            .clone()
            .unwrap_or_else(|| titleize(&self.meta.name))
    }

    /// Human label for the collection, e.g. `"Purchase orders"`.
    pub fn admin_plural(&self) -> String {
        self.admin
            .plural
            .clone()
            .unwrap_or_else(|| pluralize(&self.admin_label()))
    }

    /// The field whose value names a record in tables, pickers and headings.
    ///
    /// An explicit `display_field` wins; otherwise the first conventionally
    /// named field (`name`, `title`, …), then the first plain string field, and
    /// finally `None` — at which point the dashboard falls back to the id.
    pub fn admin_display_field(&self) -> Option<String> {
        if let Some(declared) = &self.admin.display_field {
            if self.fields.contains_key(declared) {
                return Some(declared.clone());
            }
        }
        const PREFERRED: [&str; 7] = ["name", "title", "label", "slug", "code", "number", "email"];
        for candidate in PREFERRED {
            if let Some(field) = self.fields.get(candidate) {
                if !field.hidden && matches!(field.ty, FieldType::String | FieldType::Text) {
                    return Some(candidate.to_string());
                }
            }
        }
        self.fields
            .iter()
            .find(|(_, field)| !field.hidden && field.ty == FieldType::String)
            .map(|(name, _)| name.clone())
    }

    /// The field the dashboard's list search box filters on.
    ///
    /// Always a `string` or `text` column, because searching means matching
    /// part of a value: a `display_field` of another type names records
    /// perfectly well and simply leaves the resource without a search box.
    pub fn admin_search_field(&self) -> Option<String> {
        let candidate = match &self.admin.search_field {
            Some(declared) if self.fields.contains_key(declared) => Some(declared.clone()),
            Some(_) | None => self.admin_display_field(),
        };
        candidate.filter(|name| {
            self.fields
                .get(name)
                .is_some_and(|field| matches!(field.ty, FieldType::String | FieldType::Text))
        })
    }

    /// The columns the list table shows, in order.
    ///
    /// Declared `columns` win. Otherwise: the display field first, then up to
    /// four more dashboard-visible fields, skipping `json`/`text` blobs (which
    /// never read well in a cell) and the tenancy column.
    pub fn admin_columns(&self) -> Vec<String> {
        let declared: Vec<String> = self
            .admin
            .columns
            .iter()
            .filter(|name| self.fields.contains_key(*name))
            .cloned()
            .collect();
        if !declared.is_empty() {
            return declared;
        }

        let display = self.admin_display_field();
        let mut columns: Vec<String> = display.iter().cloned().collect();
        for (name, field) in &self.fields {
            if columns.len() >= 5 {
                break;
            }
            let skip = field.hidden
                || !field.admin.visible
                || Some(name) == display.as_ref()
                || name == "organization_id"
                || matches!(field.ty, FieldType::Json | FieldType::Text);
            if !skip {
                columns.push(name.clone());
            }
        }
        columns
    }

    /// All `belongs_to` references declared by this resource's fields.
    pub fn references(&self) -> Vec<Reference> {
        self.fields
            .iter()
            .filter_map(|(name, field)| {
                if field.ty != FieldType::Reference {
                    return None;
                }
                let target = field.references.clone()?;
                Some(Reference {
                    field: name.clone(),
                    target,
                    relation: relation_name(name).to_string(),
                    on_delete: field.on_delete.unwrap_or(OnDelete::Restrict),
                    required: field.required,
                })
            })
            .collect()
    }

    /// Find the reference exposed under a given relation name (`"owner"`).
    pub fn reference_by_relation(&self, relation: &str) -> Option<Reference> {
        self.references()
            .into_iter()
            .find(|r| r.relation == relation)
    }

    /// Whether this resource is isolated per organisation (the default).
    pub fn is_org_scoped(&self) -> bool {
        self.meta.scope == Scope::Organization
    }

    /// The column that carries this resource's organisation, if any:
    /// `organization_id` for org-scoped resources, `id` for the `organization`
    /// resource itself (its rows *are* organisations), else `None`.
    pub fn org_column(&self) -> Option<&'static str> {
        if self.is_org_scoped() {
            Some("organization_id")
        } else if self.meta.name == "organization" {
            Some("id")
        } else {
            None
        }
    }

    /// Load and validate a single resource file.
    pub fn load(path: &Path) -> crate::Result<Self> {
        let text = std::fs::read_to_string(path).map_err(|e| crate::Error::Io {
            path: path.to_path_buf(),
            source: e,
        })?;
        // Model files get the same `$VAR` expansion `main.toml` does — a
        // resource can name an environment variable anywhere it takes a string.
        let source = path.file_name().unwrap_or_default().to_string_lossy();
        let resource: Resource =
            crate::env::parse_toml(&text, &source).map_err(|e| crate::Error::Toml {
                path: path.to_path_buf(),
                source: e,
            })?;
        resource.validate()?;
        Ok(resource)
    }
}

/// The `[admin]` section of a resource: how it is presented — and to whom — in
/// the generated dashboard.
///
/// This is **presentation only**. Hiding a resource from the dashboard does not
/// make its API endpoints any less reachable; that is what
/// [`Permissions`] is for. The two are deliberately separate: `[permissions]`
/// decides what the API allows, `[admin]` decides what an operator is shown.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ResourceAdmin {
    /// Show this resource in the dashboard. Unset means "decide from the
    /// resource" — see [`ResourceAdmin::is_visible`].
    pub visible: Option<bool>,
    /// Organisation roles that may see it. Empty means "anyone who can list it"
    /// — the API remains the authority either way.
    pub roles: Vec<String>,
    /// Human label for one record ("Product"). Defaults to the resource name.
    pub label: Option<String>,
    /// Human label for the collection ("Products"). Defaults to `label` + "s".
    pub plural: Option<String>,
    /// Sidebar group heading ("Catalogue"). Ungrouped resources sort last.
    pub group: Option<String>,
    /// Which field to render when a record is named — in tables, in reference
    /// pickers, in breadcrumbs. Defaults to the first sensible string field.
    pub display_field: Option<String>,
    /// Columns to show in the list table, in order. Empty means "pick for me".
    pub columns: Vec<String>,
    /// Field the list search box filters on. Defaults to `display_field`.
    pub search_field: Option<String>,
    /// Sort key within the sidebar group; lower comes first.
    pub order: i64,
}

impl ResourceAdmin {
    /// Whether the named resource appears in the dashboard's resource
    /// navigation.
    ///
    /// An explicit `visible` always wins. Otherwise the auth resources default
    /// to hidden — they are managed through purpose-built screens (account,
    /// team, organisation, API keys), and a raw table of `membership` rows is
    /// exactly the developer-facing surface the dashboard is meant to avoid.
    pub fn is_visible(&self, resource_name: &str) -> bool {
        self.visible.unwrap_or(!is_auth_resource(resource_name))
    }
}

/// Whether a resource is one of the built-in auth/tenancy resources, which the
/// dashboard manages through dedicated screens instead of generic CRUD.
pub fn is_auth_resource(name: &str) -> bool {
    matches!(
        name,
        "user" | "organization" | "membership" | "membership_role" | "api_key" | "oauth_connection"
    )
}

/// Per-field dashboard presentation, from `[fields.<name>.admin]`.
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct FieldAdmin {
    /// Show this field in the dashboard at all. Hidden fields are still part of
    /// the API (unlike [`Field::hidden`]).
    pub visible: bool,
    /// Show the field but refuse edits.
    pub readonly: bool,
    /// Human label. Defaults to a title-cased field name.
    pub label: Option<String>,
    /// One line of guidance shown under the input.
    pub help: Option<String>,
    /// Input to render. `auto` picks from the field's type.
    pub widget: Widget,
    /// Allowed values, turning the input into a dropdown. Each entry may be
    /// `"value"` or `"value|Label"`.
    pub options: Vec<String>,
    /// Placeholder text for free-text inputs.
    pub placeholder: Option<String>,
    /// What the stored text *is*, for `text`/`string` fields. Purely a
    /// presentation hint: the dashboard highlights and previews the markup,
    /// and the API stores and returns the same characters either way.
    pub format: ContentFormat,
}

impl Default for FieldAdmin {
    fn default() -> Self {
        FieldAdmin {
            visible: true,
            readonly: false,
            label: None,
            help: None,
            widget: Widget::Auto,
            options: Vec::new(),
            placeholder: None,
            format: ContentFormat::Plain,
        }
    }
}

/// What kind of content a free-text field holds.
///
/// Nothing about storage changes — this only tells the dashboard whether to
/// give the editor markup highlighting and a live preview.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContentFormat {
    /// Ordinary text, edited in a plain textarea (the default).
    #[default]
    Plain,
    Markdown,
    Html,
}

impl ContentFormat {
    pub fn as_str(self) -> &'static str {
        match self {
            ContentFormat::Plain => "plain",
            ContentFormat::Markdown => "markdown",
            ContentFormat::Html => "html",
        }
    }
}

/// The input a field is edited with in the dashboard.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Widget {
    /// Derive the input from the field's type (the default).
    Auto,
    Text,
    Textarea,
    Select,
    Email,
    Url,
    Password,
    Color,
    Date,
    DateTime,
    Json,
    Switch,
}

impl Widget {
    pub fn as_str(self) -> &'static str {
        match self {
            Widget::Auto => "auto",
            Widget::Text => "text",
            Widget::Textarea => "textarea",
            Widget::Select => "select",
            Widget::Email => "email",
            Widget::Url => "url",
            Widget::Password => "password",
            Widget::Color => "color",
            Widget::Date => "date",
            Widget::DateTime => "date_time",
            Widget::Json => "json",
            Widget::Switch => "switch",
        }
    }
}

/// One column in a resource.
#[derive(Debug, Clone, Deserialize)]
pub struct Field {
    #[serde(rename = "type")]
    pub ty: FieldType,
    /// Target resource name when `ty == Reference`.
    #[serde(default)]
    pub references: Option<String>,
    #[serde(default)]
    pub required: bool,
    #[serde(default)]
    pub unique: bool,
    /// Exclude from API responses (e.g. password hashes).
    #[serde(default)]
    pub hidden: bool,
    /// Optional default rendered as a SQL literal.
    #[serde(default)]
    pub default: Option<serde_json::Value>,
    pub max_length: Option<u32>,
    /// For `reference` fields: what happens to this row when the referenced row
    /// is deleted. Defaults to [`OnDelete::Restrict`] (safe: blocks orphaning).
    #[serde(default)]
    pub on_delete: Option<OnDelete>,
    /// Dashboard presentation for this field, from `[fields.<name>.admin]`.
    #[serde(default)]
    pub admin: FieldAdmin,
}

/// Supported column types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FieldType {
    String,
    Text,
    Integer,
    BigInt,
    Float,
    Boolean,
    Uuid,
    Timestamp,
    Json,
    /// Foreign key; see [`Field::references`].
    Reference,
}

/// Referential action applied by a foreign key when the parent row is deleted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnDelete {
    /// Block the parent delete while children exist (default).
    Restrict,
    /// Null out this reference (requires a nullable column).
    SetNull,
    /// Delete this row too.
    Cascade,
    /// No referential action.
    NoAction,
}

impl OnDelete {
    pub fn to_sql(self) -> &'static str {
        match self {
            OnDelete::Restrict => "RESTRICT",
            OnDelete::SetNull => "SET NULL",
            OnDelete::Cascade => "CASCADE",
            OnDelete::NoAction => "NO ACTION",
        }
    }
}

/// A resolved `belongs_to` edge: the referencing field, its target resource, and
/// the JSON key it expands under (`owner_id` → `owner`).
#[derive(Debug, Clone)]
pub struct Reference {
    pub field: String,
    pub target: String,
    pub relation: String,
    pub on_delete: OnDelete,
    pub required: bool,
}

/// The relation name a reference field expands under: `owner_id` → `owner`,
/// otherwise the field name unchanged.
pub fn relation_name(field: &str) -> &str {
    field.strip_suffix("_id").unwrap_or(field)
}

/// `"purchase_order"` → `"Purchase order"`. Sentence case, not title case: a
/// dashboard full of Capitalised Nouns reads like a form, not an application.
pub fn titleize(name: &str) -> String {
    let spaced = name.trim_end_matches("_id").replace('_', " ");
    let mut chars = spaced.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
        None => spaced,
    }
}

/// A deliberately small English pluraliser — enough for the labels apiplant
/// generates, and overridable per resource with `[admin] plural`.
pub fn pluralize(label: &str) -> String {
    let lower = label.to_lowercase();
    if lower.ends_with('s')
        || lower.ends_with("x")
        || lower.ends_with("ch")
        || lower.ends_with("sh")
    {
        format!("{label}es")
    } else if lower.ends_with('y')
        && !lower.ends_with("ay")
        && !lower.ends_with("ey")
        && !lower.ends_with("oy")
        && !lower.ends_with("uy")
    {
        format!("{}ies", &label[..label.len() - 1])
    } else {
        format!("{label}s")
    }
}

/// Whether a resource is isolated per organisation (the default) or shared
/// across the whole deployment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Scope {
    /// Rows belong to an organisation; every request is scoped to the caller's
    /// active organisation and `organization_id` is enforced automatically.
    Organization,
    /// Not tenant-scoped — shared by everyone, governed only by `[permissions]`.
    Global,
}

/// Access policy for a single action on a resource.
///
/// On an organisation-scoped resource, org membership is always required and
/// queries are already filtered to the caller's active organisation; these
/// levels then decide *who among the members* may act. `Role` is an
/// **organisation** role (from the caller's membership), not a global one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Access {
    /// No auth required. Only meaningful on `global` resources; on an
    /// org-scoped resource it is treated like `member`.
    Public,
    /// Any authenticated principal (⇒ any member, on an org-scoped resource).
    Authenticated,
    /// Any member of the (active) organisation.
    Member,
    /// A member holding the named role **within the organisation**.
    Role(String),
    /// The principal must own the row (owner_field == principal id).
    Owner,
    /// Never exposed.
    Private,
}

impl Access {
    /// Parse the string form used in TOML (`"public"`, `"member"`, `"role:admin"`, …).
    pub fn parse(s: &str) -> Access {
        match s {
            "public" => Access::Public,
            "authenticated" => Access::Authenticated,
            "member" => Access::Member,
            "owner" => Access::Owner,
            "private" => Access::Private,
            other => other
                .strip_prefix("role:")
                .map(|role| Access::Role(role.to_string()))
                .unwrap_or(Access::Private),
        }
    }
}

/// Per-action permissions. Strings in TOML are parsed via [`Access::parse`].
#[derive(Debug, Clone, Deserialize)]
#[serde(from = "PermissionsRaw")]
pub struct Permissions {
    pub list: Access,
    pub read: Access,
    pub create: Access,
    pub update: Access,
    pub delete: Access,
}

impl Default for Permissions {
    fn default() -> Self {
        // Multitenant-by-default: every action is limited to members of the
        // caller's organisation. On a `global` resource, `member` behaves like
        // `authenticated` (there is no org to belong to).
        Permissions {
            list: Access::Member,
            read: Access::Member,
            create: Access::Member,
            update: Access::Member,
            delete: Access::Member,
        }
    }
}

#[derive(Deserialize)]
struct PermissionsRaw {
    list: Option<String>,
    read: Option<String>,
    create: Option<String>,
    update: Option<String>,
    delete: Option<String>,
}

impl From<PermissionsRaw> for Permissions {
    fn from(r: PermissionsRaw) -> Self {
        let d = Permissions::default();
        Permissions {
            list: r.list.map(|s| Access::parse(&s)).unwrap_or(d.list),
            read: r.read.map(|s| Access::parse(&s)).unwrap_or(d.read),
            create: r.create.map(|s| Access::parse(&s)).unwrap_or(d.create),
            update: r.update.map(|s| Access::parse(&s)).unwrap_or(d.update),
            delete: r.delete.map(|s| Access::parse(&s)).unwrap_or(d.delete),
        }
    }
}

/// One point in a resource's request lifecycle at which a function may run.
///
/// `before_*` hooks run after the permission check but before the database is
/// touched, so they can validate, rewrite the submitted payload, or abort the
/// request. `after_*` hooks run once the operation succeeded and can rewrite the
/// response body.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum HookEvent {
    BeforeList,
    AfterList,
    BeforeRead,
    AfterRead,
    BeforeCreate,
    AfterCreate,
    BeforeUpdate,
    AfterUpdate,
    BeforeDelete,
    AfterDelete,
}

impl HookEvent {
    /// Every event, in lifecycle order.
    pub const ALL: [HookEvent; 10] = [
        HookEvent::BeforeList,
        HookEvent::AfterList,
        HookEvent::BeforeRead,
        HookEvent::AfterRead,
        HookEvent::BeforeCreate,
        HookEvent::AfterCreate,
        HookEvent::BeforeUpdate,
        HookEvent::AfterUpdate,
        HookEvent::BeforeDelete,
        HookEvent::AfterDelete,
    ];

    /// The TOML key / wire name, e.g. `"before_create"`.
    pub fn as_str(self) -> &'static str {
        match self {
            HookEvent::BeforeList => "before_list",
            HookEvent::AfterList => "after_list",
            HookEvent::BeforeRead => "before_read",
            HookEvent::AfterRead => "after_read",
            HookEvent::BeforeCreate => "before_create",
            HookEvent::AfterCreate => "after_create",
            HookEvent::BeforeUpdate => "before_update",
            HookEvent::AfterUpdate => "after_update",
            HookEvent::BeforeDelete => "before_delete",
            HookEvent::AfterDelete => "after_delete",
        }
    }

    /// The operation this event belongs to (`"create"`, `"list"`, …).
    pub fn action(self) -> &'static str {
        match self {
            HookEvent::BeforeList | HookEvent::AfterList => "list",
            HookEvent::BeforeRead | HookEvent::AfterRead => "read",
            HookEvent::BeforeCreate | HookEvent::AfterCreate => "create",
            HookEvent::BeforeUpdate | HookEvent::AfterUpdate => "update",
            HookEvent::BeforeDelete | HookEvent::AfterDelete => "delete",
        }
    }

    /// `"before"` or `"after"`.
    pub fn phase(self) -> &'static str {
        if self.is_before() {
            "before"
        } else {
            "after"
        }
    }

    /// Whether this event fires ahead of the database operation.
    pub fn is_before(self) -> bool {
        matches!(
            self,
            HookEvent::BeforeList
                | HookEvent::BeforeRead
                | HookEvent::BeforeCreate
                | HookEvent::BeforeUpdate
                | HookEvent::BeforeDelete
        )
    }
}

/// The `[hooks]` section of a resource: a function name per lifecycle event.
///
/// Unknown keys are rejected so a typo (`befor_create`) fails at load time
/// instead of silently never firing.
///
/// The [`AuthEvent`] keys live here too, and are only meaningful on the `user`
/// resource — declaring one anywhere else fails
/// [validation](Resource::validate), since nothing would ever fire it.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Hooks {
    pub before_list: Option<String>,
    pub after_list: Option<String>,
    pub before_read: Option<String>,
    pub after_read: Option<String>,
    pub before_create: Option<String>,
    pub after_create: Option<String>,
    pub before_update: Option<String>,
    pub after_update: Option<String>,
    pub before_delete: Option<String>,
    pub after_delete: Option<String>,
    pub before_register: Option<String>,
    pub after_register: Option<String>,
    pub before_login: Option<String>,
    pub after_login: Option<String>,
    pub before_api_key: Option<String>,
    pub after_api_key: Option<String>,
}

impl Hooks {
    /// The function bound to an event, if any.
    pub fn get(&self, event: HookEvent) -> Option<&str> {
        let slot = match event {
            HookEvent::BeforeList => &self.before_list,
            HookEvent::AfterList => &self.after_list,
            HookEvent::BeforeRead => &self.before_read,
            HookEvent::AfterRead => &self.after_read,
            HookEvent::BeforeCreate => &self.before_create,
            HookEvent::AfterCreate => &self.after_create,
            HookEvent::BeforeUpdate => &self.before_update,
            HookEvent::AfterUpdate => &self.after_update,
            HookEvent::BeforeDelete => &self.before_delete,
            HookEvent::AfterDelete => &self.after_delete,
        };
        slot.as_deref()
    }

    /// Every declared `(event, function)` pair, in lifecycle order.
    pub fn iter(&self) -> impl Iterator<Item = (HookEvent, &str)> {
        HookEvent::ALL
            .into_iter()
            .filter_map(|event| self.get(event).map(|name| (event, name)))
    }

    /// Whether any hook at all is declared, auth events included.
    pub fn is_empty(&self) -> bool {
        self.iter().next().is_none() && self.auth_iter().next().is_none()
    }
}

/// Auth configuration carried in a `[auth]` section on the `user` resource.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct AuthSpec {
    /// Field used as the login identifier.
    pub identity_field: String,
    /// Field holding the password hash.
    pub password_field: String,
    /// Enabled OAuth providers, e.g. `["google", "facebook"]`.
    pub oauth_providers: Vec<String>,
}

impl Default for AuthSpec {
    fn default() -> Self {
        AuthSpec {
            identity_field: "email".to_string(),
            password_field: "password_hash".to_string(),
            oauth_providers: Vec::new(),
        }
    }
}

/// One point in an auth endpoint's lifecycle at which a function may run.
///
/// These are declared in the `user` model's ordinary `[hooks]` section, next to
/// its CRUD hooks, and are only meaningful there — the built-in endpoints are
/// the `user` resource's other door. They sit alongside the [`HookEvent`]s
/// rather than replacing them: registration is still a `create` on `user`, so
/// `before_create` / `after_create` fire there too.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AuthEvent {
    BeforeRegister,
    AfterRegister,
    BeforeLogin,
    AfterLogin,
    BeforeApiKey,
    AfterApiKey,
}

impl AuthEvent {
    /// Every event, in lifecycle order.
    pub const ALL: [AuthEvent; 6] = [
        AuthEvent::BeforeRegister,
        AuthEvent::AfterRegister,
        AuthEvent::BeforeLogin,
        AuthEvent::AfterLogin,
        AuthEvent::BeforeApiKey,
        AuthEvent::AfterApiKey,
    ];

    /// The TOML key / wire name, e.g. `"before_login"`.
    pub fn as_str(self) -> &'static str {
        match self {
            AuthEvent::BeforeRegister => "before_register",
            AuthEvent::AfterRegister => "after_register",
            AuthEvent::BeforeLogin => "before_login",
            AuthEvent::AfterLogin => "after_login",
            AuthEvent::BeforeApiKey => "before_api_key",
            AuthEvent::AfterApiKey => "after_api_key",
        }
    }

    /// The endpoint this event belongs to (`"register"`, `"login"`, `"api_key"`).
    pub fn action(self) -> &'static str {
        match self {
            AuthEvent::BeforeRegister | AuthEvent::AfterRegister => "register",
            AuthEvent::BeforeLogin | AuthEvent::AfterLogin => "login",
            AuthEvent::BeforeApiKey | AuthEvent::AfterApiKey => "api_key",
        }
    }

    /// `"before"` or `"after"`.
    pub fn phase(self) -> &'static str {
        if self.is_before() {
            "before"
        } else {
            "after"
        }
    }

    /// Whether this event fires ahead of the work the endpoint does.
    pub fn is_before(self) -> bool {
        matches!(
            self,
            AuthEvent::BeforeRegister | AuthEvent::BeforeLogin | AuthEvent::BeforeApiKey
        )
    }
}

impl Hooks {
    /// The function bound to an auth event, if any.
    pub fn get_auth(&self, event: AuthEvent) -> Option<&str> {
        let slot = match event {
            AuthEvent::BeforeRegister => &self.before_register,
            AuthEvent::AfterRegister => &self.after_register,
            AuthEvent::BeforeLogin => &self.before_login,
            AuthEvent::AfterLogin => &self.after_login,
            AuthEvent::BeforeApiKey => &self.before_api_key,
            AuthEvent::AfterApiKey => &self.after_api_key,
        };
        slot.as_deref()
    }

    /// Every declared auth `(event, function)` pair, in lifecycle order.
    pub fn auth_iter(&self) -> impl Iterator<Item = (AuthEvent, &str)> {
        AuthEvent::ALL
            .into_iter()
            .filter_map(|event| self.get_auth(event).map(|name| (event, name)))
    }
}

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

    fn parse_resource(src: &str) -> Resource {
        let resource: Resource = toml::from_str(src).unwrap();
        resource.validate().unwrap();
        resource
    }

    #[test]
    fn access_parser_and_permissions_defaults_match_org_membership_model() {
        assert_eq!(Access::parse("public"), Access::Public);
        assert_eq!(Access::parse("authenticated"), Access::Authenticated);
        assert_eq!(Access::parse("member"), Access::Member);
        assert_eq!(Access::parse("owner"), Access::Owner);
        assert_eq!(Access::parse("role:admin"), Access::Role("admin".into()));
        assert_eq!(Access::parse("wat"), Access::Private);

        let defaults = Permissions::default();
        assert_eq!(defaults.list, Access::Member);
        assert_eq!(defaults.read, Access::Member);
        assert_eq!(defaults.create, Access::Member);
        assert_eq!(defaults.update, Access::Member);
        assert_eq!(defaults.delete, Access::Member);
    }

    #[test]
    fn validate_rejects_reserved_id_and_dangling_reference_definition() {
        let reserved_id: Resource = toml::from_str(
            r#"
[resource]
name = "bad"

[fields.id]
type = "string"
"#,
        )
        .unwrap();
        assert!(reserved_id.validate().is_err());

        let missing_target: Resource = toml::from_str(
            r#"
[resource]
name = "bad_ref"

[fields.owner_id]
type = "reference"
"#,
        )
        .unwrap();
        assert!(missing_target.validate().is_err());
    }

    #[test]
    fn content_format_is_only_allowed_on_text_fields() {
        let good: Resource = toml::from_str(
            r#"
[resource]
name = "article"

[fields.body]
type = "text"

[fields.body.admin]
format = "markdown"
"#,
        )
        .unwrap();
        good.validate().unwrap();
        assert_eq!(good.fields["body"].admin.format, ContentFormat::Markdown);

        let bad: Resource = toml::from_str(
            r#"
[resource]
name = "article"

[fields.published]
type = "boolean"

[fields.published.admin]
format = "html"
"#,
        )
        .unwrap();
        assert!(bad.validate().is_err());
    }

    #[test]
    fn references_derive_relation_names_and_default_on_delete() {
        let resource = parse_resource(
            r#"
[resource]
name = "comment"

[fields.post_id]
type = "reference"
references = "post"
required = true

[fields.author_id]
type = "reference"
references = "user"
on_delete = "cascade"
"#,
        );

        assert_eq!(relation_name("owner_id"), "owner");
        assert_eq!(relation_name("slug"), "slug");

        let refs = resource.references();
        assert_eq!(refs.len(), 2);
        let post = refs.iter().find(|rf| rf.field == "post_id").unwrap();
        assert_eq!(post.target, "post");
        assert_eq!(post.relation, "post");
        assert_eq!(post.on_delete, OnDelete::Restrict);
        assert!(post.required);

        let author = resource.reference_by_relation("author").unwrap();
        assert_eq!(author.field, "author_id");
        assert_eq!(author.on_delete, OnDelete::Cascade);
    }

    #[test]
    fn hooks_parse_per_event_and_iterate_in_lifecycle_order() {
        let resource = parse_resource(
            r#"
[resource]
name = "post"

[fields.title]
type = "string"

[hooks]
before_create = "validate_post"
after_create = "notify"
after_list = "redact"
"#,
        );

        assert_eq!(
            resource.hook(HookEvent::BeforeCreate),
            Some("validate_post")
        );
        assert_eq!(resource.hook(HookEvent::AfterCreate), Some("notify"));
        assert_eq!(resource.hook(HookEvent::AfterList), Some("redact"));
        assert_eq!(resource.hook(HookEvent::BeforeUpdate), None);
        assert!(!resource.hooks.is_empty());

        let declared: Vec<_> = resource.hooks.iter().collect();
        assert_eq!(
            declared,
            vec![
                (HookEvent::AfterList, "redact"),
                (HookEvent::BeforeCreate, "validate_post"),
                (HookEvent::AfterCreate, "notify"),
            ]
        );
    }

    #[test]
    fn hook_events_expose_wire_names_actions_and_phases() {
        assert_eq!(HookEvent::BeforeCreate.as_str(), "before_create");
        assert_eq!(HookEvent::BeforeCreate.action(), "create");
        assert_eq!(HookEvent::BeforeCreate.phase(), "before");
        assert!(HookEvent::BeforeCreate.is_before());

        assert_eq!(HookEvent::AfterList.as_str(), "after_list");
        assert_eq!(HookEvent::AfterList.action(), "list");
        assert_eq!(HookEvent::AfterList.phase(), "after");
        assert!(!HookEvent::AfterList.is_before());

        // Every event round-trips through the `[hooks]` section under its own key.
        for event in HookEvent::ALL {
            let resource = parse_resource(&format!(
                "[resource]\nname = \"post\"\n\n[hooks]\n{} = \"h\"\n",
                event.as_str()
            ));
            assert_eq!(resource.hook(event), Some("h"), "{}", event.as_str());
            assert_eq!(resource.hooks.iter().count(), 1);
        }
    }

    #[test]
    fn hooks_reject_typos_and_empty_function_names() {
        let typo = toml::from_str::<Resource>(
            r#"
[resource]
name = "post"

[hooks]
befor_create = "oops"
"#,
        );
        assert!(typo.is_err(), "unknown hook keys must not be ignored");

        let empty: Resource = toml::from_str(
            r#"
[resource]
name = "post"

[hooks]
after_delete = "  "
"#,
        )
        .unwrap();
        assert!(empty.validate().is_err());
    }

    #[test]
    fn auth_events_expose_wire_names_actions_and_phases() {
        assert_eq!(AuthEvent::BeforeLogin.as_str(), "before_login");
        assert_eq!(AuthEvent::BeforeLogin.action(), "login");
        assert_eq!(AuthEvent::BeforeLogin.phase(), "before");
        assert!(AuthEvent::BeforeLogin.is_before());

        assert_eq!(AuthEvent::AfterApiKey.action(), "api_key");
        assert_eq!(AuthEvent::AfterApiKey.phase(), "after");
        assert!(!AuthEvent::AfterApiKey.is_before());

        // Every event round-trips through `[hooks]` under its own key, next to
        // the CRUD ones.
        for event in AuthEvent::ALL {
            let resource = parse_resource(&format!(
                "[resource]\nname = \"user\"\n\n[hooks]\nafter_create = \"c\"\n{} = \"h\"\n",
                event.as_str()
            ));
            assert_eq!(resource.auth_hook(event), Some("h"), "{}", event.as_str());
            assert_eq!(resource.hook(HookEvent::AfterCreate), Some("c"));
            assert_eq!(resource.hooks.auth_iter().count(), 1);
            // The CRUD iterator stays CRUD-only, so nothing that walks a
            // resource's lifecycle events picks up an auth one by accident.
            assert_eq!(resource.hooks.iter().count(), 1);
        }
    }

    #[test]
    fn auth_hooks_are_absent_by_default_and_reject_typos_and_empty_names() {
        let plain =
            parse_resource("[resource]\nname = \"user\"\n\n[hooks]\nafter_create = \"c\"\n");
        assert_eq!(plain.auth_hook(AuthEvent::BeforeLogin), None);
        assert!(parse_resource("[resource]\nname = \"user\"\n")
            .hooks
            .is_empty());

        let typo = toml::from_str::<Resource>(
            "[resource]\nname = \"user\"\n\n[hooks]\nbefore_signin = \"oops\"\n",
        );
        assert!(typo.is_err(), "unknown auth hook keys must not be ignored");

        let empty: Resource =
            toml::from_str("[resource]\nname = \"user\"\n\n[hooks]\nafter_login = \"  \"\n")
                .unwrap();
        assert!(empty.validate().is_err());
    }

    #[test]
    fn auth_hooks_are_rejected_on_any_resource_but_user() {
        // The key parses anywhere — `[hooks]` is one section — so validation is
        // what catches a hook nothing would ever fire.
        let stray: Resource =
            toml::from_str("[resource]\nname = \"post\"\n\n[hooks]\nbefore_login = \"h\"\n")
                .unwrap();
        let message = stray.validate().unwrap_err().to_string();
        assert!(message.contains("before_login"), "{message}");
        assert!(message.contains("user"), "{message}");
    }

    #[test]
    fn resources_have_no_hooks_by_default() {
        let resource = parse_resource("[resource]\nname = \"post\"\n");
        assert!(resource.hooks.is_empty());
        assert!(HookEvent::ALL
            .into_iter()
            .all(|event| resource.hook(event).is_none()));
    }

    #[test]
    fn admin_visibility_defaults_hide_auth_resources_but_nothing_else() {
        let post = parse_resource("[resource]\nname = \"post\"\n");
        assert!(post.admin.is_visible("post"));

        let user = parse_resource(crate::defaults::USER_TOML);
        assert!(!user.admin.is_visible("user"));
        assert!(!parse_resource(crate::defaults::MEMBERSHIP_TOML)
            .admin
            .is_visible("membership"));

        // An app that replaces a built-in still gets the dedicated screen…
        let replaced = parse_resource(
            "[resource]\nname = \"user\"\nscope = \"global\"\n\n[fields.email]\ntype = \"string\"\n",
        );
        assert!(!replaced.admin.is_visible("user"));

        // …unless it asks for the table back.
        let opted_in = parse_resource(
            "[resource]\nname = \"user\"\nscope = \"global\"\n\n[admin]\nvisible = true\n",
        );
        assert!(opted_in.admin.is_visible("user"));
    }

    #[test]
    fn admin_labels_are_inferred_and_overridable() {
        let inferred = parse_resource("[resource]\nname = \"purchase_order\"\n");
        assert_eq!(inferred.admin_label(), "Purchase order");
        assert_eq!(inferred.admin_plural(), "Purchase orders");

        let overridden = parse_resource(
            "[resource]\nname = \"person\"\n\n[admin]\nlabel = \"Person\"\nplural = \"People\"\n",
        );
        assert_eq!(overridden.admin_plural(), "People");

        assert_eq!(titleize("owner_id"), "Owner");
        assert_eq!(titleize("total_cents"), "Total cents");
        assert_eq!(pluralize("Category"), "Categories");
        assert_eq!(pluralize("Address"), "Addresses");
        assert_eq!(pluralize("Day"), "Days");
        assert_eq!(pluralize("Product"), "Products");
    }

    #[test]
    fn display_field_prefers_conventional_names_then_any_string() {
        let conventional = parse_resource(
            r#"
[resource]
name = "product"

[fields.sku]
type = "string"

[fields.name]
type = "string"
"#,
        );
        assert_eq!(conventional.admin_display_field().as_deref(), Some("name"));

        let only_odd_names =
            parse_resource("[resource]\nname = \"blob\"\n\n[fields.zzz]\ntype = \"string\"\n");
        assert_eq!(only_odd_names.admin_display_field().as_deref(), Some("zzz"));

        let nothing_stringy =
            parse_resource("[resource]\nname = \"tick\"\n\n[fields.count]\ntype = \"integer\"\n");
        assert_eq!(nothing_stringy.admin_display_field(), None);

        // An explicit choice always wins, conventional or not.
        let declared = parse_resource(
            r#"
[resource]
name = "product"

[admin]
display_field = "sku"

[fields.sku]
type = "string"

[fields.name]
type = "string"
"#,
        );
        assert_eq!(declared.admin_display_field().as_deref(), Some("sku"));
        // `search_field` falls back to whatever names the record.
        assert_eq!(declared.admin_search_field().as_deref(), Some("sku"));
    }

    #[test]
    fn inferred_columns_skip_blobs_and_dashboard_hidden_fields() {
        let resource = parse_resource(
            r#"
[resource]
name = "product"

[fields.name]
type = "string"

[fields.status]
type = "string"

[fields.description]
type = "text"

[fields.attributes]
type = "json"

[fields.secret_ratio]
type = "float"

[fields.secret_ratio.admin]
visible = false
"#,
        );
        assert_eq!(resource.admin_columns(), vec!["name", "status"]);

        let declared = parse_resource(
            r#"
[resource]
name = "product"

[admin]
columns = ["status", "name"]

[fields.name]
type = "string"

[fields.status]
type = "string"
"#,
        );
        assert_eq!(declared.admin_columns(), vec!["status", "name"]);
    }

    #[test]
    fn admin_section_rejects_columns_naming_fields_that_do_not_exist() {
        let bad_column: Resource = toml::from_str(
            "[resource]\nname = \"post\"\n\n[admin]\ncolumns = [\"nope\"]\n\n[fields.title]\ntype = \"string\"\n",
        )
        .unwrap();
        assert!(bad_column.validate().is_err());

        let bad_display: Resource = toml::from_str(
            "[resource]\nname = \"post\"\n\n[admin]\ndisplay_field = \"nope\"\n\n[fields.title]\ntype = \"string\"\n",
        )
        .unwrap();
        assert!(bad_display.validate().is_err());

        // The search box matches substrings, so a search field that is not text
        // would be a box that answers 400 to every keystroke.
        let unsearchable: Resource = toml::from_str(
            "[resource]\nname = \"tick\"\n\n[admin]\nsearch_field = \"count\"\n\n[fields.count]\ntype = \"integer\"\n",
        )
        .unwrap();
        assert!(unsearchable.validate().is_err());

        // And one inherited from a non-text `display_field` simply leaves the
        // resource without a search box, rather than failing the app.
        let named_by_a_number = parse_resource(
            "[resource]\nname = \"tick\"\n\n[admin]\ndisplay_field = \"count\"\n\n[fields.count]\ntype = \"integer\"\n",
        );
        assert_eq!(
            named_by_a_number.admin_display_field().as_deref(),
            Some("count")
        );
        assert_eq!(named_by_a_number.admin_search_field(), None);

        // A typo in a key is caught too, rather than silently ignored.
        assert!(toml::from_str::<Resource>(
            "[resource]\nname = \"post\"\n\n[admin]\nvisibel = true\n"
        )
        .is_err());
    }

    #[test]
    fn field_admin_carries_widget_options_and_visibility() {
        let resource = parse_resource(
            r#"
[resource]
name = "product"

[fields.status]
type = "string"

[fields.status.admin]
label = "Lifecycle"
widget = "select"
options = ["draft", "active|Live"]
readonly = true
"#,
        );
        let status = &resource.fields["status"];
        assert_eq!(status.admin.label.as_deref(), Some("Lifecycle"));
        assert_eq!(status.admin.widget, Widget::Select);
        assert_eq!(status.admin.widget.as_str(), "select");
        assert_eq!(status.admin.options, vec!["draft", "active|Live"]);
        assert!(status.admin.readonly);
        // Defaults stay out of the way when `[fields.x.admin]` says nothing.
        assert!(status.admin.visible);
        assert_eq!(resource.fields["status"].admin.help, None);
    }

    #[test]
    fn org_column_reflects_resource_scope() {
        let org_scoped = parse_resource(
            r#"
[resource]
name = "post"

[fields.title]
type = "string"
"#,
        );
        let global = parse_resource(
            r#"
[resource]
name = "plan"
scope = "global"

[fields.name]
type = "string"
"#,
        );
        let organization = parse_resource(crate::defaults::ORGANIZATION_TOML);

        assert_eq!(org_scoped.org_column(), Some("organization_id"));
        assert_eq!(global.org_column(), None);
        assert_eq!(organization.org_column(), Some("id"));
    }
}