rustango-cms 0.4.0

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

// Our extractors, not axum's: they refuse a malformed value in the same
// JSON envelope as everything else. See `query::Query`.
use crate::api::query::{Path, Query};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::Json;
use rustango::core::Column as _;
use rustango::extractors::{SessionUser, Tenant};
use rustango::sql::FetcherPool as _;
use serde::Deserialize;

use super::query as q;
use crate::page::{Page, PageStatus};
use crate::page_type::{find_handler, PageTypeHandler};
use crate::page_type_model::PageType;

/// Per-endpoint filters layered on top of [`crate::api::query::ListQuery`].
#[derive(Debug, Default, Deserialize)]
pub struct PageFilters {
    /// `?type=cms_pages.HomePage` — handler type_name match.
    #[serde(default, deserialize_with = "q::empty_string_as_none")]
    pub r#type: Option<String>,
    /// `?child_of=N` — direct children of page N.
    #[serde(default, deserialize_with = "q::empty_as_none")]
    pub child_of: Option<i64>,
    /// `?descendant_of=N` — every descendant of page N (excluding N).
    #[serde(default, deserialize_with = "q::empty_as_none")]
    pub descendant_of: Option<i64>,
    /// `?ancestor_of=N` — every ancestor of page N (excluding N).
    #[serde(default, deserialize_with = "q::empty_as_none")]
    pub ancestor_of: Option<i64>,
    /// `?translation_of=N` — sibling locale variants of page N.
    #[serde(default, deserialize_with = "q::empty_as_none")]
    pub translation_of: Option<i64>,
    /// `?locale=en` — restrict to a specific locale.
    #[serde(default, deserialize_with = "q::empty_string_as_none")]
    pub locale: Option<String>,
    /// `?tag=release` — restrict to pages carrying this tag.
    #[serde(default, deserialize_with = "q::empty_string_as_none")]
    pub tag: Option<String>,
    /// `?id_in=3,9,14` — fetch several pages by id in one request.
    ///
    /// Without it, hydrating a resolved menu (which returns `page_id`
    /// per node and nothing else) costs one request per item. Unknown
    /// and non-public ids are simply absent from the result rather than
    /// an error, so a stale client id degrades to a missing row instead
    /// of failing the whole batch. Bounded by `?limit=` like any list.
    #[serde(default, deserialize_with = "q::empty_string_as_none")]
    pub id_in: Option<String>,
}

/// Combined query string for `GET /api/v2/pages/`.
#[derive(Debug, Default, Deserialize)]
pub struct PageListQuery {
    #[serde(flatten)]
    pub list: q::ListQuery,
    #[serde(flatten)]
    pub filters: PageFilters,
}

/// Query string for `GET /api/v2/pages/find/`.
#[derive(Debug, Default, Deserialize)]
pub struct FindQuery {
    /// Public URL path to resolve, e.g. `/about` (with or without a
    /// trailing slash).
    #[serde(default, deserialize_with = "q::empty_string_as_none")]
    pub html_path: Option<String>,
}

/// Query for the page detail endpoint.
#[derive(Default, Deserialize)]
pub struct DetailQuery {
    /// A signed preview token (from the admin mint endpoint).
    /// When valid for this page id, the endpoint serves the page even
    /// if it isn't published, so a decoupled frontend can render the
    /// draft.
    #[serde(default, deserialize_with = "q::empty_string_as_none")]
    pub preview_token: Option<String>,
    /// `?locale=fr` — return this locale's content. Overrides from
    /// `cms_translation` are applied per field, so anything untranslated
    /// falls back to canonical rather than blanking. An unknown or
    /// inactive code falls back to the tenant default.
    ///
    /// Note this is a *content selector*, unlike the list endpoint's
    /// `?locale=`, which is a legacy row filter over the deprecated
    /// `locale_variant_of` column.
    #[serde(default, deserialize_with = "q::empty_string_as_none")]
    pub locale: Option<String>,
    /// `?fields=title,seo_title` — same sparse selection the list
    /// endpoints accept. It was list-only, so a client fetching one page
    /// had no way to avoid pulling `extension`, `builder` and the whole
    /// `children` array. `id` and `meta` are always kept.
    #[serde(default, deserialize_with = "q::empty_string_as_none")]
    pub fields: Option<String>,
}

/// `GET /api/v2/pages/`
pub async fn list(
    tenant: Tenant,
    SessionUser(session_user): SessionUser,
    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
    Query(qs): Query<PageListQuery>,
) -> Response {
    // #members — a public member outranks an admin session, matching
    // `tree`, `menus::detail` and the public renderer.
    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
    match list_inner(tenant.pool(), &tenant.org.slug, viewer, &qs).await {
        Ok(resp) => resp,
        Err(e) => {
            tracing::error!(target: "rustango_cms::api", error = %e, "pages list failed");
            crate::api::error::ApiError::internal().into_response()
        }
    }
}

/// The SQL side of a page listing: every filter that is an exact match,
/// resolved once so the count, the window and the in-memory fallback all
/// read the same rows.
struct PageScope {
    /// `?translation_of=` keeps the legacy locale-variant rows every
    /// other query drops.
    translation_of: Option<i64>,
    type_id: Option<i64>,
    updated_since: Option<chrono::DateTime<chrono::Utc>>,
    id_in: Option<Vec<i64>>,
    child_of: Option<i64>,
    /// `?descendant_of=` as the anchor's path prefix.
    descendant_prefix: Option<String>,
    /// `?ancestor_of=` as the anchor's ancestor paths.
    ancestor_paths: Option<Vec<String>>,
    /// A non-default `?locale=`: only the variant rows.
    variants_only: bool,
    /// `?tag=`, normalized.
    tag: Option<String>,
    /// A filter that can match nothing (an unknown type, an anchor the
    /// viewer cannot see, an empty id list) — no query needed.
    matches_nothing: bool,
}

impl PageScope {
    /// The filters the tree anchors are resolved against: public, no
    /// legacy variants (unless `translation_of`), type, `updated_since`,
    /// `id_in` and `child_of`. The anchor of `?descendant_of=` has to pass
    /// these but not the tag, locale or translation filters, which is the
    /// order the in-memory listing has always applied them in.
    fn base(&self) -> rustango::query::QuerySet<Page> {
        let mut qs = Page::objects().where_(Page::status.is_in([
            PageStatus::Published.as_str().to_owned(),
            PageStatus::Archived.as_str().to_owned(),
        ]));
        if self.translation_of.is_none() {
            qs = qs.where_(Page::locale_variant_of.is_null());
        }
        if let Some(tid) = self.type_id {
            qs = qs.where_(Page::page_type_id.eq(tid));
        }
        if let Some(since) = self.updated_since {
            qs = qs.where_(Page::updated_at.gte(since));
        }
        if let Some(ids) = &self.id_in {
            qs = qs.where_(Page::id.is_in(ids.iter().copied()));
        }
        if let Some(parent) = self.child_of {
            qs = qs.where_(Page::parent_id.eq(parent));
        }
        qs
    }

    /// [`Self::base`] plus the tree, translation, locale and tag filters.
    fn narrowed(&self) -> Result<rustango::query::QuerySet<Page>, rustango::sql::ExecError> {
        let mut qs = self.base();
        if let Some(prefix) = &self.descendant_prefix {
            // Materialized paths are lowercase hex and `/`, so the prefix
            // needs no LIKE escaping (see `tree`).
            qs = qs.where_(Page::path.like(format!("{prefix}%")));
            qs = qs.where_(Page::path.ne(prefix.clone()));
        }
        if let Some(paths) = &self.ancestor_paths {
            qs = qs.where_(Page::path.is_in(paths.iter().cloned()));
        }
        if let Some(canon) = self.translation_of {
            qs = qs.where_(Page::locale_variant_of.eq(canon));
        }
        if self.variants_only {
            qs = qs.where_(Page::locale_variant_of.is_not_null());
        }
        if let Some(tag) = &self.tag {
            // A subquery rather than an id list: a popular tag must not
            // run into a backend's bind-parameter ceiling.
            let tagged = crate::page_tag::PageTag::objects()
                .where_(crate::page_tag::PageTag::name.eq(tag.clone()))
                .values_list_flat("page_id")
                .compile()?;
            qs = qs.where_(rustango::core::TypedExpr::from_where_expr(
                rustango::core::subquery::in_subquery("id", tagged),
            ));
        }
        Ok(qs)
    }
}

/// How a listing with no text search may be ordered in SQL.
enum SqlOrder {
    /// The default: newest published first, then title, then id.
    Default,
    /// Only date and number keys, then `id`.
    Keys(Vec<(&'static str, bool, rustango::core::NullsOrder)>),
}

/// The SQL order for `orderings`, or `None` when it needs Rust: a text
/// key (collations differ per backend, Rust's byte order does not) or
/// `random`.
fn sql_order(orderings: &[q::OrderSpec]) -> Option<SqlOrder> {
    use rustango::core::NullsOrder;
    if orderings.is_empty() {
        return Some(SqlOrder::Default);
    }
    let mut keys = Vec::with_capacity(orderings.len() + 1);
    for o in orderings {
        if o.random {
            return None;
        }
        let col = match o.field.as_str() {
            "published_at" => "published_at",
            "updated_at" => "updated_at",
            "created_at" => "created_at",
            "depth" => "depth",
            "sort_order" => "sort_order",
            _ => return None,
        };
        // Rust orders `None` first, so a descending sort puts it last.
        let nulls = if col != "published_at" {
            NullsOrder::Default
        } else if o.descending {
            NullsOrder::Last
        } else {
            NullsOrder::First
        };
        keys.push((col, o.descending, nulls));
    }
    keys.push(("id", false, NullsOrder::Default));
    Some(SqlOrder::Keys(keys))
}

/// The default listing order: most recently published first, then
/// title, then id.
fn compare_default(a: &Page, b: &Page) -> std::cmp::Ordering {
    b.published_at
        .cmp(&a.published_at)
        .then_with(|| a.title.cmp(&b.title))
        // Unique tiebreaker: `sort_by` is stable, so without one tied
        // rows keep the fetch order and paging is only as stable as the
        // driver happens to be.
        .then_with(|| a.id.get().cmp(&b.id.get()))
}

/// One window of `scope` in the default order, without loading the rest.
///
/// SQL sorts by `published_at DESC, id`, which puts the rows in the same
/// groups of equal `published_at` as [`compare_default`] and differs only
/// inside a group, where the title decides. So: take the SQL window, read
/// the (at most two) groups that straddle its edges in full, and order
/// that run in Rust. It starts right after every row of a newer group.
/// Most ids `?id_in=` accepts in one request.
const MAX_ID_IN: usize = 200;

/// The default-order page window (`published_at` desc, then title, id).
/// SQL picks the window by `published_at, id`; the rows sharing a
/// `published_at` with the window's first or last row are re-read in full
/// and sorted in Rust, since a title order isn't the same on every
/// backend. Cost note: that re-read is as big as the tie group — pages
/// bulk-published in the same instant all load once a window touches them.
async fn default_order_window(
    pool: &rustango::sql::Pool,
    scope: &PageScope,
    limit: usize,
    offset: usize,
) -> Result<Vec<Page>, rustango::sql::ExecError> {
    use rustango::core::NullsOrder;
    use rustango::sql::CounterPool as _;
    let sql_window: Vec<Page> = scope
        .narrowed()?
        .order_by_with_nulls(&[
            ("published_at", true, NullsOrder::Last),
            ("id", false, NullsOrder::Default),
        ])
        .limit(i64::try_from(limit).unwrap_or(i64::MAX))
        // A huge `?offset=` must not wrap negative (backends differ).
        .offset(i64::try_from(offset).unwrap_or(i64::MAX))
        .fetch(pool)
        .await?;
    let (Some(first), Some(last)) = (sql_window.first(), sql_window.last()) else {
        return Ok(Vec::new());
    };
    let (first_key, last_key) = (first.published_at, last.published_at);
    let ahead = match first_key {
        Some(t) => scope.narrowed()?.where_(Page::published_at.gt(t)).count(pool).await?,
        // NULLs sort last, so every dated row is ahead of them.
        None => scope.narrowed()?.where_(Page::published_at.is_not_null()).count(pool).await?,
    };
    let group = |key: Option<chrono::DateTime<chrono::Utc>>| -> Result<_, rustango::sql::ExecError> {
        Ok(match key {
            Some(t) => scope.narrowed()?.where_(Page::published_at.eq(t)),
            None => scope.narrowed()?.where_(Page::published_at.is_null()),
        })
    };
    let mut run: Vec<Page> = group(first_key)?.fetch(pool).await?;
    if last_key != first_key {
        run.extend(
            sql_window
                .into_iter()
                .filter(|p| p.published_at != first_key && p.published_at != last_key),
        );
        run.extend(group(last_key)?.fetch(pool).await?);
    }
    run.sort_by(compare_default);
    let skip = offset.saturating_sub(usize::try_from(ahead).unwrap_or_default());
    Ok(run.into_iter().skip(skip).take(limit).collect())
}

/// The path of anchor page `id` when it is in `base` and `access` lets
/// the viewer see it.
///
/// `None` for "gated" and for "absent" alike is deliberate: answering
/// differently would tell a caller whether a page it may not see exists.
async fn visible_anchor_path(
    pool: &rustango::sql::Pool,
    base: rustango::query::QuerySet<Page>,
    access: &crate::view_restriction::AccessContext,
    id: i64,
) -> Result<Option<String>, rustango::sql::ExecError> {
    let anchor: Option<Page> = base.where_(Page::id.eq(id)).first(pool).await?;
    Ok(anchor
        .filter(|p| access.can_view(&p.path, p.page_type_id))
        .map(|p| p.path))
}

/// The body of `GET /api/v2/pages/`.
///
/// Takes a `&Pool` and the tenant slug rather than the `Tenant`, so the
/// endpoint is exercisable against an in-memory database (see
/// [`crate::api::tree::tree_inner`]).
///
/// Exact filters run in SQL (#655). Count, order and paging do too when
/// there is no text search, the viewer is denied nothing, and the order
/// is the default or uses only date and number keys; otherwise the
/// SQL-narrowed rows are filtered, ordered and paged in memory.
///
/// # Errors
/// Driver / query failures.
pub async fn list_inner(
    pool: &rustango::sql::Pool,
    tenant_slug: &str,
    viewer: Option<&rustango::tenancy::auth::User>,
    qs: &PageListQuery,
) -> Result<Response, rustango::sql::ExecError> {
    let (limit, offset) = q::paginate(&qs.list);
    let fields = q::field_set(&qs.list);
    let orderings = match q::parse_order_in(&qs.list, &PAGE_ORDER_FIELDS) {
        Ok(v) => v,
        Err(msg) => return Ok(crate::api::error::ApiError::bad_request(msg).into_response()),
    };
    // #changes — `?updated_since=` so a polling client can ask for only
    // what moved, instead of re-fetching the collection and diffing it.
    let updated_since = match crate::api::query::parse_updated_since(&qs.list) {
        Ok(v) => v,
        Err(msg) => return Ok(crate::api::error::ApiError::bad_request(msg).into_response()),
    };
    // ----- explicit id set ----------------------------------------------
    // An *unknown* id is deliberately absent rather than an error, so one
    // stale id costs a batch one row instead of all of them. A segment
    // that is not a number at all is a different thing: it was never an
    // id, so it cannot be stale, and dropping it made a client's own bug
    // look like a deleted page — the worst possible reading, on the
    // endpoint whose whole job is hydrating a list of ids a menu just
    // handed over.
    let mut id_in: Option<Vec<i64>> = None;
    if let Some(raw) = qs.filters.id_in.as_deref() {
        let mut wanted = std::collections::BTreeSet::new();
        for seg in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
            match seg.parse::<i64>() {
                Ok(id) => {
                    wanted.insert(id);
                }
                Err(_) => {
                    return Ok(crate::api::error::ApiError::bad_request(format!(
                        "`id_in` expects comma-separated integers; `{seg}` is not one",
                    ))
                    .into_response())
                }
            }
        }
        // Bound the list: it is bound as one `IN (…)` in several queries,
        // and SQLite builds can cap bind parameters at 999.
        if wanted.len() > MAX_ID_IN {
            return Ok(crate::api::error::ApiError::bad_request(format!(
                "`id_in` takes at most {MAX_ID_IN} ids; got {}",
                wanted.len()
            ))
            .into_response());
        }
        id_in = Some(wanted.into_iter().collect());
    }

    // `random` reshuffles per request, so an offset into it is not a
    // second page — it is a fresh shuffle with rows skipped. Refuse the
    // combination rather than quietly returning overlapping garbage.
    if orderings.iter().any(|o| o.random) && offset > 0 {
        return Ok(crate::api::error::ApiError::bad_request(
            "`order=random` cannot be paged — omit `offset`, or order by a field",
        )
        .into_response());
    }
    // Public means `published` **or** `archived` (`PageStatus::is_public`),
    // matching the renderer, the sitemap, the tree, the child summaries
    // and the menu resolver — so `?id_in=` can re-fetch any page a menu
    // just named.
    //
    // Legacy per-locale variant trees were standalone copies of the whole
    // site, so leaving them in returned it once per locale (#275).
    // `?translation_of=` exists precisely to list those rows, so it opts
    // out.
    let mut scope = PageScope {
        translation_of: qs.filters.translation_of,
        type_id: None,
        updated_since,
        matches_nothing: id_in.as_ref().is_some_and(Vec::is_empty),
        id_in,
        child_of: qs.filters.child_of,
        descendant_prefix: None,
        ancestor_paths: None,
        variants_only: false,
        tag: None,
    };

    // ----- type filter --------------------------------------------------
    if let Some(type_name) = qs.filters.r#type.as_deref().filter(|s| !s.is_empty()) {
        // `cms_page_type.type_name` stores the bare handler name and
        // keeps `app_label` in its own column, so the dotted form the
        // doc comment advertises (`cms_pages.HomePage`) could never
        // match. Accept both rather than making the documentation wrong.
        let bare = type_name.rsplit('.').next().unwrap_or(type_name);
        match lookup_page_type(pool, bare).await? {
            Some(pt) => scope.type_id = Some(pt.id.get().copied().unwrap_or_default()),
            None => scope.matches_nothing = true,
        }
    }

    // #members — what this viewer may not see is dropped *before* any
    // filter runs, so a gated page's title, SEO text and URL stay
    // private, and `?descendant_of=` against a member-only section
    // cannot dump it. Subtree-aware via `path`, so a gated ancestor takes
    // its descendants with it.
    let access = crate::view_restriction::access_context(pool, viewer).await;

    // ----- tree filters -------------------------------------------------
    // The anchors are resolved against the *visible* set, not the whole
    // table. Looking them up unrestricted would let a caller pivot off a
    // page they cannot see: the anchor's path is all `?descendant_of=`
    // needs.
    let mut descendant_prefix = None;
    let mut ancestor_paths = None;
    if !scope.matches_nothing {
        if let Some(root_id) = qs.filters.descendant_of {
            descendant_prefix = visible_anchor_path(pool, scope.base(), &access, root_id).await?;
            if descendant_prefix.is_none() {
                scope.matches_nothing = true;
            }
        }
        if let Some(leaf_id) = qs.filters.ancestor_of {
            match visible_anchor_path(pool, scope.base(), &access, leaf_id).await? {
                Some(path) => {
                    let paths: Vec<String> = ancestor_paths_of(&path).into_iter().collect();
                    if paths.is_empty() {
                        scope.matches_nothing = true;
                    }
                    ancestor_paths = Some(paths);
                }
                None => scope.matches_nothing = true,
            }
        }
    }
    scope.descendant_prefix = descendant_prefix;
    scope.ancestor_paths = ancestor_paths;

    // ----- locale -------------------------------------------------------
    if let Some(code) = qs.filters.locale.as_deref().filter(|s| !s.is_empty()) {
        // Resolve through the shared helper: it honours `active` and
        // falls back to the tenant default on an unknown code, which is
        // what `tree`, `detail` and `menus` all do.
        //
        // Canonical content lives on the page row, so the default locale
        // filters nothing. A non-default locale keeps only rows
        // explicitly marked as variants (a v1 proxy for "in that locale").
        let locale = crate::translation::resolve_locale(pool, Some(code)).await?;
        scope.variants_only = locale.is_some_and(|loc| !loc.is_default);
    }

    // ----- tag ----------------------------------------------------------
    if let Some(raw) = qs.filters.tag.as_deref().filter(|s| !s.is_empty()) {
        scope.tag = Some(crate::page_tag::normalize_name(raw));
    }

    // Capture the raw needle so the promotion-pinning step below can run
    // off the same value the title/slug/url_path filter uses.
    let search_needle = qs.list.search.as_deref().filter(|s| !s.trim().is_empty());

    // ----- SQL fast path ------------------------------------------------
    let fast = if search_needle.is_some() || !access.denies_nothing() {
        None
    } else {
        sql_order(&orderings)
    };
    let mut fts_ordered = false;
    let (window, total_count): (Vec<Page>, usize) = if scope.matches_nothing && fast.is_some() {
        (Vec::new(), 0)
    } else if let Some(order) = fast {
        use rustango::sql::CounterPool as _;
        let total = usize::try_from(scope.narrowed()?.count(pool).await?).unwrap_or_default();
        let rows = match order {
            SqlOrder::Default => default_order_window(pool, &scope, limit, offset).await?,
            SqlOrder::Keys(keys) => {
                scope
                    .narrowed()?
                    .order_by_with_nulls(&keys)
                    .limit(i64::try_from(limit).unwrap_or(i64::MAX))
                    // A huge `?offset=` must not wrap negative.
                    .offset(i64::try_from(offset).unwrap_or(i64::MAX))
                    .fetch(pool)
                    .await?
            }
        };
        (rows, total)
    } else {
        let mut pages: Vec<Page> = if scope.matches_nothing {
            Vec::new()
        } else {
            scope
                .narrowed()?
                // A deterministic base order. Without it the driver
                // decides, and on Postgres an unrelated UPDATE moves a row
                // to the end of the heap. `id` is unique, which is what
                // the in-memory comparators below lack.
                .order_by(&[("id", false)])
                .fetch(pool)
                .await?
        };
        if !access.is_unrestricted() {
            pages.retain(|p| access.can_view(&p.path, p.page_type_id));
        }

        // ----- search ---------------------------------------------------
        // #408 — relevance-ranked search. An installed external backend
        // (Elasticsearch) takes priority; else Postgres full-text; else
        // (None) the substring filter below. The ranked hit list also
        // drives result order (relevance by default).
        if let Some(needle) = search_needle {
            crate::search_promotion::log_public_query(pool, needle, offset);
            let ranked =
                crate::search::ranked_public_page_ids(pool, tenant_slug, needle, 1000).await;
            // A ranked hit OR a substring match (#702): the ranked backend
            // finds stemmed words but not a partial word, slug fragment or
            // URL path, so it adds to the substring match every backend
            // runs rather than replacing it. Ranked hits lead, in rank
            // order; substring-only hits follow in their existing order
            // (the sort is stable).
            let rank: Option<std::collections::HashMap<i64, usize>> =
                ranked.map(|r| r.iter().enumerate().map(|(i, id)| (*id, i)).collect());
            let n = crate::api::search::fold(needle);
            pages.retain(|p| {
                rank.as_ref()
                    .is_some_and(|r| p.id.get().copied().is_some_and(|id| r.contains_key(&id)))
                    || crate::api::search::contains_folded(&p.title, &n)
                    || crate::api::search::contains_folded(&p.slug, &n)
                    || crate::api::search::contains_folded(&p.url_path, &n)
            });
            if let Some(rank) = &rank {
                pages.sort_by_key(|p| {
                    p.id.get()
                        .copied()
                        .and_then(|id| rank.get(&id).copied())
                        .unwrap_or(usize::MAX)
                });
                fts_ordered = true;
            }
        }

        // ----- ordering -------------------------------------------------
        // FTS already ordered by relevance; an explicit ?order= still wins.
        if fts_ordered && orderings.is_empty() {
            // keep the relevance order from the FTS hit list
        } else if orderings.iter().any(|o| o.random) {
            // Random is one-shot per request; cheap on bounded list size.
            use rand::seq::SliceRandom as _;
            pages.shuffle(&mut rand::rng());
        } else if !orderings.is_empty() {
            pages.sort_by(|a, b| compare_pages(a, b, &orderings));
        } else {
            pages.sort_by(compare_default);
        }

        // ----- search promotions (#289) ---------------------------------
        // After the search filter + ordering settle, pin editor-promoted
        // pages to the front of the list. Skipped when the request didn't
        // include a search needle, when no SearchQuery row matches the
        // normalized form, or when the query has no promotions attached.
        //
        // Promotion order: pages are inserted in `sort_order` ascending,
        // de-duplicated against whatever was already at the head of the
        // filtered list (a page that organically ranked first AND was
        // promoted stays where the promotion put it, doesn't appear
        // twice).
        if let Some(needle) = search_needle {
            if let Ok(Some(q)) = crate::search_promotion::find_by_query(pool, needle).await {
                let query_id = q.id.get().copied().unwrap_or_default();
                if query_id != 0 {
                    if let Ok(promos) =
                        crate::search_promotion::promotions_for_query(pool, query_id).await
                    {
                        // Pull each promoted page out of the filtered list
                        // and reinsert it at the front in promotion order.
                        // Promoted pages outside the filtered result set
                        // stay dropped; the promotion table doesn't
                        // override the visitor's filter scope.
                        let mut pinned: Vec<Page> = Vec::with_capacity(promos.len());
                        for p in &promos {
                            if let Some(pos) = pages
                                .iter()
                                .position(|page| page.id.get().copied() == Some(p.page_id))
                            {
                                pinned.push(pages.remove(pos));
                            }
                        }
                        for (i, page) in pinned.into_iter().enumerate() {
                            pages.insert(i, page);
                        }
                    }
                }
            }
        }

        let total = pages.len();
        (pages.into_iter().skip(offset).take(limit).collect(), total)
    };

    // #408 — a fuzzy "did you mean?" when an FTS search matched nothing
    // but a near-match title exists (Postgres + pg_trgm only; None
    // otherwise). The suggestion comes from a similarity query that joins
    // nothing and spans `published + archived`, so confirm the suggested
    // title belongs to something this caller can see before offering it.
    let did_you_mean = match (fts_ordered, total_count, search_needle) {
        (true, 0, Some(needle)) => match crate::search::did_you_mean(pool, needle, 0.3).await {
            Some(title) => visible_title(pool, viewer, &title).await,
            None => None,
        },
        _ => None,
    };

    // ----- serialize ----------------------------------------------------
    let type_names = page_type_names(pool).await?;
    let mut items = Vec::with_capacity(window.len());
    for p in &window {
        let mut obj = serialize_summary(p, &type_names);
        // Validated against the first serialized row rather than a
        // hand-written list, so it cannot drift from what we return.
        if let Err(msg) = q::validate_fields(fields.as_ref(), &obj) {
            return Ok(crate::api::error::ApiError::bad_request(msg).into_response());
        }
        q::apply_fields(&mut obj, fields.as_ref());
        items.push(serde_json::Value::Object(obj));
    }

    let envelope = q::ListEnvelope {
        meta: q::ListMeta {
            did_you_mean,
            ..q::ListMeta::paged(total_count, limit, offset)
        },
        items,
    };
    Ok(Json(envelope).into_response())
}

/// `GET /api/v2/pages/{id}/`
pub async fn detail(
    tenant: Tenant,
    SessionUser(session_user): SessionUser,
    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
    headers: HeaderMap,
    Path(id): Path<i64>,
    Query(qs): Query<DetailQuery>,
) -> Response {
    // #members — gate against a public member OR an admin (member wins).
    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
    // #430 — a valid preview token for THIS page unlocks draft access.
    let allow_draft = qs
        .preview_token
        .as_deref()
        .zip(rustango::tenancy::TenantSlug::of(&tenant.org))
        .and_then(|(t, org)| crate::preview_token::verify(&org, t, chrono::Utc::now().timestamp()))
        == Some(id);
    match detail_inner(
        &tenant,
        viewer,
        &headers,
        id,
        allow_draft,
        qs.locale.as_deref(),
        qs.fields.as_deref(),
    )
    .await
    {
        Ok(resp) => resp,
        Err(e) => {
            tracing::error!(target: "rustango_cms::api", error = %e, "page detail failed");
            crate::api::error::ApiError::internal().into_response()
        }
    }
}

/// `GET /api/v2/pages/find/?html_path=/about` — resolve a public URL
/// path to its page and 302-redirect to the detail endpoint. Resolves **published** pages only; view
/// restrictions are enforced by the detail endpoint the client follows
/// to (`find` itself doesn't pre-check them).
pub async fn find(
    tenant: Tenant,
    SessionUser(session_user): SessionUser,
    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
    axum::extract::RawQuery(raw_query): axum::extract::RawQuery,
    Query(qs): Query<FindQuery>,
) -> Response {
    let Some(html_path) = qs.html_path.filter(|p| !p.is_empty()) else {
        return crate::api::error::ApiError::bad_request("missing `html_path` query parameter")
            .into_response();
    };
    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
    let carry = carried_query(raw_query.as_deref());
    match find_inner(&tenant, viewer, &html_path, &carry).await {
        Ok(resp) => resp,
        Err(e) => {
            tracing::error!(target: "rustango_cms::api", error = %e, "page find failed");
            crate::api::error::ApiError::internal().into_response()
        }
    }
}

/// The part of `find/`'s own query string that the detail URL should
/// inherit, rendered as `?a=b&c=d` (or empty).
///
/// A client resolves its route with `find/` and lets `fetch` follow the
/// 302 — that is the whole point of answering with a redirect. But the
/// `Location` named only the id, so every other parameter was dropped in
/// flight: `find/?html_path=/&locale=fr` returned the **English** page,
/// and a SPA had no way to ask for anything else in one hop. Worse, it
/// looked like it had worked; only `meta.locale` gave it away.
///
/// `html_path` is consumed here and must not travel. Everything else is
/// forwarded verbatim, including parameters this endpoint knows nothing
/// about — the detail endpoint ignores names it does not recognise, and
/// hard-coding a list here would silently drop the next one added.
fn carried_query(raw: Option<&str>) -> String {
    let Some(raw) = raw.filter(|r| !r.is_empty()) else {
        return String::new();
    };
    let kept: Vec<&str> = raw
        .split('&')
        .filter(|pair| !pair.is_empty())
        .filter(|pair| {
            let name = pair.split('=').next().unwrap_or("");
            name != "html_path"
        })
        .collect();
    if kept.is_empty() {
        String::new()
    } else {
        format!("?{}", kept.join("&"))
    }
}

async fn find_inner(
    tenant: &Tenant,
    viewer: Option<&rustango::tenancy::auth::User>,
    html_path: &str,
    carry: &str,
) -> Result<Response, rustango::sql::ExecError> {
    let pool = tenant.pool();
    // url_path is stored without a trailing slash (e.g. "/about"); accept
    // either form from callers by trying the path and its slash-variant.
    let mut rows: Vec<Page> = Page::objects()
        .where_(Page::url_path.eq(html_path))
        .fetch(pool)
        .await?;
    if rows.is_empty() {
        let alt = if let Some(stripped) = html_path.strip_suffix('/') {
            stripped.to_owned()
        } else {
            format!("{html_path}/")
        };
        rows = Page::objects()
            .where_(Page::url_path.eq(alt))
            .fetch(pool)
            .await?;
    }
    // `is_public()`, not `Published`: `list`, `tree` and `detail` all
    // serve archived pages, and the tree hands out a `detail_url` for
    // one. Matching on `Published` alone left `find` as the single
    // endpoint that 404'd a page the rest of the API was happy to
    // return — the same contradiction archived pages already caused on
    // `detail`, one endpoint over.
    let hit = rows
        .into_iter()
        .find(|p| PageStatus::str_is_public(&p.status));

    // #members — a gated page must be indistinguishable from a missing
    // one. Redirecting for one and 404-ing for the other turned this
    // endpoint into an oracle: an anonymous caller could walk URLs and
    // learn both which member-only pages exist and their ids, straight
    // out of the `Location` header.
    let id = match hit {
        Some(p) => {
            let pid = p.id.get().copied().unwrap_or_default();
            let denied = crate::view_restriction::denied_page_ids(
                pool,
                viewer,
                &[(pid, p.path.clone(), p.page_type_id)],
            )
            .await;
            if denied.contains(&pid) {
                None
            } else {
                Some(pid)
            }
        }
        None => None,
    };
    match id {
        // 302 Found → detail endpoint (which enforces view restrictions).
        Some(id) => Ok((
            StatusCode::FOUND,
            [(
                axum::http::header::LOCATION,
                format!("/api/v2/pages/{id}/{carry}"),
            )],
        )
            .into_response()),
        // `not_found` appends " not found", so this must be the noun
        // alone — and it must be the *same* noun the detail endpoint
        // uses, because a gated page and a missing one are deliberately
        // indistinguishable here.
        None => Ok(crate::api::error::ApiError::not_found("page").into_response()),
    }
}

async fn detail_inner(
    tenant: &Tenant,
    viewer: Option<&rustango::tenancy::auth::User>,
    headers: &HeaderMap,
    id: i64,
    allow_draft: bool,
    locale_code: Option<&str>,
    fields: Option<&str>,
) -> Result<Response, rustango::sql::ExecError> {
    let pool = tenant.pool();
    let Some(page) = lookup_page(pool, id).await? else {
        return Ok(crate::api::error::ApiError::not_found("page").into_response());
    };
    // Public means `published` **or** `archived` — the same
    // `PageStatus::is_public` test the renderer and sitemap use. Serving
    // only `published` here made `detail` 404 pages that `tree` and
    // `children` list *and* hand out a `detail_url` for, so every
    // archived node advertised a dead link. Drafts still 404 unless a
    // valid preview token unlocked them (#430).
    let is_public = PageStatus::str_is_public(&page.status);
    if !is_public && !allow_draft {
        return Ok(crate::api::error::ApiError::not_found("page").into_response());
    }
    // Honour view restrictions — the same decision the public renderer
    // makes, reported the way a JSON client can act on.
    //
    // The HTML path answers a denial with `303 → /members/login`, which
    // is right for a browser and useless here: `fetch()` follows it and
    // the caller ends up with a login page under status 200, with no
    // signal that it is unauthenticated. So the API renders the same
    // `Denial` as a status code instead.
    if let Some(denial) =
        crate::view_restriction_guard::decide(tenant, &page, viewer, headers).await
    {
        use crate::view_restriction_guard::Denial;
        return Ok(match denial {
            Denial::NeedsLogin => crate::api::error::ApiError::unauthenticated(),
            Denial::Forbidden => crate::api::error::ApiError::forbidden(),
            Denial::NeedsPassword { .. } => crate::api::error::ApiError::password_required(),
        }
        .into_response());
    }

    // #75 — an alias serves the source's content under its own URL. The
    // gating above ran against the alias row (its own restrictions), and
    // only the *content* is borrowed. Without this, detail returned the
    // stale title copied at creation, no `extension` and no `builder`,
    // while `tree` and the renderer all showed the source's live content.
    let mut alias_owned = None;
    if let Some(source_id) = page.alias_of {
        match lookup_page(pool, source_id).await? {
            Some(src) => alias_owned = Some(crate::page::alias_hybrid(&page, &src)),
            None => tracing::warn!(
                target: "rustango_cms::api",
                alias_id = ?page.id.get().copied(),
                source_id,
                "alias source missing — serving the alias row verbatim",
            ),
        }
    }
    let page = alias_owned.as_ref().unwrap_or(&page);

    let type_name = page_type_names(pool)
        .await?
        .get(&page.page_type_id)
        .cloned()
        .unwrap_or_default();
    // Default locale resolves to `None` — canonical content already is
    // the default-locale content, so the overlay would be a wasted query.
    let locale = crate::translation::resolve_locale(pool, locale_code)
        .await
        .ok()
        .flatten();
    // Only a non-default locale needs an overlay — canonical content
    // already *is* the default-locale content.
    let locale_id = locale
        .as_ref()
        .filter(|l| !l.is_default)
        .and_then(|l| l.id.get().copied());
    let mut obj =
        detail_object_with_type(pool, page, &type_name, None, None, locale_id, viewer).await;

    echo_locale(&mut obj, locale.as_ref());

    // Sparse selection, matching the list endpoints.
    let keep = fields.map(|raw| -> std::collections::HashSet<String> {
        raw.split(',')
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_owned)
            .collect()
    });
    q::apply_fields(&mut obj, keep.as_ref());

    Ok(Json(serde_json::Value::Object(obj)).into_response())
}

/// Return `title` only if some published page with that title is visible
/// to `viewer`.
///
/// Used to vet a search suggestion before echoing it back — otherwise the
/// "did you mean?" hint becomes a way to enumerate the titles of pages the
/// caller is not allowed to see.
async fn visible_title(
    pool: &rustango::sql::Pool,
    viewer: Option<&rustango::tenancy::auth::User>,
    title: &str,
) -> Option<String> {
    let matches: Vec<Page> = Page::objects()
        .where_(Page::title.eq(title.to_owned()))
        .where_(Page::status.eq(PageStatus::Published.as_str().to_owned()))
        .fetch(pool)
        .await
        .ok()?;
    if matches.is_empty() {
        return None;
    }
    let triples: Vec<(i64, String, i64)> = matches
        .iter()
        .map(|p| {
            (
                p.id.get().copied().unwrap_or_default(),
                p.path.clone(),
                p.page_type_id,
            )
        })
        .collect();
    let denied = crate::view_restriction::denied_page_ids(pool, viewer, &triples).await;
    triples
        .iter()
        .any(|(id, _, _)| !denied.contains(id))
        .then(|| title.to_owned())
}

/// Echo the locale a detail body was built in as `meta.locale`. An
/// unknown or inactive code falls back to the tenant default silently, so
/// without this a client cannot tell `?locale=fr` from `?locale=fr-typo`.
/// Every page detail body carries it, so the page URL's negotiated JSON
/// stays equal to `/api/v2/pages/{id}/`.
pub(crate) fn echo_locale(
    obj: &mut serde_json::Map<String, serde_json::Value>,
    locale: Option<&crate::locale::Locale>,
) {
    if let Some(meta) = obj.get_mut("meta").and_then(|m| m.as_object_mut()) {
        meta.insert(
            "locale".to_owned(),
            locale.map_or(serde_json::Value::Null, |l| serde_json::Value::String(l.code.clone())),
        );
    }
}

/// Build the canonical page-detail object.
///
/// Shared by `GET /api/v2/pages/{id}/` and the public `Accept`-negotiated
/// JSON view, so the two are byte-identical by construction rather than
/// by discipline — the whole reason the editor's JSON preview can be
/// trusted to show what a client will actually receive.
///
/// The two `Option` parameters are the preview seam. `None` loads from
/// the database, which is what the saved-row API path wants; `Some(_)`
/// substitutes *virtual* values built from unsaved editor form state.
/// Callers that already hold the registry row pass `type_name` directly
/// to skip the full `cms_page_type` scan `page_type_names` performs.
///
/// `locale_id` localizes the result. `None` (or the default locale)
/// returns canonical content; `Some(id)` overlays that locale's
/// `cms_translation` rows — scalars (`title`, `seo_*`, extension fields),
/// per-leaf StreamField overrides, and page-builder text leaves. Every
/// JSON surface shares this, so localizing here localizes the v2 endpoint
/// and the `Accept`-negotiated page view together.
///
/// Note this deliberately performs **no** access control *on the page
/// itself*: the published check and `view_restriction_guard::enforce`
/// live in the callers, because a draft preview must bypass exactly
/// those gates. `viewer` is used only to filter the `children` listing —
/// see `child_summaries`.
pub async fn detail_object_with_type(
    pool: &rustango::sql::Pool,
    page: &Page,
    type_name: &str,
    extension_override: Option<serde_json::Value>,
    builder_override: Option<serde_json::Value>,
    locale_id: Option<i64>,
    viewer: Option<&rustango::tenancy::auth::User>,
) -> serde_json::Map<String, serde_json::Value> {
    let id = page.id.get().copied().unwrap_or_default();
    // #75 — per-type extension rows and builder documents live against
    // the *source* for an alias; the alias row has none of its own. Same
    // resolution the renderer applies (`extension_page_id`).
    let content_id = page.alias_of.unwrap_or(id);
    let mut type_names = std::collections::HashMap::new();
    type_names.insert(page.page_type_id, type_name.to_owned());
    let mut obj = serialize_summary(page, &type_names);

    // Extension fields via the registered handler. `load_extension`
    // is opt-in per handler; the default returns `Value::Null`.
    let handler: Option<Box<dyn PageTypeHandler>> = find_handler(type_name);
    if let Some(h) = handler {
        // #442 — expose this page's routable sub-URL patterns so API
        // consumers can resolve/reverse them client-side. Omitted when
        // the page type declares none.
        let routes = h.routes();
        if !routes.is_empty() {
            let arr: Vec<serde_json::Value> = routes
                .iter()
                .map(|r| serde_json::json!({ "name": r.name, "pattern": r.pattern.as_str() }))
                .collect();
            obj.insert("routes".to_owned(), serde_json::Value::Array(arr));
        }
        let streams = stream_field_names(h.as_ref(), pool, content_id).await;
        match extension_override {
            Some(mut ext) => {
                if !ext.is_null() {
                    decode_stream_fields(&mut ext, &streams);
                    obj.insert("extension".to_owned(), ext);
                }
            }
            None => match h.load_extension(pool, content_id).await {
                Ok(mut ext) if !ext.is_null() => {
                    decode_stream_fields(&mut ext, &streams);
                    obj.insert("extension".to_owned(), ext);
                }
                Ok(_) => {}
                Err(e) => {
                    tracing::warn!(
                        target: "rustango_cms::api",
                        page_id = id,
                        error = %e,
                        "load_extension failed in api detail",
                    );
                }
            },
        }
    }

    // #572 — page-builder body. When the page type has a published schema
    // (code type with a UI body, or a UI-created type), expose the filled,
    // lazily-upgraded values so headless clients render the UI-defined body.
    // Values only — clients render; no server-side zone HTML here.
    //
    // The compiled schema is kept so the localization pass below can reach
    // the builder's text leaves — they are keyed `builder.<path>`, which
    // the flat scalar overlay cannot address.
    let mut compiled_schema = None;
    match builder_override {
        Some(values) => {
            obj.insert("builder".to_owned(), values);
            if locale_id.is_some() {
                compiled_schema = crate::page_builder::values::values_for(
                    pool,
                    content_id,
                    page.page_type_id,
                    None,
                )
                .await
                .map(|(_, c)| c);
            }
        }
        None => {
            if let Some((values, compiled)) =
                crate::page_builder::values::values_for(pool, content_id, page.page_type_id, None)
                    .await
            {
                obj.insert("builder".to_owned(), values);
                compiled_schema = Some(compiled);
            }
        }
    }

    if let Some(lid) = locale_id {
        localize_detail_object(pool, id, type_name, lid, &mut obj, compiled_schema.as_ref()).await;
    }

    // Direct children, so a client can walk the site from any page without
    // first fetching the whole tree. One level only — `/api/v2/pages/tree/`
    // is the endpoint for depth.
    obj.insert(
        "children".to_owned(),
        serde_json::Value::Array(child_summaries(pool, page, viewer, locale_id).await),
    );

    obj
}

/// Most children a detail response will inline.
///
/// `tree` caps itself at `MAX_NODES` and says so via `meta.truncated`;
/// `children` had no equivalent, so a flat blog's homepage returned every
/// one of its posts on every request — including on each
/// `Accept: application/json` render of `/`. Clients that need the whole
/// set have `/api/v2/pages/?child_of=`, which is paged.
pub const MAX_CHILDREN: usize = 100;

/// Summaries of a page's **direct** children — `id, title, slug, url,
/// has_children`.
///
/// One query covers both levels: children *and* grandchildren, sliced by
/// `depth`, so `has_children` costs nothing extra. It filters on `path`
/// rather than `parent_id` because `cms_page` indexes `path` and does not
/// index `parent_id` (`migrations/0001_cms_initial.json`).
///
/// `viewer` gates the listing: without it a page whose child subtree is
/// member-only would publish those titles and URLs to anonymous callers,
/// which is exactly what the restriction is for. This is the *only* thing
/// `detail_object_with_type` uses the viewer for — the page itself is
/// gated by its callers.
async fn child_summaries(
    pool: &rustango::sql::Pool,
    page: &Page,
    viewer: Option<&rustango::tenancy::auth::User>,
    locale_id: Option<i64>,
) -> Vec<serde_json::Value> {
    // An unsaved preview row has no id and therefore no children yet.
    let Some(&parent_id) = page.id.get() else {
        return Vec::new();
    };
    if page.path.is_empty() {
        return Vec::new();
    }

    // Match the public renderer, not `list`: `archived` still resolves to
    // a real URL (`PageStatus::is_public`), so omitting it would advertise
    // fewer children than the site actually serves.
    let statuses = [
        PageStatus::Published.as_str().to_owned(),
        PageStatus::Archived.as_str().to_owned(),
    ];
    let mut rows: Vec<Page> = match Page::objects()
        .where_(Page::path.like(crate::tree::descendants_like(&page.path)))
        .where_(Page::depth.is_in([page.depth + 1, page.depth + 2]))
        .where_(Page::status.is_in(statuses))
        .order_by(&[("path", false)])
        .fetch(pool)
        .await
    {
        Ok(rows) => rows,
        Err(e) => {
            tracing::warn!(
                target: "rustango_cms::api",
                page_id = parent_id,
                error = %e,
                "child summaries lookup failed",
            );
            return Vec::new();
        }
    };

    // Error pages are routing furniture, not site structure — excluded
    // here exactly as `tree` and `auto_menu` exclude them. Without this a
    // 404 handler parented under Home showed up as one of its children.
    let error_tid = crate::error_pages::error_page_type_id(pool).await;
    rows.retain(|p| error_tid.is_none_or(|tid| p.page_type_id != tid));

    // #members — drop what the viewer may not see, before anything is
    // counted, so `has_children` never advertises a gated subtree either.
    let triples: Vec<(i64, String, i64)> = rows
        .iter()
        .map(|p| {
            (
                p.id.get().copied().unwrap_or_default(),
                p.path.clone(),
                p.page_type_id,
            )
        })
        .collect();
    let denied = crate::view_restriction::denied_page_ids(pool, viewer, &triples).await;

    let visible: Vec<&Page> = rows
        .iter()
        .filter(|p| !denied.contains(&p.id.get().copied().unwrap_or_default()))
        // Legacy per-locale variant trees are not children of this page in
        // any sense a client cares about (#275) — `feed` and the tree
        // endpoint drop them too.
        .filter(|p| p.locale_variant_of.is_none())
        .collect();

    let mut grandchildren: std::collections::HashSet<i64> = std::collections::HashSet::new();
    for p in visible.iter().filter(|p| p.depth == page.depth + 2) {
        if let Some(pid) = p.parent_id {
            grandchildren.insert(pid);
        }
    }

    let mut children: Vec<&&Page> = visible
        .iter()
        .filter(|p| p.depth == page.depth + 1)
        .collect();
    // Same ordering the rendered site uses (`sort_order, id`), not the
    // `path` order the query returned — see the note in `api::tree`.
    children.sort_by_key(|p| (p.sort_order, p.id.get().copied().unwrap_or_default()));
    if children.is_empty() {
        return Vec::new();
    }

    // Localized titles for the whole set in one query, never per child.
    let translations = match locale_id {
        Some(lid) => {
            let ids: Vec<i64> = children.iter().filter_map(|p| p.id.get().copied()).collect();
            crate::translation::fetch_for_pages(pool, &ids, lid)
                .await
                .unwrap_or_default()
        }
        None => std::collections::HashMap::new(),
    };

    children
        .into_iter()
        .take(MAX_CHILDREN)
        .map(|p| {
            let id = p.id.get().copied().unwrap_or_default();
            let title = translations
                .get(&id)
                .and_then(|m| m.get("title"))
                .filter(|s| !s.is_empty())
                .cloned()
                .unwrap_or_else(|| p.title.clone());
            serde_json::json!({
                "id": id,
                "title": title,
                "slug": p.slug,
                "url": if p.url_path.is_empty() { "/" } else { p.url_path.as_str() },
                "has_children": grandchildren.contains(&id),
                "detail_url": format!("/api/v2/pages/{id}/"),
            })
        })
        .collect()
}

/// The extension fields this page type declares as StreamFields. Taken from
/// the handler's widgets rather than by sniffing whether a string parses as
/// a JSON array — that heuristic corrupts a prose field whose text happens
/// to look like "[1,2]".
async fn stream_field_names(
    h: &dyn PageTypeHandler,
    pool: &rustango::sql::Pool,
    page_id: i64,
) -> Vec<String> {
    h.widgets(pool, page_id)
        .await
        .unwrap_or_default()
        .into_iter()
        .filter(|w| w.kind == crate::widget::WidgetKind::Stream)
        .map(|w| w.name)
        .collect()
}

/// StreamField columns are stored as JSON text. Hand them to API clients as
/// the block array itself — the same shape `builder` zones already use — so
/// a client never has to parse a string inside the JSON. An empty column is
/// an empty stream; text that is not a JSON array is left as it is.
fn decode_stream_fields(ext: &mut serde_json::Value, names: &[String]) {
    let Some(map) = ext.as_object_mut() else {
        return;
    };
    for name in names {
        let Some(serde_json::Value::String(raw)) = map.get(name) else {
            continue;
        };
        let decoded = if raw.trim().is_empty() {
            serde_json::Value::Array(Vec::new())
        } else {
            match serde_json::from_str::<serde_json::Value>(raw) {
                Ok(v @ serde_json::Value::Array(_)) => v,
                _ => continue,
            }
        };
        map.insert(name.clone(), decoded);
    }
}

/// Overlay one locale's `cms_translation` rows onto a built detail object.
///
/// Three storage shapes, three mechanisms — a single flat overlay cannot
/// cover them, which is why the HTML renderer needs three calls too:
///
/// * **scalars** (`title`, `seo_*`, extension columns, and the legacy
///   whole-body stream blob) — [`crate::translation::overlay_translations`],
///   which replaces only keys the object already carries and recurses into
///   `extension`, matching on its `page_id`.
/// * **StreamField leaves** keyed `<field>.<uuid>.<name>` —
///   [`crate::block::translate::apply_translatable_overrides`], per stream
///   field, since dotted paths address block contents the flat overlay skips.
/// * **page-builder leaves** keyed `builder.<path>` —
///   [`crate::page_builder::values::apply_builder_translations`].
///
/// One `fetch_for_pages` query feeds all three. Missing or empty overrides
/// leave canonical content in place, so a partially-translated page degrades
/// per field rather than blanking.
async fn localize_detail_object(
    pool: &rustango::sql::Pool,
    page_id: i64,
    type_name: &str,
    locale_id: i64,
    obj: &mut serde_json::Map<String, serde_json::Value>,
    compiled: Option<&crate::page_builder::compile::CompiledSchema>,
) {
    let by_page = crate::translation::fetch_for_pages(pool, &[page_id], locale_id)
        .await
        .unwrap_or_default();
    let Some(here) = by_page.get(&page_id) else {
        return; // nothing translated for this page in this locale
    };

    let mut value = serde_json::Value::Object(std::mem::take(obj));
    crate::translation::overlay_translations(&mut value, &by_page);

    // Per-leaf stream overrides. Which extension fields are streams comes
    // from the handler's declared widgets rather than sniffing whether a
    // string happens to parse as a JSON array — that heuristic corrupts a
    // prose field whose text is something like "[1,2]".
    if let Some(h) = find_handler(type_name) {
        let stream_fields = stream_field_names(h.as_ref(), pool, page_id).await;
        if let Some(ext) = value.get_mut("extension") {
            // A whole-body translation row puts the stream back as a JSON
            // string; decode it so the per-leaf overrides below can apply.
            decode_stream_fields(ext, &stream_fields);
            for name in stream_fields {
                if let Some(raw) = ext.get(&name).cloned() {
                    let localized =
                        crate::block::translate::apply_translatable_overrides(&name, &raw, here);
                    if let Some(m) = ext.as_object_mut() {
                        m.insert(name, localized);
                    }
                }
            }
        }
    }

    if let (Some(compiled), Some(builder)) = (compiled, value.get_mut("builder")) {
        if let Some(map) = builder.as_object_mut() {
            crate::page_builder::values::apply_builder_translations(compiled, map, here);
        }
    }

    if let serde_json::Value::Object(m) = value {
        *obj = m;
    }
}

// ---------------------------------------------------------------
// helpers
// ---------------------------------------------------------------

async fn lookup_page(
    pool: &rustango::sql::Pool,
    id: i64,
) -> Result<Option<Page>, rustango::sql::ExecError> {
    let mut rows: Vec<Page> = Page::objects().where_(Page::id.eq(id)).fetch(pool).await?;
    Ok(rows.pop())
}

async fn lookup_page_type(
    pool: &rustango::sql::Pool,
    type_name: &str,
) -> Result<Option<PageType>, rustango::sql::ExecError> {
    let mut rows: Vec<PageType> = PageType::objects()
        .where_(PageType::type_name.eq(type_name.to_owned()))
        .fetch(pool)
        .await?;
    Ok(rows.pop())
}

/// Build a `{ page_type_id → type_name }` lookup so each row can
/// emit its symbolic type in the response without an N+1.
pub(crate) async fn page_type_names(
    pool: &rustango::sql::Pool,
) -> Result<std::collections::HashMap<i64, String>, rustango::sql::ExecError> {
    let rows: Vec<PageType> = PageType::objects().fetch(pool).await?;
    Ok(rows
        .into_iter()
        .filter_map(|pt| pt.id.get().copied().map(|id| (id, pt.type_name)))
        .collect())
}

fn serialize_summary(
    p: &Page,
    type_names: &std::collections::HashMap<i64, String>,
) -> serde_json::Map<String, serde_json::Value> {
    let id = p.id.get().copied().unwrap_or_default();
    let type_name = type_names.get(&p.page_type_id).cloned().unwrap_or_default();
    let mut obj = serde_json::Map::new();
    obj.insert("id".to_owned(), serde_json::json!(id));
    obj.insert(
        "meta".to_owned(),
        serde_json::json!({
            "type": type_name,
            "detail_url": format!("/api/v2/pages/{id}/"),
            "html_url": p.url_path,
            "slug": p.slug,
            "depth": p.depth,
            "parent_id": p.parent_id,
            "alias_of": p.alias_of,
            "first_published_at": p.published_at,
            "updated_at": p.updated_at.get().copied(),
        }),
    );
    obj.insert("title".to_owned(), serde_json::json!(p.title));
    // The same `url` key tree nodes and child summaries use. It is also
    // at `meta.html_url` for compatibility, but a client should not need
    // a different accessor per endpoint to read one field — and unlike
    // `html_url`, this normalizes the root's empty `url_path` to "/",
    // as the other two shapes already did.
    obj.insert(
        "url".to_owned(),
        serde_json::json!(if p.url_path.is_empty() {
            "/"
        } else {
            p.url_path.as_str()
        }),
    );
    obj.insert("seo_title".to_owned(), serde_json::json!(p.seo_title));
    obj.insert(
        "seo_description".to_owned(),
        serde_json::json!(p.seo_description),
    );
    obj.insert("robots_index".to_owned(), serde_json::json!(p.robots_index));
    obj.insert(
        "sitemap_priority".to_owned(),
        serde_json::json!(p.sitemap_priority),
    );
    obj.insert(
        "show_in_menus".to_owned(),
        serde_json::json!(p.show_in_menus),
    );
    obj
}

/// Build the set of ancestor paths for `path` (excluding `path` itself).
/// Mirrors [`crate::tree::MaterializedPath::ancestors`] without needing a
/// `MaterializedPath` value.
fn ancestor_paths_of(path: &str) -> std::collections::HashSet<String> {
    let mut out = std::collections::HashSet::new();
    let mut acc = String::new();
    for seg in path.split('/').filter(|s| !s.is_empty()) {
        acc.push_str(seg);
        acc.push('/');
        if acc != path {
            out.insert(acc.clone());
        }
    }
    out
}

/// Fields `?order=` accepts on this endpoint. Anything else is a `400`
/// — kept next to `compare_pages`, which must handle exactly these.
const PAGE_ORDER_FIELDS: [&str; 8] = [
    "title",
    "slug",
    "url_path",
    "depth",
    "sort_order",
    "published_at",
    "updated_at",
    "created_at",
];

fn compare_pages(a: &Page, b: &Page, specs: &[q::OrderSpec]) -> std::cmp::Ordering {
    for spec in specs {
        let ord = match spec.field.as_str() {
            "title" => a.title.cmp(&b.title),
            "slug" => a.slug.cmp(&b.slug),
            "url_path" => a.url_path.cmp(&b.url_path),
            "depth" => a.depth.cmp(&b.depth),
            "sort_order" => a.sort_order.cmp(&b.sort_order),
            "published_at" => a.published_at.cmp(&b.published_at),
            "updated_at" => a.updated_at.get().cmp(&b.updated_at.get()),
            "created_at" => a.created_at.get().cmp(&b.created_at.get()),
            _ => continue,
        };
        if ord != std::cmp::Ordering::Equal {
            return if spec.descending { ord.reverse() } else { ord };
        }
    }
    // Same reason as the default ordering: a unique last resort, so two
    // rows tied on every requested key still page deterministically.
    a.id.get().cmp(&b.id.get())
}

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

    #[test]
    fn the_resolved_path_is_not_carried_onto_the_detail_url() {
        // `html_path` is what `find/` consumed; repeating it on the
        // detail URL would be noise at best.
        assert_eq!(carried_query(Some("html_path=%2Fabout")), "");
        assert_eq!(carried_query(None), "");
        assert_eq!(carried_query(Some("")), "");
    }

    #[test]
    fn everything_else_survives_the_redirect() {
        // The bug this exists for: a SPA resolving its route with
        // `?locale=fr` followed the 302 and got English back.
        assert_eq!(carried_query(Some("html_path=%2F&locale=fr")), "?locale=fr");
        assert_eq!(
            carried_query(Some("locale=fr&html_path=%2F&fields=title")),
            "?locale=fr&fields=title",
        );
    }

    #[test]
    fn a_parameter_this_endpoint_never_heard_of_is_still_forwarded() {
        // Hard-coding an allowlist here would silently drop whatever the
        // detail endpoint gains next; it ignores names it doesn't know.
        assert_eq!(carried_query(Some("html_path=%2F&whatever=1")), "?whatever=1");
    }

    #[test]
    fn values_are_forwarded_verbatim_not_re_encoded() {
        // Re-encoding risks double-escaping a token that already is.
        assert_eq!(
            carried_query(Some("html_path=%2Fx&preview_token=7.123.ab%2Fcd")),
            "?preview_token=7.123.ab%2Fcd",
        );
    }
}