fraiseql-server 2.16.0

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

#![allow(clippy::unwrap_used, clippy::panic)] // Reason: test code, panics acceptable
use fraiseql_core::schema::{
    ArgumentDefinition, AutoParams, Cardinality, FieldDefinition, FieldType, QueryDefinition,
    Relationship, RestConfig, TypeDefinition,
};

use super::*;

// -----------------------------------------------------------------------
// Test helpers
// -----------------------------------------------------------------------

fn test_config() -> RestConfig {
    RestConfig {
        max_page_size: 100,
        default_page_size: 20,
        max_filter_bytes: 4096,
        ..RestConfig::default()
    }
}

fn user_type_def() -> TypeDefinition {
    TypeDefinition::new("User", "v_user")
        .with_field(FieldDefinition::new("id", FieldType::Uuid))
        .with_field(FieldDefinition::new("name", FieldType::String))
        .with_field(FieldDefinition::new("email", FieldType::String))
        .with_field(FieldDefinition::new("age", FieldType::Int))
        .with_field(FieldDefinition::new("active", FieldType::Boolean))
}

fn list_query_def() -> QueryDefinition {
    QueryDefinition {
        name: "users".to_string(),
        return_type: "User".to_string(),
        returns_list: true,
        auto_params: AutoParams::all(),
        arguments: vec![
            ArgumentDefinition::optional("where", FieldType::Json),
            ArgumentDefinition::optional("orderBy", FieldType::Json),
            ArgumentDefinition::optional("limit", FieldType::Int),
            ArgumentDefinition::optional("offset", FieldType::Int),
        ],
        ..default_query_def()
    }
}

fn single_query_def() -> QueryDefinition {
    QueryDefinition {
        name: "user".to_string(),
        return_type: "User".to_string(),
        returns_list: false,
        arguments: vec![ArgumentDefinition::new("id", FieldType::Uuid)],
        ..default_query_def()
    }
}

fn relay_query_def() -> QueryDefinition {
    QueryDefinition {
        name: "users".to_string(),
        return_type: "User".to_string(),
        returns_list: true,
        relay: true,
        relay_cursor_column: Some("pk_user".to_string()),
        auto_params: AutoParams::all(),
        arguments: vec![
            ArgumentDefinition::optional("first", FieldType::Int),
            ArgumentDefinition::optional("after", FieldType::String),
            ArgumentDefinition::optional("last", FieldType::Int),
            ArgumentDefinition::optional("before", FieldType::String),
        ],
        ..default_query_def()
    }
}

fn default_query_def() -> QueryDefinition {
    QueryDefinition::new("test", "Test")
}

fn extractor_list<'a>(
    config: &'a RestConfig,
    query_def: &'a QueryDefinition,
    type_def: &'a TypeDefinition,
) -> RestParamExtractor<'a> {
    RestParamExtractor::new(config, query_def, Some(type_def))
}

// -----------------------------------------------------------------------
// Path param extraction
// -----------------------------------------------------------------------

#[test]
fn path_param_int_coercion() {
    let config = test_config();
    let qd = QueryDefinition {
        arguments: vec![ArgumentDefinition::new("id", FieldType::Int)],
        ..single_query_def()
    };
    let td = user_type_def();
    let ext = RestParamExtractor::new(&config, &qd, Some(&td));

    let result = ext.extract(&[("id", "123")], &[]).unwrap();
    assert_eq!(result.path_params, vec![("id".to_string(), serde_json::json!(123))]);
}

#[test]
fn path_param_uuid_passthrough() {
    let config = test_config();
    let qd = single_query_def();
    let td = user_type_def();
    let ext = RestParamExtractor::new(&config, &qd, Some(&td));

    let uuid = "550e8400-e29b-41d4-a716-446655440000";
    let result = ext.extract(&[("id", uuid)], &[]).unwrap();
    assert_eq!(result.path_params, vec![("id".to_string(), serde_json::json!(uuid))]);
}

// -----------------------------------------------------------------------
// Offset pagination
// -----------------------------------------------------------------------

#[test]
fn offset_pagination_explicit() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("limit", "10"), ("offset", "5")]).unwrap();
    assert_eq!(
        result.pagination,
        PaginationParams::Offset {
            limit:  10,
            offset: 5,
        }
    );
}

#[test]
fn offset_pagination_defaults() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[]).unwrap();
    assert_eq!(
        result.pagination,
        PaginationParams::Offset {
            limit:  20, // default_page_size
            offset: 0,
        }
    );
}

#[test]
fn limit_clamped_to_max_page_size() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("limit", "500")]).unwrap();
    assert_eq!(
        result.pagination,
        PaginationParams::Offset {
            limit:  100,
            offset: 0,
        }
    );
}

// -----------------------------------------------------------------------
// Cursor (Relay) pagination
// -----------------------------------------------------------------------

#[test]
fn cursor_pagination_explicit() {
    let config = test_config();
    let qd = relay_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("first", "10"), ("after", "abc")]).unwrap();
    assert_eq!(
        result.pagination,
        PaginationParams::Cursor {
            first:  Some(10),
            after:  Some("abc".to_string()),
            last:   None,
            before: None,
        }
    );
}

#[test]
fn cursor_pagination_defaults() {
    let config = test_config();
    let qd = relay_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[]).unwrap();
    assert_eq!(
        result.pagination,
        PaginationParams::Cursor {
            first:  Some(20), // default_page_size
            after:  None,
            last:   None,
            before: None,
        }
    );
}

#[test]
fn first_clamped_to_max_page_size() {
    let config = test_config();
    let qd = relay_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("first", "500")]).unwrap();
    match result.pagination {
        PaginationParams::Cursor { first, .. } => assert_eq!(first, Some(100)),
        other => panic!("expected Cursor, got {other:?}"),
    }
}

// -----------------------------------------------------------------------
// Requested vs resolved pagination (#1273)
//
// Every case here asserts the two fields on the **same** request. A test reading only
// one of them cannot see the distinction they exist to draw, which is how the relay
// export defect survived: `pagination` was correct throughout.
// -----------------------------------------------------------------------

/// An absent `?limit=` stays absent in what the client asked for, while the plan fills it.
///
/// The two mean opposite things to an export: a cap, against "the whole table" (#811).
/// `streaming::helpers::requested_total_limit` used to recover this from the raw query
/// pairs; the extractor now records it.
#[test]
fn an_absent_limit_is_recorded_as_absent_and_still_planned_as_the_default() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[]).unwrap();

    assert_eq!(
        result.pagination,
        PaginationParams::Offset {
            limit:  20,
            offset: 0,
        },
        "the plan still serves the default page"
    );
    assert_eq!(
        result.requested_pagination,
        RequestedPagination::default(),
        "and the request is recorded as having asked for none of it"
    );
}

/// The same, on a relay route — the case #1273 is about.
///
/// `resolve_pagination` fills `first` with `default_page_size` when no cursor parameter is
/// present, so the plan alone cannot say whether the client asked for a page. An export
/// reading the plan refused every request this route was ever offered.
#[test]
fn an_absent_cursor_is_recorded_as_absent_and_still_planned_as_the_default() {
    let config = test_config();
    let qd = relay_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[]).unwrap();

    assert_eq!(
        result.pagination,
        PaginationParams::Cursor {
            first:  Some(20),
            after:  None,
            last:   None,
            before: None,
        },
        "the plan still serves the default page"
    );
    assert_eq!(
        result.requested_pagination,
        RequestedPagination::default(),
        "and no cursor parameter was sent, which is what an export has to be able to see"
    );
}

/// A supplied `?limit=` is recorded **unclamped**, because an export total is not a page.
///
/// `max_page_size` bounds one page of an interactive read (#421); `export_rows` applies the
/// client's total to the stream instead. Clamping what was requested would silently cap
/// every export at one page — the defect #811 fixed.
#[test]
fn a_supplied_limit_is_recorded_unclamped_and_planned_clamped() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("limit", "500")]).unwrap();

    assert_eq!(
        result.pagination,
        PaginationParams::Offset {
            limit:  100, // max_page_size
            offset: 0,
        },
        "a page is bounded by `max_page_size`"
    );
    assert_eq!(
        result.requested_pagination.limit,
        Some(500),
        "an export total is not a page, so what was asked for is kept whole"
    );
}

/// A repeated `?limit=` resolves **once**, so the export and the plan cannot disagree.
///
/// `requested_total_limit` searched the raw pairs — `.find`, first-wins — while the
/// extractor's classification assigns — last-wins. `?limit=5&limit=9` therefore capped an
/// export at 5 rows while every other consumer of the same request read 9. That is #1274's
/// shape (one parameter, two parsers, opposite resolutions) reached through a different
/// parameter, and collapsing the readers is what removes it.
#[test]
fn a_repeated_limit_resolves_once_for_the_plan_and_the_request() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("limit", "5"), ("limit", "9")]).unwrap();

    assert_eq!(
        result.requested_pagination.limit,
        Some(9),
        "last-wins, the same resolution the projection and the plan use"
    );
    assert_eq!(
        result.pagination,
        PaginationParams::Offset {
            limit:  9,
            offset: 0,
        },
        "and the plan agrees, because there is only one reader left"
    );
}

/// Cursor parameters are recorded as sent, each in its own field.
///
/// `first` is the only one `resolve_pagination` ever supplies, so the other three are the
/// evidence a fix reading `requested.first` alone would miss.
#[test]
fn every_cursor_parameter_is_recorded_as_sent() {
    let config = test_config();
    let qd = relay_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let forward = ext.extract(&[], &[("first", "10"), ("after", "abc")]).unwrap();
    assert_eq!(
        forward.requested_pagination,
        RequestedPagination {
            first: Some(10),
            after: Some("abc".to_string()),
            ..RequestedPagination::default()
        }
    );

    let backward = ext.extract(&[], &[("last", "7"), ("before", "xyz")]).unwrap();
    assert_eq!(
        backward.requested_pagination,
        RequestedPagination {
            last: Some(7),
            before: Some("xyz".to_string()),
            ..RequestedPagination::default()
        }
    );
}

/// A single-resource route records nothing, because it parses nothing.
///
/// `?limit=` on `/users/1` has always been accepted and ignored — it is a known parameter
/// on a route that applies no pagination — and recording it would be recording a value the
/// request was not answered under.
#[test]
fn a_single_resource_route_records_no_requested_pagination() {
    let config = test_config();
    let qd = single_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let uuid = "550e8400-e29b-41d4-a716-446655440000";
    let result = ext.extract(&[("id", uuid)], &[("limit", "5")]).unwrap();

    assert_eq!(result.pagination, PaginationParams::None);
    assert_eq!(result.requested_pagination, RequestedPagination::default());
}

// -----------------------------------------------------------------------
// Cross-pagination guards
// -----------------------------------------------------------------------

#[test]
fn relay_rejects_limit_offset() {
    let config = test_config();
    let qd = relay_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let err = ext.extract(&[], &[("limit", "10")]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("cursor-based pagination"), "got: {msg}");
    assert!(msg.contains("first"), "got: {msg}");
}

#[test]
fn offset_rejects_first_after() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let err = ext.extract(&[], &[("first", "10")]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("offset-based pagination"), "got: {msg}");
    assert!(msg.contains("limit"), "got: {msg}");
}

// -----------------------------------------------------------------------
// Simple equality filters
// -----------------------------------------------------------------------

#[test]
fn simple_equality_filter() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("name", "Alice")]).unwrap();
    assert_eq!(result.where_clause, Some(serde_json::json!({ "name": { "eq": "Alice" } })));
}

// -----------------------------------------------------------------------
// Bracket operator filters
// -----------------------------------------------------------------------

#[test]
fn bracket_operator_filter() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("name[icontains]", "Ali")]).unwrap();
    assert_eq!(result.where_clause, Some(serde_json::json!({ "name": { "icontains": "Ali" } })));
}

#[test]
fn bracket_operator_invalid() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let err = ext.extract(&[], &[("name[beginsWith]", "A")]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("Unknown bracket operator"), "got: {msg}");
    assert!(msg.contains("Available bracket operators"), "got: {msg}");
}

// -----------------------------------------------------------------------
// JSON filter
// -----------------------------------------------------------------------

#[test]
fn json_filter_passthrough() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let filter = r#"{"name":{"startswith":"A"}}"#;
    let result = ext.extract(&[], &[("filter", filter)]).unwrap();
    assert_eq!(result.where_clause, Some(serde_json::json!({ "name": { "startswith": "A" } })));
}

#[test]
fn filter_exceeding_max_bytes() {
    let config = RestConfig {
        max_filter_bytes: 10,
        ..test_config()
    };
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let filter = r#"{"name":{"eq":"very long value here"}}"#;
    let err = ext.extract(&[], &[("filter", filter)]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("exceeds maximum size"), "got: {msg}");
}

#[test]
fn filter_unknown_field() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let filter = r#"{"bogus":{"eq":"x"}}"#;
    let err = ext.extract(&[], &[("filter", filter)]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("Unknown field 'bogus'"), "got: {msg}");
    assert!(msg.contains("Available fields"), "got: {msg}");
}

#[test]
fn filter_unknown_operator() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let filter = r#"{"name":{"bogusOp":"x"}}"#;
    let err = ext.extract(&[], &[("filter", filter)]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("Unknown filter operator"), "got: {msg}");
    assert!(msg.contains("Available operators"), "got: {msg}");
}

#[test]
fn filter_nesting_depth_exceeded() {
    let config = test_config();
    let qd = list_query_def();
    // No type_def — skip field validation so deeply nested JSON passes field check.
    let ext = RestParamExtractor::new(&config, &qd, None);

    // Build JSON with depth > 64.
    let mut json = r#""leaf""#.to_string();
    for i in 0..65 {
        json = format!(r#"{{"k{i}":{json}}}"#);
    }
    let filter = &json;
    let err = ext.extract(&[], &[("filter", filter)]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("nesting depth"), "got: {msg}");
}

// -----------------------------------------------------------------------
// Sort
// -----------------------------------------------------------------------

#[test]
fn sort_ascending_descending() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("sort", "name,-age")]).unwrap();
    assert_eq!(
        result.order_by,
        Some(serde_json::json!([
            { "field": "name", "direction": "ASC" },
            { "field": "age", "direction": "DESC" },
        ]))
    );
}

#[test]
fn sort_invalid_field() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let err = ext.extract(&[], &[("sort", "bogus")]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("Unknown field 'bogus'"), "got: {msg}");
}

// -----------------------------------------------------------------------
// Select
// -----------------------------------------------------------------------

#[test]
fn select_fields() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("select", "id,name")]).unwrap();
    assert_eq!(
        result.field_selection,
        RestFieldSpec::Fields(vec!["id".to_string(), "name".to_string()])
    );
}

#[test]
fn select_dot_notation_rejects_non_count_suffix() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let err = ext.extract(&[], &[("select", "address.city")]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("Unsupported dot-suffix"), "got: {msg}");
}

// -----------------------------------------------------------------------
// Unknown param
// -----------------------------------------------------------------------

#[test]
fn unknown_param_rejected() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let err = ext.extract(&[], &[("unknown", "x")]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("Unknown query parameter"), "got: {msg}");
    assert!(msg.contains("Available parameters"), "got: {msg}");
}

// -----------------------------------------------------------------------
// Type coercion
// -----------------------------------------------------------------------

#[test]
fn coerce_int() {
    let result = coerce_to_type("42", &FieldType::Int).unwrap();
    assert_eq!(result, serde_json::json!(42));
}

#[test]
fn coerce_float() {
    let result = coerce_to_type("2.78", &FieldType::Float).unwrap();
    assert_eq!(result, serde_json::json!(2.78));
}

#[test]
fn coerce_boolean_true() {
    assert_eq!(coerce_to_type("true", &FieldType::Boolean).unwrap(), serde_json::json!(true));
    assert_eq!(coerce_to_type("1", &FieldType::Boolean).unwrap(), serde_json::json!(true));
    assert_eq!(coerce_to_type("yes", &FieldType::Boolean).unwrap(), serde_json::json!(true));
}

#[test]
fn coerce_boolean_false() {
    assert_eq!(coerce_to_type("false", &FieldType::Boolean).unwrap(), serde_json::json!(false));
    assert_eq!(coerce_to_type("0", &FieldType::Boolean).unwrap(), serde_json::json!(false));
}

#[test]
fn coerce_boolean_invalid() {
    let err = coerce_to_type("maybe", &FieldType::Boolean).unwrap_err();
    assert!(err.to_string().contains("Expected boolean"), "{err}");
}

#[test]
fn coerce_string_passthrough() {
    let result = coerce_to_type("hello", &FieldType::String).unwrap();
    assert_eq!(result, serde_json::json!("hello"));
}

#[test]
fn coerce_json_value() {
    let result = coerce_to_type(r#"{"key":"val"}"#, &FieldType::Json).unwrap();
    assert_eq!(result, serde_json::json!({"key": "val"}));
}

#[test]
fn coerce_list_csv() {
    let result = coerce_to_type("a,b,c", &FieldType::List(Box::new(FieldType::String))).unwrap();
    assert_eq!(result, serde_json::json!(["a", "b", "c"]));
}

#[test]
fn coerce_list_json_array() {
    let result =
        coerce_to_type(r#"["a","b"]"#, &FieldType::List(Box::new(FieldType::String))).unwrap();
    assert_eq!(result, serde_json::json!(["a", "b"]));
}

// -----------------------------------------------------------------------
// Single-resource endpoint
// -----------------------------------------------------------------------

#[test]
fn single_resource_no_pagination() {
    let config = test_config();
    let qd = single_query_def();
    let td = user_type_def();
    let ext = RestParamExtractor::new(&config, &qd, Some(&td));

    let result = ext.extract(&[("id", "550e8400-e29b-41d4-a716-446655440000")], &[]).unwrap();
    assert_eq!(result.pagination, PaginationParams::None);
}

// -----------------------------------------------------------------------
// Variables count limit
// -----------------------------------------------------------------------

#[test]
fn total_params_exceeding_max() {
    let config = test_config();
    let qd = list_query_def();
    // No type_def to skip field validation.
    let ext = RestParamExtractor::new(&config, &qd, None);

    // Build > 1000 simple filters.
    let pairs: Vec<(String, String)> =
        (0..1001).map(|i| (format!("f{i}"), format!("v{i}"))).collect();
    let query_pairs: Vec<(&str, &str)> =
        pairs.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();

    let err = ext.extract(&[], &query_pairs).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("Too many parameters"), "got: {msg}");
}

// -----------------------------------------------------------------------
// parse_bracket_key helper
// -----------------------------------------------------------------------

#[test]
fn parse_bracket_key_valid() {
    assert_eq!(
        parse_bracket_key("name[icontains]"),
        Some(("name".to_string(), "icontains".to_string()))
    );
}

#[test]
fn parse_bracket_key_no_brackets() {
    assert_eq!(parse_bracket_key("name"), None);
}

#[test]
fn parse_bracket_key_empty_op() {
    assert_eq!(parse_bracket_key("name[]"), None);
}

#[test]
fn parse_bracket_key_empty_field() {
    assert_eq!(parse_bracket_key("[op]"), None);
}

// -----------------------------------------------------------------------
// json_depth helper
// -----------------------------------------------------------------------

#[test]
fn json_depth_flat() {
    assert_eq!(json_depth(&serde_json::json!("hello")), 1);
}

#[test]
fn json_depth_nested_object() {
    assert_eq!(json_depth(&serde_json::json!({"a": {"b": "c"}})), 3);
}

#[test]
fn json_depth_nested_array() {
    assert_eq!(json_depth(&serde_json::json!([[[1]]])), 4);
}

// -----------------------------------------------------------------------
// Parenthetical select parser
// -----------------------------------------------------------------------

#[test]
fn parse_select_entries_flat_fields() {
    let entries = parse_select_entries("id,name,email").unwrap();
    assert_eq!(
        entries,
        vec![
            SelectEntry::Field("id".to_string()),
            SelectEntry::Field("name".to_string()),
            SelectEntry::Field("email".to_string()),
        ]
    );
}

#[test]
fn parse_select_entries_embedded() {
    let entries = parse_select_entries("id,name,posts(id,title)").unwrap();
    assert_eq!(entries.len(), 3);
    assert_eq!(entries[0], SelectEntry::Field("id".to_string()));
    assert_eq!(entries[1], SelectEntry::Field("name".to_string()));
    match &entries[2] {
        SelectEntry::Embedded(spec) => {
            assert_eq!(spec.relationship, "posts");
            assert!(spec.rename.is_none());
            assert_eq!(
                spec.fields,
                vec![
                    SelectEntry::Field("id".to_string()),
                    SelectEntry::Field("title".to_string()),
                ]
            );
        },
        _ => panic!("Expected Embedded"),
    }
}

#[test]
fn parse_select_entries_nested_depth_2() {
    let entries = parse_select_entries("id,posts(id,title,comments(id,body))").unwrap();
    assert_eq!(entries.len(), 2);
    match &entries[1] {
        SelectEntry::Embedded(spec) => {
            assert_eq!(spec.relationship, "posts");
            assert_eq!(spec.fields.len(), 3);
            match &spec.fields[2] {
                SelectEntry::Embedded(inner) => {
                    assert_eq!(inner.relationship, "comments");
                    assert_eq!(
                        inner.fields,
                        vec![
                            SelectEntry::Field("id".to_string()),
                            SelectEntry::Field("body".to_string()),
                        ]
                    );
                },
                _ => panic!("Expected nested Embedded"),
            }
        },
        _ => panic!("Expected Embedded"),
    }
}

#[test]
fn parse_select_entries_rename_syntax() {
    let entries = parse_select_entries("id,author:fk_user(id,name)").unwrap();
    assert_eq!(entries.len(), 2);
    match &entries[1] {
        SelectEntry::Embedded(spec) => {
            assert_eq!(spec.relationship, "fk_user");
            assert_eq!(spec.rename, Some("author".to_string()));
            assert_eq!(
                spec.fields,
                vec![
                    SelectEntry::Field("id".to_string()),
                    SelectEntry::Field("name".to_string()),
                ]
            );
        },
        _ => panic!("Expected Embedded"),
    }
}

#[test]
fn parse_select_entries_count_only() {
    let entries = parse_select_entries("id,posts.count").unwrap();
    assert_eq!(
        entries,
        vec![
            SelectEntry::Field("id".to_string()),
            SelectEntry::Count("posts".to_string()),
        ]
    );
}

#[test]
fn parse_select_entries_unbalanced_parens() {
    let err = parse_select_entries("id,posts(id,title").unwrap_err();
    assert!(err.to_string().contains("Unbalanced parentheses"));
}

#[test]
fn parse_select_entries_invalid_dot_suffix() {
    let err = parse_select_entries("id,posts.foo").unwrap_err();
    assert!(err.to_string().contains("Unsupported dot-suffix"));
}

// -----------------------------------------------------------------------
// Panic surface: multi-byte UTF-8 (H17) and recursion-depth guard (H18)
// -----------------------------------------------------------------------

#[test]
fn parse_select_entries_multibyte_field_does_not_panic() {
    // H17: char positions were used as byte indices, so any multi-byte char
    // before a slice boundary panicked ("byte index N is not a char boundary").
    // `?select=é,id` (percent-decoded) must parse, not abort the worker.
    let entries = parse_select_entries("é,id").expect("multi-byte select must not panic");
    assert_eq!(entries.len(), 2);
    assert!(matches!(&entries[0], SelectEntry::Field(f) if f == "é"));
    assert!(matches!(&entries[1], SelectEntry::Field(f) if f == "id"));
}

#[test]
fn parse_select_entries_multibyte_inside_embedding() {
    // Multi-byte char inside the parenthesised inner slice (H17 site at `inner`).
    let entries = parse_select_entries("posts(café,id)").expect("must not panic");
    let SelectEntry::Embedded(spec) = &entries[0] else {
        panic!("expected embedded spec, got {:?}", entries[0]);
    };
    assert_eq!(spec.relationship, "posts");
    assert_eq!(spec.fields.len(), 2);
    assert!(matches!(&spec.fields[0], SelectEntry::Field(f) if f == "café"));
}

#[test]
fn parse_select_entries_multibyte_count_suffix() {
    // Multi-byte char before a `.count` dot-suffix slice (H17 site at `suffix`).
    let entries = parse_select_entries("café.count").expect("must not panic");
    assert!(matches!(&entries[0], SelectEntry::Count(n) if n == "café"));
}

#[test]
fn parse_select_entries_excessive_nesting_is_rejected_not_overflow() {
    // H18: a shadowed paren counter defeated the recursion-depth guard, so the
    // recursive call always received depth 1 and `MAX_PARSE_DEPTH` never fired —
    // deep `?select=a(a(a(…)))` overflowed the stack (process abort). 40 levels
    // must now be rejected with the depth-limit error, never recursed into.
    let deep = format!("{}{}", "a(".repeat(40), ")".repeat(40));
    let err = parse_select_entries(&deep).expect_err("deep nesting must be rejected");
    assert!(
        err.to_string().contains("nesting depth exceeds maximum"),
        "expected depth-limit error, got: {err}"
    );
}

// -----------------------------------------------------------------------
// Embedding depth validation
// -----------------------------------------------------------------------

#[test]
fn embedding_depth_within_limit() {
    let spec = EmbeddedSpec {
        relationship: "posts".to_string(),
        rename:       None,
        fields:       vec![SelectEntry::Field("id".to_string())],
    };
    assert!(validate_embedding_depth(&spec, 1, 3).is_ok());
}

#[test]
fn embedding_depth_exceeds_limit() {
    let inner = EmbeddedSpec {
        relationship: "comments".to_string(),
        rename:       None,
        fields:       vec![SelectEntry::Field("id".to_string())],
    };
    let outer = EmbeddedSpec {
        relationship: "posts".to_string(),
        rename:       None,
        fields:       vec![SelectEntry::Embedded(inner)],
    };
    // depth=1, max=1 -> inner at depth=2 should fail
    let err = validate_embedding_depth(&outer, 1, 1).unwrap_err();
    assert!(err.to_string().contains("exceeds maximum"));
}

// -----------------------------------------------------------------------
// Embedding relationship validation via extractor
// -----------------------------------------------------------------------

fn user_type_with_relationships() -> TypeDefinition {
    let mut td = user_type_def();
    td.relationships = vec![Relationship {
        name:           "posts".to_string(),
        target_type:    "Post".to_string(),
        foreign_key:    "fk_user".to_string(),
        referenced_key: "pk_user".to_string(),
        cardinality:    Cardinality::OneToMany,
    }];
    td
}

#[test]
fn extract_with_valid_embedding() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_with_relationships();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("select", "id,name,posts(id,title)")]);
    let params = result.unwrap();
    assert_eq!(params.embeddings.len(), 1);
    assert_eq!(params.embeddings[0].relationship, "posts");
}

#[test]
fn extract_with_invalid_relationship() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def(); // No relationships
    let ext = extractor_list(&config, &qd, &td);

    let err = ext.extract(&[], &[("select", "id,comments(id,body)")]).unwrap_err();
    assert!(err.to_string().contains("has no relationship 'comments'"));
    assert!(err.to_string().contains("Available: none"));
}

#[test]
fn extract_with_embedding_filter() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_with_relationships();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(
        &[],
        &[
            ("select", "id,posts(id,title)"),
            ("posts.status", "published"),
        ],
    );
    let params = result.unwrap();
    assert_eq!(params.embedding_filters.len(), 1);
    let posts_filter = params.embedding_filters.get("posts").unwrap();
    assert_eq!(posts_filter, &serde_json::json!({"status": {"eq": "published"}}),);
}

#[test]
fn extract_count_only_embedding() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_with_relationships();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("select", "id,posts.count")]);
    let params = result.unwrap();
    assert_eq!(params.embedding_counts, vec!["posts"]);
}

#[test]
fn extract_embedding_depth_exceeded() {
    let mut config = test_config();
    config.max_embedding_depth = 1;
    let qd = list_query_def();
    let td = user_type_with_relationships();
    let ext = extractor_list(&config, &qd, &td);

    // Depth 2: posts -> comments (but max is 1)
    let err = ext.extract(&[], &[("select", "id,posts(id,comments(id,body))")]).unwrap_err();
    assert!(err.to_string().contains("exceeds maximum"));
}

// -----------------------------------------------------------------------
// Full-text search
// -----------------------------------------------------------------------

fn article_type_def() -> TypeDefinition {
    TypeDefinition::new("Article", "v_article")
        .with_field(FieldDefinition::new("id", FieldType::Uuid))
        .with_field(FieldDefinition::new("title", FieldType::String))
        .with_field(FieldDefinition::new("body", FieldType::String))
        .with_field(FieldDefinition::new("status", FieldType::String))
}

fn article_list_query_def() -> QueryDefinition {
    QueryDefinition {
        name: "articles".to_string(),
        return_type: "Article".to_string(),
        returns_list: true,
        auto_params: AutoParams::all(),
        arguments: vec![
            ArgumentDefinition::optional("where", FieldType::Json),
            ArgumentDefinition::optional("orderBy", FieldType::Json),
            ArgumentDefinition::optional("limit", FieldType::Int),
            ArgumentDefinition::optional("offset", FieldType::Int),
        ],
        ..default_query_def()
    }
}

#[test]
fn search_param_parsed() {
    let config = test_config();
    let qd = article_list_query_def();
    let td = article_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("search", "rust async")]).unwrap();
    assert_eq!(result.search_query, Some("rust async".to_string()));
}

#[test]
fn search_combined_with_filters() {
    let config = test_config();
    let qd = article_list_query_def();
    let td = article_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("search", "rust"), ("status[eq]", "published")]).unwrap();
    assert_eq!(result.search_query, Some("rust".to_string()));
    assert_eq!(
        result.where_clause,
        Some(serde_json::json!({ "status": { "eq": "published" } }))
    );
}

#[test]
fn search_on_resource_without_searchable_fields_fails() {
    let config = test_config();
    let qd = list_query_def();
    // Use a type with no String fields so searchable_fields() returns empty.
    let td = TypeDefinition::new("Counter", "v_counter")
        .with_field(FieldDefinition::new("id", FieldType::Uuid))
        .with_field(FieldDefinition::new("value", FieldType::Int));
    let ext = extractor_list(&config, &qd, &td);

    let err = ext.extract(&[], &[("search", "hello")]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("Full-text search not available"), "got: {msg}");
    assert!(msg.contains("No searchable fields"), "got: {msg}");
}

#[test]
fn search_with_explicit_sort_preserves_sort() {
    let config = test_config();
    let qd = article_list_query_def();
    let td = article_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("search", "rust"), ("sort", "title")]).unwrap();
    assert_eq!(result.search_query, Some("rust".to_string()));
    assert!(result.order_by.is_some());
}

#[test]
fn search_on_single_resource_fails() {
    // `?search=x` on a non-searchable single-resource endpoint fails with
    // "not available" (search is a reserved param, not treated as a filter).
    let config = test_config();
    let qd = single_query_def();
    let td = user_type_def();
    let ext = RestParamExtractor::new(&config, &qd, Some(&td));

    let err = ext
        .extract(&[("id", "550e8400-e29b-41d4-a716-446655440000")], &[("search", "x")])
        .unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("Full-text search not available"), "got: {msg}");
}

// -----------------------------------------------------------------------
// Logical operators
// -----------------------------------------------------------------------

#[test]
fn logical_or_two_conditions() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("or", "(name[eq]=Alice,name[eq]=Bob)")]).unwrap();
    assert_eq!(
        result.where_clause,
        Some(serde_json::json!({
            "_or": [
                { "name": { "eq": "Alice" } },
                { "name": { "eq": "Bob" } }
            ]
        }))
    );
}

#[test]
fn logical_and_explicit() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("and", "(age[gte]=18,age[lte]=65)")]).unwrap();
    assert_eq!(
        result.where_clause,
        Some(serde_json::json!({
            "_and": [
                { "age": { "gte": 18 } },
                { "age": { "lte": 65 } }
            ]
        }))
    );
}

#[test]
fn logical_not() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext.extract(&[], &[("not", "(active[eq]=false)")]).unwrap();
    assert_eq!(
        result.where_clause,
        Some(serde_json::json!({
            "_not": [
                { "active": { "eq": false } }
            ]
        }))
    );
}

#[test]
fn logical_nested_or_and() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext
        .extract(&[], &[("or", "(and=(age[gte]=18,active[eq]=true),name[eq]=admin)")])
        .unwrap();
    let wc = result.where_clause.unwrap();
    assert!(wc.get("_or").is_some(), "expected _or in {wc}");
    let or_arr = wc["_or"].as_array().unwrap();
    assert_eq!(or_arr.len(), 2);
    assert!(or_arr[0].get("_and").is_some(), "expected _and in {}", or_arr[0]);
}

#[test]
fn logical_combined_with_regular_filters() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let result = ext
        .extract(
            &[],
            &[
                ("active[eq]", "true"),
                ("or", "(name[eq]=Alice,name[eq]=Bob)"),
            ],
        )
        .unwrap();

    let wc = result.where_clause.unwrap();
    // Should have _and wrapping the regular filter + the or group.
    assert!(wc.get("_and").is_some(), "expected _and wrapper in {wc}");
}

#[test]
fn logical_depth_exceeded() {
    let config = test_config();
    let qd = list_query_def();
    // No type_def to skip field validation.
    let ext = RestParamExtractor::new(&config, &qd, None);

    // Build deeply nested: or=(and=(or=(and=(...))))
    let mut inner = "name[eq]=x".to_string();
    for _ in 0..65 {
        inner = format!("or=({inner})");
    }
    let input = format!("({inner})");
    let err = ext.extract(&[], &[("or", &input)]).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("nesting depth") || msg.contains("depth"), "got: {msg}");
}

#[test]
fn filter_json_with_logical_operators() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let filter = r#"{"_or":[{"name":{"eq":"Alice"}},{"name":{"eq":"Bob"}}]}"#;
    let result = ext.extract(&[], &[("filter", filter)]).unwrap();
    let wc = result.where_clause.unwrap();
    assert!(wc.get("_or").is_some(), "expected _or in {wc}");
}

#[test]
fn filter_json_with_nested_logical_validates_fields() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let filter = r#"{"_or":[{"bogus":{"eq":"x"}}]}"#;
    let err = ext.extract(&[], &[("filter", filter)]).unwrap_err();
    assert!(err.to_string().contains("Unknown field 'bogus'"));
}

#[test]
fn logical_invalid_syntax() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_def();
    let ext = extractor_list(&config, &qd, &td);

    let err = ext.extract(&[], &[("or", "not-parenthetical")]).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("must be enclosed in parentheses") || msg.contains("syntax"),
        "got: {msg}"
    );
}

// -----------------------------------------------------------------------
// Property test: the select parser never panics on arbitrary UTF-8 (H17/H18)
// -----------------------------------------------------------------------

proptest::proptest! {
    #![proptest_config(proptest::prelude::ProptestConfig::with_cases(2048))]

    /// Arbitrary UTF-8 (including multi-byte chars and adversarial parenthesis
    /// nesting) must produce a `Result`, never a panic or stack overflow.
    #[test]
    fn parse_select_entries_never_panics(input in ".*") {
        let _ = parse_select_entries(&input);
    }
}

// -----------------------------------------------------------------------
// #828 — the REST vocabulary and the executor's vocabulary are one set
// -----------------------------------------------------------------------

/// Every operator this transport accepts must be one the executor can run.
///
/// Both lists this asserts over used to be maintained by hand and disagreed on
/// 27 names, so `?status[ne]=archived` and `?deletedAt[is_null]=true` passed
/// validation here and then failed in the WHERE parser with a 400 — after the
/// surface had already said the request was well-formed.
#[test]
fn every_advertised_rest_operator_parses_in_the_where_builder() {
    for op in BRACKET_OPERATORS {
        assert!(
            fraiseql_core::db::WhereOperator::from_str(op).is_ok(),
            "BRACKET_OPERATORS advertises {op:?} in ?field[op]= syntax, but the WHERE parser \
             rejects it (#828)"
        );
    }
    for op in OPERATOR_REGISTRY.keys() {
        assert!(
            fraiseql_core::db::WhereOperator::from_str(op).is_ok(),
            "the ?filter= error message recommends {op:?}, but the WHERE parser rejects it (#828)"
        );
    }
}

/// A null check takes a boolean, whatever the field's declared type is.
///
/// Coercing the operand to the *field* type produced a JSON string for a
/// `DateTime` field, and the generator's `as_bool().unwrap_or(true)` then read
/// that as "assume IS NULL" — silently inverting `is_null=false`.
#[test]
fn null_check_operands_coerce_to_boolean_not_to_the_field_type() {
    let config = test_config();
    let query_def = list_query_def();
    // A DateTime field: coercing the operand to *this* type is what inverted
    // the check.
    let type_def =
        user_type_def().with_field(FieldDefinition::new("createdAt", FieldType::DateTime));
    let extractor = extractor_list(&config, &query_def, &type_def);

    let params = extractor
        .extract(&[], &[("createdAt[is_null]", "false")])
        .expect("is_null=false is a valid filter");
    let where_clause = params.where_clause.expect("filter produces a where clause");
    assert_eq!(
        where_clause["createdAt"]["is_null"],
        serde_json::Value::Bool(false),
        "operand must be the boolean false, not a DateTime-coerced string: {where_clause}"
    );

    let err = extractor
        .extract(&[], &[("createdAt[is_null]", "yesterday")])
        .expect_err("a non-boolean null-check operand must be refused, not defaulted");
    assert!(
        format!("{err}").contains("boolean"),
        "the error must name the expected type, got: {err}"
    );
}

/// The `OpenAPI` document advertises exactly the operators the validator accepts.
///
/// A third hand-maintained list (`BRACKET_OPERATORS_DESC`) advertised `contains`,
/// which `validate_bracket_operator` rejected, and omitted `istartswith`,
/// `iendswith` and `is_not_null`, which it accepted (#828).
#[test]
fn the_openapi_bracket_operator_list_matches_the_validator() {
    let advertised = crate::routes::rest::openapi::format::bracket_operators_desc();
    let listed: Vec<&str> = advertised.split(", ").collect();
    assert_eq!(
        listed, BRACKET_OPERATORS,
        "the OpenAPI description and the request validator must name one set"
    );
}

// -----------------------------------------------------------------------
// #1279: a dot must not exempt a parameter from the unknown-parameter rule
// -----------------------------------------------------------------------

/// The comparison that makes #1279 a defect: the same misspelling, with and without a dot.
///
/// `?nonsense=x` is refused by name. `?nonsense.field=x` is not — the classification loop
/// `continue`s on any key containing a dot before every check that could refuse it, and
/// `extract_embedding_filters` then stores it with no validation at all. So adding a dot to a
/// misspelled parameter converts a 400 into a silent 200.
#[test]
fn a_dotted_parameter_naming_no_relationship_is_refused() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_with_relationships();
    let ext = extractor_list(&config, &qd, &td);

    let undotted = ext.extract(&[], &[("nonsense", "x")]).unwrap_err();
    assert!(
        undotted.to_string().contains("nonsense"),
        "the control: an unknown parameter is refused by name: {undotted}"
    );

    let dotted = ext
        .extract(&[], &[("nonsense.field", "x")])
        .expect_err("a dot must not exempt a parameter from the unknown-parameter rule");
    assert!(
        dotted.to_string().contains("nonsense"),
        "the refusal names the relationship the type does not have: {dotted}"
    );
}

/// The bracket spelling of the same thing: `?nonsense.field[eq]=x`.
///
/// It takes a different branch — `parse_bracket_key` splits it first, and both the
/// classification loop and `extract_embedding_filters` handle it separately from the simple
/// form. A fix applied to one spelling and not the other leaves the exemption intact.
#[test]
fn a_dotted_bracket_parameter_naming_no_relationship_is_refused() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_with_relationships();
    let ext = extractor_list(&config, &qd, &td);

    let err = ext
        .extract(&[], &[("nonsense.field[eq]", "x")])
        .expect_err("the bracket spelling is exempt by the same mechanism");
    assert!(err.to_string().contains("nonsense"), "the refusal names it: {err}");
}

/// `Prefer: handling=lenient` is the opt-in that grants the exemption deliberately, and a
/// dotted parameter must need it like any other unknown parameter.
///
/// This is the half that says the fix is "apply the existing rule" rather than "refuse dotted
/// keys": under the opt-in the request succeeds and the parameter is dropped, exactly as an
/// unknown undotted parameter is.
#[test]
fn a_dotted_parameter_is_ignored_under_lenient_handling() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_with_relationships();
    let ext = extractor_list(&config, &qd, &td).with_lenient_handling(true);

    let params = ext
        .extract(&[], &[("nonsense.field", "x")])
        .expect("lenient handling ignores an unknown parameter rather than refusing it");
    assert!(
        params.embedding_filters.is_empty(),
        "an ignored parameter must not survive as a filter: {:?}",
        params.embedding_filters
    );
}

/// A relationship the type *does* declare, filtered without being selected: the extractor
/// **accepts** it, and that is the answer #1285 kept.
///
/// It is not accepted because it is honoured. `execute_embeddings` and
/// `execute_embedding_counts` read `embedding_filters` by relationship, once per **selected**
/// embed or count (nested embeds are passed `&no_filters`), so a filter naming neither is read
/// by nothing. #1285 refuses it — in `refuse_unapplied_embedding_filters`, after a
/// representation has been chosen, not here.
///
/// **Why not here**, which is where it most obviously belongs: this function runs before
/// `Accept` is looked at. On an export the same request is already refused by #1275, with the
/// diagnosis an export calls for — "an export carries no embed to filter; request
/// `Accept: application/json` to embed and filter". An extractor-level refusal would replace
/// that with the JSON path's advice, *add `posts(...)` to your `?select=`*, which on an export
/// is a request #1268 refuses. The client would be told to make a request that cannot succeed.
///
/// So the extractor's job here is to produce the filter, and the representation's job is to say
/// what it does with one it cannot apply. This test pins the first half; the second is
/// `handler::tests::unapplied_embedding_filters` and
/// `a_filter_on_a_relationship_this_request_did_not_embed_is_refused`
/// (`rest_embedding_safety_e2e_pg`).
#[test]
fn a_filter_on_an_unselected_relationship_is_accepted_by_the_extractor() {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_with_relationships();
    let ext = extractor_list(&config, &qd, &td);

    let params = ext
        .extract(&[], &[("posts.status", "published")])
        .expect("the extractor produces the filter; the representation decides what to do");
    assert_eq!(
        params.embedding_filters.len(),
        1,
        "an extractor-level refusal would reach the export path too, which needs #1275's \
         diagnosis rather than this one's"
    );

    // The half that must keep working under either answer: the same filter, embed selected.
    let ok = ext
        .extract(
            &[],
            &[
                ("select", "id,posts(id,title)"),
                ("posts.status", "published"),
            ],
        )
        .expect("a filter on a selected embed is the supported request");
    assert_eq!(ok.embedding_filters.len(), 1);
}

// -----------------------------------------------------------------------
// `?rel.limit=n`: an embedded level's page
// -----------------------------------------------------------------------

fn extract_embed_page(pairs: &[(&str, &str)]) -> Result<ExtractedParams, FraiseQLError> {
    let config = test_config();
    let qd = list_query_def();
    let td = user_type_with_relationships();
    let mut query = vec![("select", "id,posts(id,comments(id))")];
    query.extend_from_slice(pairs);
    extractor_list(&config, &qd, &td).extract(&[], &query)
}

/// `?posts.limit=` is the level's page, not a filter on a field called `limit` — which is
/// what it was parsed as before the level had a page to set.
#[test]
fn an_embed_limit_is_a_page_not_a_filter() {
    let params = extract_embed_page(&[("posts.limit", "20")]).unwrap();
    assert_eq!(params.embedding_pages, BTreeMap::from([("posts".to_string(), 20)]));
    assert!(params.embedding_filters.is_empty(), "{:?}", params.embedding_filters);
}

/// A nested level is reached by its dotted relationship path.
#[test]
fn a_nested_embed_limit_is_keyed_by_its_path() {
    let params = extract_embed_page(&[("posts.comments.limit", "5")]).unwrap();
    assert_eq!(params.embedding_pages, BTreeMap::from([("posts.comments".to_string(), 5)]));
}

/// Above the ceiling is refused, naming the parameter — not clamped, which would serve 100
/// rows to a client that asked for 101 and could not tell a short relation from a cut one.
/// At the ceiling is served.
#[test]
fn an_embed_limit_above_the_ceiling_is_refused_not_clamped() {
    let err = extract_embed_page(&[("posts.limit", "101")]).unwrap_err();
    assert!(
        err.to_string()
            .contains("`posts.limit` 101 exceeds the maximum page size of 100"),
        "{err}"
    );
    let params = extract_embed_page(&[("posts.limit", "100")]).unwrap();
    assert_eq!(params.embedding_pages.get("posts"), Some(&100));
}

/// Zero is refused and points at `.count`, which answers "how many" without rows.
#[test]
fn an_embed_limit_of_zero_is_refused() {
    let err = extract_embed_page(&[("posts.limit", "0")]).unwrap_err();
    assert!(err.to_string().contains("Expected a positive integer"), "{err}");
    assert!(err.to_string().contains("`posts.count`"), "{err}");
}

/// `offset`, `order` and `sort` are reserved at the level's position rather than read as
/// filters, so giving a level its own ordering later changes no request's meaning.
#[test]
fn offset_order_and_sort_are_reserved_at_the_level() {
    for name in ["offset", "order", "sort"] {
        let key = format!("posts.{name}");
        let err = extract_embed_page(&[(key.as_str(), "1")]).unwrap_err();
        assert!(err.to_string().contains("reserved"), "{key}: {err}");
    }
}

/// The bracket form still filters a field with a reserved name.
#[test]
fn the_bracket_form_still_filters_a_field_named_limit() {
    let params = extract_embed_page(&[("posts.limit[eq]", "5")]).unwrap();
    assert!(params.embedding_pages.is_empty());
    assert_eq!(
        params.embedding_filters.get("posts"),
        Some(&serde_json::json!({"limit": {"eq": "5"}}))
    );
}