crudcrate 0.9.2

Derive complete REST APIs from Sea-ORM entities — endpoints, filtering, pagination, batch ops, and OpenAPI on Axum
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
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
use sea_orm::{
    Condition, DatabaseBackend,
    sea_query::{Alias, Expr, ExprTrait, LikeExpr, SimpleExpr},
};
use std::collections::HashMap;
use uuid::Uuid;

use super::search::{build_fulltext_condition, build_like_condition, escape_like_wildcards};

// Basic safety limits
const MAX_FIELD_VALUE_LENGTH: usize = 10_000;
const MAX_PAGE_SIZE: u64 = 1000;
const MAX_OFFSET: u64 = 1_000_000;
/// Maximum number of elements accepted in a single array-valued filter.
///
/// An array filter (`filter={"id":[...]}`) becomes one SQL `IN (...)` clause with
/// one bind parameter per element. `MAX_FILTER_CLAUSES` caps the number of keys, not
/// the length of any single array, so without this cap a single key could carry tens
/// of thousands of elements and blow past the backend bind-parameter ceiling (SQLite
/// 32766, Postgres/MySQL 65535). A 500 at the top, a query-planning DoS below it.
/// This bound is also reachable over GET, whose query string is not covered by the
/// request body-size limit. Exceeding it produces `400 Bad Request`, matching the
/// reject-don't-silently-drop policy of `MAX_FILTER_CLAUSES`.
const MAX_FILTER_ARRAY_LEN: usize = 1000;
/// Maximum number of filter clauses accepted per request.
///
/// A malicious client could otherwise submit a filter object with thousands of
/// keys, each producing a SQL condition and potentially blowing up query planning
/// or evaluation time. Legitimate admin dashboards rarely exceed ~20 filter fields
/// (remember comparison operators split one field into two clauses: `year_gte`
/// and `year_lte`), so 100 gives generous headroom while still preventing abuse.
///
/// Exceeding this limit produces a `400 Bad Request` response — crudcrate
/// deliberately does *not* silently drop filters, because a silently-unfiltered
/// response is worse than a failed request.
const MAX_FILTER_CLAUSES: usize = 100;

/// Basic field name validation
fn is_valid_field_name(field_name: &str) -> bool {
    // Strengthen validation to prevent injection attempts (defense-in-depth)
    // Note: Actual field names are validated against a whitelist, but this adds an extra layer
    !field_name.is_empty()
        && field_name.len() <= 100
        && field_name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_')
        && !field_name.starts_with('_')
        && !field_name.starts_with(|c: char| c.is_ascii_digit())
}

/// Basic value length check
const fn validate_field_value(value: &str) -> bool {
    value.len() <= MAX_FIELD_VALUE_LENGTH
}

/// Parse React Admin comparison operator suffixes
/// Returns (`base_field_name`, `sql_operator`) if a suffix is found
fn parse_comparison_operator(field_name: &str) -> Option<(&str, &str)> {
    field_name.strip_suffix("_gte").map_or_else(
        || {
            field_name.strip_suffix("_lte").map_or_else(
                || {
                    field_name.strip_suffix("_gt").map_or_else(
                        || {
                            field_name.strip_suffix("_lt").map_or_else(
                                || {
                                    field_name
                                        .strip_suffix("_neq")
                                        .map(|base_field| (base_field, "!="))
                                },
                                |base_field| Some((base_field, "<")),
                            )
                        },
                        |base_field| Some((base_field, ">")),
                    )
                },
                |base_field| Some((base_field, "<=")),
            )
        },
        |base_field| Some((base_field, ">=")),
    )
}

/// Apply numeric comparison for any numeric type (i64, f64, etc.)
fn apply_numeric_comparison<V>(field_name: &str, operator: &str, value: V) -> SimpleExpr
where
    V: Into<sea_orm::Value> + Copy,
{
    let column = Expr::col(Alias::new(field_name));
    match operator {
        ">=" => column.gte(value),
        "<=" => column.lte(value),
        ">" => column.gt(value),
        "<" => column.lt(value),
        "!=" => column.ne(value),
        _ => column.eq(value), // fallback to equality
    }
}

fn parse_filter_json(
    filter_str: Option<String>,
) -> Result<HashMap<String, serde_json::Value>, crate::errors::ApiError> {
    let Some(filter) = filter_str else {
        return Ok(HashMap::new());
    };

    match serde_json::from_str::<HashMap<String, serde_json::Value>>(&filter) {
        Ok(parsed) => {
            if parsed.len() > MAX_FILTER_CLAUSES {
                tracing::debug!(
                    "Filter has {} clauses, exceeding MAX_FILTER_CLAUSES ({})",
                    parsed.len(),
                    MAX_FILTER_CLAUSES
                );
                return Err(crate::errors::ApiError::bad_request(format!(
                    "Filter contains too many clauses (max {MAX_FILTER_CLAUSES})"
                )));
            }
            // Cap array-valued filters here, at the shared chokepoint, so the bound
            // applies to every element type (UUID/int/string/bool) before it fans out
            // into an `IN (...)` list, and to joined `In` filters too, which also
            // flow through this parser.
            if let Some((key, len)) = parsed.iter().find_map(|(k, v)| match v {
                serde_json::Value::Array(a) if a.len() > MAX_FILTER_ARRAY_LEN => {
                    Some((k.clone(), a.len()))
                }
                _ => None,
            }) {
                tracing::debug!(
                    "Filter key '{key}' has {len} array elements, exceeding MAX_FILTER_ARRAY_LEN ({MAX_FILTER_ARRAY_LEN})"
                );
                return Err(crate::errors::ApiError::bad_request(format!(
                    "Filter array for '{key}' has too many elements (max {MAX_FILTER_ARRAY_LEN})"
                )));
            }
            Ok(parsed)
        }
        Err(_e) => {
            // Invalid JSON is a client error but we preserve historical behavior
            // (ignore and return empty) to avoid breaking callers that pass
            // malformed filters defensively. The MAX_FILTER_CLAUSES path is new
            // and deliberately strict.
            tracing::debug!("Invalid JSON in filter parameter - ignoring filter");
            Ok(HashMap::new())
        }
    }
}

fn handle_fulltext_search<T: crate::traits::CRUDResource>(
    filters: &HashMap<String, serde_json::Value>,
    searchable_columns: &[(&str, impl sea_orm::ColumnTrait)],
    backend: DatabaseBackend,
) -> Option<Condition> {
    if let Some(q_value) = filters.get("q")
        && let Some(q_value_str) = q_value.as_str()
    {
        // Trim and skip empty/whitespace-only queries
        let trimmed_q = q_value_str.trim();
        if trimmed_q.is_empty() {
            return None;
        }

        // Try fulltext search first
        if let Some(fulltext_expr) = build_fulltext_condition::<T>(trimmed_q, backend) {
            return Some(Condition::all().add(fulltext_expr));
        }

        // Fallback to original LIKE search on regular searchable columns
        // Escape LIKE wildcards to prevent wildcard injection
        let escaped_query = escape_like_wildcards(trimmed_q);

        let mut or_conditions = Condition::any();
        for (col_name, col) in searchable_columns {
            if T::is_enum_field(col_name) {
                // Cast enum fields to TEXT for LIKE operations
                match backend {
                    DatabaseBackend::Postgres => {
                        or_conditions = or_conditions.add(
                            SimpleExpr::FunctionCall(sea_orm::sea_query::Func::upper(
                                Expr::cast_as(Expr::col(*col), Alias::new("TEXT")),
                            ))
                            .like(
                                LikeExpr::new(format!("%{}%", escaped_query.to_uppercase()))
                                    .escape('!'),
                            ),
                        );
                    }
                    _ => {
                        // For SQLite/MySQL, treat enum as string
                        or_conditions = or_conditions.add(
                            SimpleExpr::FunctionCall(sea_orm::sea_query::Func::upper(Expr::col(
                                *col,
                            )))
                            .like(
                                LikeExpr::new(format!("%{}%", escaped_query.to_uppercase()))
                                    .escape('!'),
                            ),
                        );
                    }
                }
            } else {
                let cast_type = match backend {
                    DatabaseBackend::MySql => "CHAR",
                    _ => "TEXT",
                };
                or_conditions = or_conditions.add(
                    SimpleExpr::FunctionCall(sea_orm::sea_query::Func::upper(Expr::cast_as(
                        Expr::col(*col),
                        Alias::new(cast_type),
                    )))
                    .like(LikeExpr::new(format!("%{}%", escaped_query.to_uppercase())).escape('!')),
                );
            }
        }
        return Some(or_conditions);
    }
    None
}

/// Apply a string comparison using the given operator.
fn apply_string_comparison(
    column: impl sea_orm::ColumnTrait + Copy,
    operator: &str,
    trimmed_value: &str,
) -> SimpleExpr {
    let col_upper = SimpleExpr::FunctionCall(sea_orm::sea_query::Func::upper(Expr::col(column)));
    let val_upper = trimmed_value.to_uppercase();
    match operator {
        "!=" => col_upper.ne(val_upper),
        ">=" => col_upper.gte(val_upper),
        "<=" => col_upper.lte(val_upper),
        ">" => col_upper.gt(val_upper),
        "<" => col_upper.lt(val_upper),
        _ => col_upper.eq(val_upper),
    }
}

fn process_string_filter<T: crate::traits::CRUDResource>(
    base_field: &str,
    operator: &str,
    string_value: &str,
    column: impl sea_orm::ColumnTrait + Copy,
    backend: DatabaseBackend,
) -> Option<SimpleExpr> {
    if !validate_field_value(string_value) {
        return None;
    }

    let trimmed_value = string_value.trim();
    if trimmed_value.is_empty() {
        return None;
    }

    // Check if this field should use LIKE queries (only for equality, not comparison operators)
    if operator == "=" && T::like_filterable_columns().contains(&base_field) {
        return Some(build_like_condition(base_field, trimmed_value, backend));
    }

    if T::is_enum_field(base_field) {
        // Handle enum fields with case-insensitive matching
        let col_expr = match backend {
            DatabaseBackend::Postgres => Expr::cast_as(Expr::col(column), Alias::new("TEXT")),
            _ => Expr::col(column).into(),
        };
        let col_upper = SimpleExpr::FunctionCall(sea_orm::sea_query::Func::upper(col_expr));
        let val_upper = trimmed_value.to_uppercase();
        return Some(match operator {
            "!=" => col_upper.ne(val_upper),
            ">=" => col_upper.gte(val_upper),
            "<=" => col_upper.lte(val_upper),
            ">" => col_upper.gt(val_upper),
            "<" => col_upper.lt(val_upper),
            _ => col_upper.eq(val_upper),
        });
    }

    // Try to parse as UUID first (only for equality/inequality)
    if let Ok(uuid_value) = Uuid::parse_str(trimmed_value) {
        return Some(match operator {
            "!=" => Expr::col(column).ne(uuid_value),
            _ => Expr::col(column).eq(uuid_value),
        });
    }

    // Case-insensitive string comparison with operator
    Some(apply_string_comparison(column, operator, trimmed_value))
}

fn process_number_filter(
    key: &str,
    number: &serde_json::Number,
    column: impl sea_orm::ColumnTrait + Copy,
    searchable_columns: &[(&str, impl sea_orm::ColumnTrait)],
) -> Option<SimpleExpr> {
    if let Some((base_field, operator)) = parse_comparison_operator(key) {
        // Check if the base field exists in searchable columns
        if searchable_columns
            .iter()
            .any(|(col_name, _)| *col_name == base_field)
        {
            if let Some(int_value) = number.as_i64() {
                return Some(apply_numeric_comparison(base_field, operator, int_value));
            } else if let Some(uint_value) = number.as_u64() {
                // Values above i64::MAX (e.g. a BIGINT UNSIGNED column) must bind as
                // u64, not fall through to a lossy f64 that mis-matches rows.
                return Some(apply_numeric_comparison(base_field, operator, uint_value));
            } else if let Some(float_value) = number.as_f64() {
                return Some(apply_numeric_comparison(base_field, operator, float_value));
            }
        }
    } else {
        // Regular number equality
        if let Some(int_value) = number.as_i64() {
            return Some(Expr::col(column).eq(int_value));
        } else if let Some(uint_value) = number.as_u64() {
            return Some(Expr::col(column).eq(uint_value));
        } else if let Some(float_value) = number.as_f64() {
            return Some(Expr::col(column).eq(float_value));
        }
    }
    None
}

/// Build a type-matched `IN (...)` expression for a homogeneous JSON array so the
/// bound values match the column type on strict backends. Postgres rejects
/// `int_col IN ('1','3')` and `bool_col IN ('true')` (`operator does not exist:
/// integer = text`); SQLite's loose typing silently accepted the stringified form.
/// Returns `None` unless every element is an integer, every element is a number,
/// or every element is a boolean — callers fall back to a string IN list for
/// string/enum/mixed arrays.
fn typed_array_in_list<C: sea_orm::ColumnTrait + Copy>(
    column: C,
    array_values: &[serde_json::Value],
) -> Option<SimpleExpr> {
    if array_values.is_empty() || array_values.len() > MAX_FILTER_ARRAY_LEN {
        return None;
    }
    if array_values.iter().all(serde_json::Value::is_i64) {
        let ints: Vec<i64> = array_values
            .iter()
            .filter_map(serde_json::Value::as_i64)
            .collect();
        return Some(Expr::col(column).is_in(ints));
    }
    if array_values.iter().all(serde_json::Value::is_number) {
        let nums: Vec<f64> = array_values
            .iter()
            .filter_map(serde_json::Value::as_f64)
            .collect();
        if nums.len() == array_values.len() {
            return Some(Expr::col(column).is_in(nums));
        }
    }
    if array_values.iter().all(serde_json::Value::is_boolean) {
        let bools: Vec<bool> = array_values
            .iter()
            .filter_map(serde_json::Value::as_bool)
            .collect();
        return Some(Expr::col(column).is_in(bools));
    }
    None
}

fn process_array_filter(
    array_values: &[serde_json::Value],
    column: impl sea_orm::ColumnTrait + Copy,
    is_enum: bool,
    backend: DatabaseBackend,
) -> Option<SimpleExpr> {
    if array_values.is_empty() || array_values.len() > MAX_FILTER_ARRAY_LEN {
        return None;
    }

    // Try to parse all values as UUIDs first
    let mut uuid_values = Vec::new();
    let mut all_uuids = true;
    for v in array_values {
        if let Some(s) = v.as_str()
            && let Ok(uuid_value) = Uuid::parse_str(s.trim())
        {
            uuid_values.push(uuid_value);
            continue;
        }
        all_uuids = false;
        break;
    }

    if all_uuids && !uuid_values.is_empty() {
        return Some(Expr::col(column).is_in(uuid_values));
    }

    // Type-matched IN list (integers/floats/bools) so the bound values match the
    // column type on strict backends. Enum columns keep the string path below —
    // their casted/uppercased comparison needs text binds.
    if !is_enum && let Some(expr) = typed_array_in_list(column, array_values) {
        return Some(expr);
    }

    // Fall back to string-based IN for non-UUID values
    let in_values: Vec<String> = array_values
        .iter()
        .filter_map(|v| match v {
            serde_json::Value::String(s) => Some(s.clone()),
            serde_json::Value::Number(n) => Some(n.to_string()),
            serde_json::Value::Bool(b) => Some(b.to_string()),
            _ => None,
        })
        .collect();

    if !in_values.is_empty() {
        if is_enum {
            // For enum fields, cast column to TEXT and uppercase both sides
            // so that native PostgreSQL ENUMs work with string bind parameters
            let col_expr = match backend {
                DatabaseBackend::Postgres => Expr::cast_as(Expr::col(column), Alias::new("TEXT")),
                _ => Expr::col(column).into(),
            };
            let col_upper = SimpleExpr::FunctionCall(sea_orm::sea_query::Func::upper(col_expr));
            let upper_values: Vec<String> = in_values.iter().map(|v| v.to_uppercase()).collect();
            return Some(col_upper.is_in(upper_values));
        }
        return Some(Expr::col(column).is_in(in_values));
    }
    None
}

/// Build a Sea-ORM `SimpleExpr` from a column, operator, and a JSON value.
///
/// Used by the derive-macro-generated `resolve_joined_filters` to translate
/// parsed [`crate::filtering::joined::JoinedFilter`] entries into concrete
/// sub-query conditions on child tables.
///
/// Unlike the main-entity filter path, this builder does not apply enum or
/// fulltext normalization — joined filters target plain columns (strings,
/// numbers, UUIDs, bools). Attempts to use range operators (`_gt`, `_gte`,
/// `_lt`, `_lte`) against unsupported value kinds return `None` so the caller
/// can silently skip the filter, matching the existing "skip invalid filters"
/// convention.
///
/// Returns `None` for:
/// - empty strings / overlong strings (> `10_000` chars)
/// - range operators against UUIDs, bools, arrays, or null
/// - `IsNull` / `In` operators against non-matching value kinds
/// - objects as values
#[must_use]
pub fn build_comparison_expr<C>(
    column: C,
    operator: super::joined::FilterOperator,
    value: &serde_json::Value,
) -> Option<SimpleExpr>
where
    C: sea_orm::ColumnTrait + Copy,
{
    use super::joined::FilterOperator;
    use serde_json::Value;

    let col = || Expr::col(column);

    match value {
        Value::String(s) => {
            if !validate_field_value(s) {
                return None;
            }
            let trimmed = s.trim();
            if trimmed.is_empty() {
                return None;
            }

            // Try UUID first — ranges on UUIDs are meaningless, so only allow eq/neq
            if let Ok(uuid_val) = Uuid::parse_str(trimmed) {
                return match operator {
                    FilterOperator::Eq => Some(col().eq(uuid_val)),
                    FilterOperator::Neq => Some(col().ne(uuid_val)),
                    _ => None,
                };
            }

            match operator {
                FilterOperator::Eq => Some(col().eq(trimmed)),
                FilterOperator::Neq => Some(col().ne(trimmed)),
                FilterOperator::Gt => Some(col().gt(trimmed)),
                FilterOperator::Gte => Some(col().gte(trimmed)),
                FilterOperator::Lt => Some(col().lt(trimmed)),
                FilterOperator::Lte => Some(col().lte(trimmed)),
                FilterOperator::Like => {
                    let escaped = escape_like_wildcards(trimmed);
                    Some(col().like(LikeExpr::new(format!("%{escaped}%")).escape('!')))
                }
                FilterOperator::In | FilterOperator::IsNull => None,
            }
        }
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                return match operator {
                    FilterOperator::Eq => Some(col().eq(i)),
                    FilterOperator::Neq => Some(col().ne(i)),
                    FilterOperator::Gt => Some(col().gt(i)),
                    FilterOperator::Gte => Some(col().gte(i)),
                    FilterOperator::Lt => Some(col().lt(i)),
                    FilterOperator::Lte => Some(col().lte(i)),
                    _ => None,
                };
            }
            // Values above i64::MAX bind as u64 rather than falling through to a
            // lossy f64 (a BIGINT UNSIGNED column would otherwise mis-compare).
            if let Some(u) = n.as_u64() {
                return match operator {
                    FilterOperator::Eq => Some(col().eq(u)),
                    FilterOperator::Neq => Some(col().ne(u)),
                    FilterOperator::Gt => Some(col().gt(u)),
                    FilterOperator::Gte => Some(col().gte(u)),
                    FilterOperator::Lt => Some(col().lt(u)),
                    FilterOperator::Lte => Some(col().lte(u)),
                    _ => None,
                };
            }
            if let Some(f) = n.as_f64() {
                return match operator {
                    FilterOperator::Eq => Some(col().eq(f)),
                    FilterOperator::Neq => Some(col().ne(f)),
                    FilterOperator::Gt => Some(col().gt(f)),
                    FilterOperator::Gte => Some(col().gte(f)),
                    FilterOperator::Lt => Some(col().lt(f)),
                    FilterOperator::Lte => Some(col().lte(f)),
                    _ => None,
                };
            }
            None
        }
        Value::Bool(b) => match operator {
            FilterOperator::Eq => Some(col().eq(*b)),
            FilterOperator::Neq => Some(col().ne(*b)),
            _ => None,
        },
        Value::Array(arr) => {
            if arr.is_empty() || arr.len() > MAX_FILTER_ARRAY_LEN {
                return None;
            }
            // Type-matched IN list so integer/float/bool arrays bind as their
            // native type (Postgres rejects `int_col IN ('1','3')`).
            if let Some(expr) = typed_array_in_list(column, arr) {
                return Some(expr);
            }
            let strings: Vec<String> = arr
                .iter()
                .filter_map(|v| match v {
                    Value::String(s) => Some(s.clone()),
                    Value::Number(n) => Some(n.to_string()),
                    Value::Bool(b) => Some(b.to_string()),
                    _ => None,
                })
                .collect();
            if strings.is_empty() {
                return None;
            }
            Some(col().is_in(strings))
        }
        Value::Null => match operator {
            FilterOperator::Eq | FilterOperator::IsNull => Some(col().is_null()),
            FilterOperator::Neq => Some(col().is_not_null()),
            _ => None,
        },
        Value::Object(_) => None,
    }
}

/// Build a Sea-ORM `Condition` from a JSON filter string.
///
/// # Errors
/// Returns `ApiError::BadRequest` if the filter contains more than
/// [`MAX_FILTER_CLAUSES`] keys.
pub fn apply_filters<T: crate::traits::CRUDResource>(
    filter_str: Option<String>,
    searchable_columns: &[(&str, impl sea_orm::ColumnTrait)],
    backend: DatabaseBackend,
) -> Result<Condition, crate::errors::ApiError> {
    let filters = parse_filter_json(filter_str)?;
    let mut condition = Condition::all();

    // Handle fulltext search
    if let Some(fulltext_condition) =
        handle_fulltext_search::<T>(&filters, searchable_columns, backend)
    {
        condition = condition.add(fulltext_condition);
    }

    // Process other filters (excluding 'q')
    for (key, value) in &filters {
        if key == "q" {
            continue; // Skip fulltext search, already handled
        }

        // Validate field name
        if !is_valid_field_name(key) {
            continue;
        }

        // Parse comparison operator to get base field name
        // For "year_neq", this extracts "year" and stores the operator
        let (base_field, operator) = parse_comparison_operator(key).unwrap_or((key, "="));

        // Find the column in searchable columns using the BASE field name
        let column_opt = searchable_columns
            .iter()
            .find(|(col_name, _)| *col_name == base_field)
            .map(|(_, col)| col);

        if let Some(column) = column_opt {
            // Handle different value types
            let filter_condition = match value {
                serde_json::Value::String(string_value) => {
                    process_string_filter::<T>(base_field, operator, string_value, *column, backend)
                }
                serde_json::Value::Number(number) => {
                    process_number_filter(key, number, *column, searchable_columns)
                }
                serde_json::Value::Bool(bool_value) => Some(Expr::col(*column).eq(*bool_value)),
                serde_json::Value::Array(array_values) => process_array_filter(
                    array_values,
                    *column,
                    T::is_enum_field(base_field),
                    backend,
                ),
                serde_json::Value::Null => Some(if operator == "!=" {
                    Expr::col(*column).is_not_null()
                } else {
                    Expr::col(*column).is_null()
                }),
                serde_json::Value::Object(_) => None, // Skip unsupported value types
            };

            if let Some(filter_expr) = filter_condition {
                condition = condition.add(filter_expr);
            }
        }
    }

    Ok(condition)
}

#[must_use]
pub fn parse_range(range_str: Option<String>) -> (u64, u64) {
    range_str.map_or((0, 9), |r| {
        serde_json::from_str::<[u64; 2]>(&r).map_or((0, 9), |range| (range[0], range[1]))
    })
}

#[must_use]
pub fn parse_pagination(params: &crate::models::FilterOptions) -> (u64, u64) {
    if let (Some(page), Some(per_page)) = (params.page, params.per_page) {
        // Standard REST pagination (1-based page numbers)
        // Enforce maximum page size to prevent DoS
        let safe_per_page = per_page.min(MAX_PAGE_SIZE);

        // Use saturating_mul to prevent overflow panic
        let offset = (page.saturating_sub(1)).saturating_mul(safe_per_page);

        // Enforce maximum offset to prevent excessive database queries
        let safe_offset = offset.min(MAX_OFFSET);

        (safe_offset, safe_per_page)
    } else if let Some(range) = &params.range {
        // React Admin pagination
        let (start, end) = parse_range(Some(range.clone()));
        // saturating_add: a client-supplied end of u64::MAX would otherwise overflow
        // the `+ 1` (panic in debug/test, silent wrap-to-zero in release).
        let limit = end
            .saturating_sub(start)
            .saturating_add(1)
            .min(MAX_PAGE_SIZE);
        let safe_start = start.min(MAX_OFFSET);
        (safe_start, limit)
    } else {
        // Default pagination
        (0, 10)
    }
}

/// Parse filters with support for dot-notation filtering on joined entities.
///
/// This function separates filters into:
/// - Main entity filters (applied to the primary table)
/// - Joined entity filters (applied after joining related tables)
///
/// # Example
///
/// ```text
/// Input:  filter={"name":"John","vehicles.make":"BMW","vehicles.year_gte":2020}
/// Output: main_condition: name = 'John'
///         joined_filters: [vehicles.make = 'BMW', vehicles.year >= 2020]
/// ```
/// Parse filters with support for dot-notation joined-entity filters.
///
/// # Errors
/// Returns `ApiError::BadRequest` if the filter contains more than
/// [`MAX_FILTER_CLAUSES`] keys.
pub fn apply_filters_with_joins<T: crate::traits::CRUDResource>(
    filter_str: Option<String>,
    searchable_columns: &[(&str, impl sea_orm::ColumnTrait)],
    backend: DatabaseBackend,
) -> Result<super::joined::ParsedFilters, crate::errors::ApiError> {
    use super::joined::{JoinedFilter, ParsedFilters, parse_dot_notation};

    let filters = parse_filter_json(filter_str)?;
    let mut result = ParsedFilters::default();

    // Get allowed joined columns for validation
    let joined_filterable = T::joined_filterable_columns();

    // Handle fulltext search (always goes to main condition)
    if let Some(fulltext_condition) =
        handle_fulltext_search::<T>(&filters, searchable_columns, backend)
    {
        result.main_condition = result.main_condition.add(fulltext_condition);
    }

    // Process other filters
    for (key, value) in &filters {
        if key == "q" {
            continue; // Skip fulltext search, already handled
        }

        // Check if this is a dot-notation filter (e.g., "vehicles.make")
        if let Some((join_field, column, operator)) = parse_dot_notation(key) {
            // Validate against allowed joined columns
            let full_path_for_check = format!("{join_field}.{column}");
            let is_allowed = joined_filterable
                .iter()
                .any(|c| c.full_path == full_path_for_check);

            if is_allowed {
                result.joined_filters.push(JoinedFilter {
                    join_field,
                    column,
                    operator,
                    value: value.clone(),
                });
                result.has_joined_filters = true;
            }
            // Skip invalid joined filters silently (security: don't expose schema)
            continue;
        }

        // Regular filter - validate field name and apply to main condition
        if !is_valid_field_name(key) {
            continue;
        }

        // Parse comparison operator to get base field name
        let (base_field, operator) = parse_comparison_operator(key).unwrap_or((key, "="));

        // Find the column in searchable columns using the BASE field name
        let column_opt = searchable_columns
            .iter()
            .find(|(col_name, _)| *col_name == base_field)
            .map(|(_, col)| col);

        if let Some(column) = column_opt {
            // Handle different value types (same as apply_filters)
            let filter_condition = match value {
                serde_json::Value::String(string_value) => {
                    process_string_filter::<T>(base_field, operator, string_value, *column, backend)
                }
                serde_json::Value::Number(number) => {
                    process_number_filter(key, number, *column, searchable_columns)
                }
                serde_json::Value::Bool(bool_value) => Some(Expr::col(*column).eq(*bool_value)),
                serde_json::Value::Array(array_values) => process_array_filter(
                    array_values,
                    *column,
                    T::is_enum_field(base_field),
                    backend,
                ),
                serde_json::Value::Null => Some(if operator == "!=" {
                    Expr::col(*column).is_not_null()
                } else {
                    Expr::col(*column).is_null()
                }),
                serde_json::Value::Object(_) => None,
            };

            if let Some(filter_expr) = filter_condition {
                result.main_condition = result.main_condition.add(filter_expr);
            }
        }
    }

    Ok(result)
}

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

    /// Test that malicious field names are rejected
    #[test]
    fn test_field_name_validation_rejects_sql_injection() {
        // These are currently rejected by the basic validation
        let rejected_names = vec![
            "../../../etc/passwd", // Path traversal (contains ..)
            "id..name",            // Double dots
            "_internal",           // Starts with underscore
            "",                    // Empty
        ];

        for malicious_name in rejected_names {
            assert!(
                !is_valid_field_name(malicious_name),
                "Should reject malicious field name: {malicious_name}"
            );
        }

        // Test too long separately
        let too_long = "a".repeat(101);
        assert!(
            !is_valid_field_name(&too_long),
            "Should reject field names longer than 100 chars"
        );
    }

    /// Test that valid field names are accepted
    #[test]
    fn test_field_name_validation_accepts_valid_names() {
        let valid_names = vec!["id", "user_name", "created_at", "field123"];

        for valid_name in valid_names {
            assert!(
                is_valid_field_name(valid_name),
                "Should accept valid field name: {valid_name}"
            );
        }

        // Test max length separately
        let max_length_name = "a".repeat(100);
        assert!(
            is_valid_field_name(&max_length_name),
            "Should accept 100-char field name"
        );
    }

    /// Test that excessively long field values are rejected
    #[test]
    fn test_field_value_length_validation() {
        let short_value = "a".repeat(100);
        let max_value = "a".repeat(MAX_FIELD_VALUE_LENGTH);
        let too_long_value = "a".repeat(MAX_FIELD_VALUE_LENGTH + 1);

        assert!(
            validate_field_value(&short_value),
            "Short values should be valid"
        );
        assert!(
            validate_field_value(&max_value),
            "Max length values should be valid"
        );
        assert!(
            !validate_field_value(&too_long_value),
            "Overly long values should be invalid"
        );
    }

    /// TDD: Pagination should enforce maximum page size
    /// This test will FAIL until we add `MAX_PAGE_SIZE` enforcement
    #[test]
    fn test_pagination_enforces_max_page_size() {
        const MAX_PAGE_SIZE: u64 = 1000;

        let params = crate::models::FilterOptions {
            page: Some(1),
            per_page: Some(999_999), // Requesting huge page size
            ..Default::default()
        };

        let (_offset, limit) = parse_pagination(&params);

        // After fix: Should be capped at MAX_PAGE_SIZE
        assert!(
            limit <= MAX_PAGE_SIZE,
            "Page size should be capped at {MAX_PAGE_SIZE}, got {limit}"
        );
    }

    /// TDD: Pagination should enforce maximum offset
    /// This test will FAIL until we add `MAX_OFFSET` enforcement
    #[test]
    fn test_pagination_enforces_max_offset() {
        const MAX_OFFSET: u64 = 1_000_000;

        let params = crate::models::FilterOptions {
            page: Some(1_000_000), // Huge page number
            per_page: Some(100),
            ..Default::default()
        };

        let (offset, _limit) = parse_pagination(&params);

        // After fix: Should be capped at MAX_OFFSET
        assert!(
            offset <= MAX_OFFSET,
            "Offset should be capped at {MAX_OFFSET}, got {offset}"
        );
    }

    /// TDD: Pagination should handle overflow with `saturating_mul`
    /// This test will FAIL until we fix the overflow panic
    #[test]
    fn test_pagination_handles_overflow_gracefully() {
        let params = crate::models::FilterOptions {
            page: Some(u64::MAX),
            per_page: Some(u64::MAX),
            ..Default::default()
        };

        // Should NOT panic - should use saturating arithmetic
        let (_offset, _limit) = parse_pagination(&params);
        // After fix: This should succeed without panic
    }

    /// Test comparison operator parsing
    #[test]
    fn test_comparison_operator_parsing() {
        assert_eq!(parse_comparison_operator("age_gte"), Some(("age", ">=")));
        assert_eq!(parse_comparison_operator("age_lte"), Some(("age", "<=")));
        assert_eq!(parse_comparison_operator("age_gt"), Some(("age", ">")));
        assert_eq!(parse_comparison_operator("age_lt"), Some(("age", "<")));
        assert_eq!(parse_comparison_operator("age_neq"), Some(("age", "!=")));
        assert_eq!(parse_comparison_operator("age"), None);
    }

    /// The LIKE paths in this module share search.rs's `!`-based escaper, which is
    /// always paired with an explicit `ESCAPE '!'` clause (see
    /// `test_build_comparison_expr_like_escapes_wildcards`). Backslash escaping was
    /// removed because it is a no-op on SQLite (`.like()` emits no ESCAPE clause).
    #[test]
    fn test_escape_like_wildcards() {
        assert_eq!(escape_like_wildcards("normal text"), "normal text");
        assert_eq!(escape_like_wildcards("test%"), "test!%");
        assert_eq!(escape_like_wildcards("test_value"), "test!_value");
        assert_eq!(escape_like_wildcards("%_"), "!%!_");
        assert_eq!(escape_like_wildcards("!"), "!!");
        assert_eq!(escape_like_wildcards("100% complete"), "100!% complete");
    }

    // ========================================================================
    // build_comparison_expr — direct coverage of the public joined-filter
    // expression builder used by derive-generated resolve_joined_filters.
    // ========================================================================

    mod cmp_entity {
        use sea_orm::entity::prelude::*;

        #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
        #[sea_orm(table_name = "cmp_things")]
        pub struct Model {
            #[sea_orm(primary_key)]
            pub id: i32,
            pub name: String,
        }

        #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
        pub enum Relation {}

        impl ActiveModelBehavior for ActiveModel {}
    }

    use crate::filtering::joined::FilterOperator;

    /// Render an expression to inlined SQLite SQL so the ESCAPE clause and the
    /// (escaped) bound pattern are both visible as text.
    fn cmp_sql(expr: SimpleExpr) -> String {
        use sea_orm::sea_query::{Query, SqliteQueryBuilder};
        Query::select()
            .column(cmp_entity::Column::Id)
            .from(cmp_entity::Entity)
            .and_where(expr)
            .to_string(SqliteQueryBuilder)
    }

    /// A1 regression: the joined `_like` path must escape user wildcards with `!`
    /// AND declare `ESCAPE '!'` so the escaping is not a no-op on SQLite.
    #[test]
    fn test_build_comparison_expr_like_escapes_wildcards() {
        let expr = build_comparison_expr(
            cmp_entity::Column::Name,
            FilterOperator::Like,
            &serde_json::json!("100%"),
        )
        .expect("Like on a string builds an expression");
        let sql = cmp_sql(expr);
        assert!(
            sql.contains("ESCAPE '!'"),
            "LIKE must declare ESCAPE '!': {sql}"
        );
        assert!(
            sql.contains("100!%"),
            "user-supplied wildcard must be escaped with !: {sql}"
        );
    }

    #[test]
    fn test_build_comparison_expr_string_ops_build() {
        for op in [
            FilterOperator::Eq,
            FilterOperator::Neq,
            FilterOperator::Gt,
            FilterOperator::Gte,
            FilterOperator::Lt,
            FilterOperator::Lte,
        ] {
            assert!(
                build_comparison_expr(cmp_entity::Column::Name, op, &serde_json::json!("abc"))
                    .is_some(),
                "string {op:?} should build an expression"
            );
        }
    }

    #[test]
    fn test_build_comparison_expr_empty_and_overlong_string_none() {
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Eq,
                &serde_json::json!("")
            )
            .is_none()
        );
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Eq,
                &serde_json::json!("   "),
            )
            .is_none()
        );
        let overlong = "a".repeat(10_001);
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Eq,
                &serde_json::json!(overlong),
            )
            .is_none()
        );
    }

    #[test]
    fn test_build_comparison_expr_uuid_only_eq_neq() {
        let uuid = "550e8400-e29b-41d4-a716-446655440000";
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Eq,
                &serde_json::json!(uuid)
            )
            .is_some()
        );
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Neq,
                &serde_json::json!(uuid)
            )
            .is_some()
        );
        // Ranges and LIKE on a UUID are meaningless -> None.
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Gt,
                &serde_json::json!(uuid)
            )
            .is_none()
        );
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Like,
                &serde_json::json!(uuid)
            )
            .is_none()
        );
    }

    #[test]
    fn test_build_comparison_expr_number_ops_and_rejections() {
        for op in [
            FilterOperator::Eq,
            FilterOperator::Neq,
            FilterOperator::Gt,
            FilterOperator::Gte,
            FilterOperator::Lt,
            FilterOperator::Lte,
        ] {
            assert!(
                build_comparison_expr(cmp_entity::Column::Id, op, &serde_json::json!(42)).is_some()
            );
            assert!(
                build_comparison_expr(cmp_entity::Column::Id, op, &serde_json::json!(3.5))
                    .is_some()
            );
        }
        // In / IsNull are not valid against a scalar number -> None.
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Id,
                FilterOperator::In,
                &serde_json::json!(42)
            )
            .is_none()
        );
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Id,
                FilterOperator::IsNull,
                &serde_json::json!(42),
            )
            .is_none()
        );
    }

    /// A JSON integer above `i64::MAX` must bind as an exact `u64`, not fall through
    /// to a lossy `f64`. 9223372036854775810 (= i64::MAX as u64 + 3) is NOT exactly
    /// representable in `f64` (it rounds to 9223372036854775808), so the rendered SQL
    /// proves whether the value was preserved.
    #[test]
    fn test_build_comparison_expr_u64_above_i64_max_binds_exact() {
        let big: u64 = (i64::MAX as u64) + 3;
        assert_eq!(big, 9_223_372_036_854_775_810);
        let v = serde_json::json!(big);
        assert!(v.as_i64().is_none(), "value must exceed i64::MAX");

        let expr = build_comparison_expr(cmp_entity::Column::Id, FilterOperator::Gte, &v)
            .expect("u64 value builds an expression");
        let sql = cmp_sql(expr);
        assert!(
            sql.contains("9223372036854775810"),
            "u64 above i64::MAX must bind exactly, got lossy SQL: {sql}"
        );
    }

    /// Direct callers of the public `build_comparison_expr` are also protected: an
    /// array longer than the element cap yields `None` instead of an oversized `IN`.
    #[test]
    fn test_build_comparison_expr_rejects_overlong_array() {
        let arr: Vec<serde_json::Value> = (0..=super::MAX_FILTER_ARRAY_LEN as i64)
            .map(|n| serde_json::json!(n))
            .collect();
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Id,
                FilterOperator::In,
                &serde_json::Value::Array(arr)
            )
            .is_none(),
            "array over MAX_FILTER_ARRAY_LEN must not build an IN expression"
        );
    }

    #[test]
    fn test_build_comparison_expr_bool_eq_neq_only() {
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Eq,
                &serde_json::json!(true)
            )
            .is_some()
        );
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Neq,
                &serde_json::json!(false),
            )
            .is_some()
        );
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Gt,
                &serde_json::json!(true)
            )
            .is_none()
        );
    }

    #[test]
    fn test_build_comparison_expr_array_null_object() {
        // Non-empty array -> IN.
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::In,
                &serde_json::json!(["a", "b"]),
            )
            .is_some()
        );
        // Empty array, or an array of only objects (no extractable scalars) -> None.
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::In,
                &serde_json::json!([])
            )
            .is_none()
        );
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::In,
                &serde_json::json!([{"k": "v"}]),
            )
            .is_none()
        );
        // Null + Eq/IsNull -> IS NULL; Null + Neq -> IS NOT NULL; other operators -> None.
        let eq_null = build_comparison_expr(
            cmp_entity::Column::Name,
            FilterOperator::Eq,
            &serde_json::Value::Null,
        )
        .expect("Eq + null builds an expression");
        assert!(
            cmp_sql(eq_null).contains("IS NULL"),
            "Eq + null must render IS NULL"
        );
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::IsNull,
                &serde_json::Value::Null,
            )
            .is_some()
        );
        let neq_null = build_comparison_expr(
            cmp_entity::Column::Name,
            FilterOperator::Neq,
            &serde_json::Value::Null,
        )
        .expect("Neq + null builds an expression");
        assert!(
            cmp_sql(neq_null).contains("IS NOT NULL"),
            "Neq + null must render IS NOT NULL (paired/has-value filter)"
        );
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Gt,
                &serde_json::Value::Null
            )
            .is_none()
        );
        // Object value is unsupported -> None.
        assert!(
            build_comparison_expr(
                cmp_entity::Column::Name,
                FilterOperator::Eq,
                &serde_json::json!({"k": "v"}),
            )
            .is_none()
        );
    }

    /// Test numeric comparison operators
    #[test]
    fn test_apply_numeric_comparison() {
        // Test that we can apply various comparison operators
        let gte_expr = apply_numeric_comparison("age", ">=", 18);
        let sql = format!("{gte_expr:?}");
        assert!(sql.contains("age") && sql.contains("18"));

        let lte_expr = apply_numeric_comparison("price", "<=", 100.50);
        let sql = format!("{lte_expr:?}");
        assert!(sql.contains("price"));

        let gt_expr = apply_numeric_comparison("count", ">", 0);
        let sql = format!("{gt_expr:?}");
        assert!(sql.contains("count") && sql.contains("0"));

        let lt_expr = apply_numeric_comparison("score", "<", 50);
        let sql = format!("{lt_expr:?}");
        assert!(sql.contains("score") && sql.contains("50"));

        let neq_expr = apply_numeric_comparison("status", "!=", 404);
        let sql = format!("{neq_expr:?}");
        assert!(sql.contains("status") && sql.contains("404"));

        // Test fallback to equality for unknown operator
        let eq_expr = apply_numeric_comparison("id", "unknown", 123);
        let sql = format!("{eq_expr:?}");
        assert!(sql.contains("id") && sql.contains("123"));
    }

    /// Test JSON filter parsing
    #[test]
    fn test_parse_filter_json_valid() {
        let filter_str = Some(r#"{"name": "John", "age": 30}"#.to_string());
        let parsed = parse_filter_json(filter_str).expect("valid filter");

        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed.get("name").and_then(|v| v.as_str()), Some("John"));
        assert_eq!(parsed.get("age").and_then(|v| v.as_i64()), Some(30));
    }

    #[test]
    fn test_parse_filter_json_invalid() {
        // Invalid JSON historically returns empty (preserved behavior); over-limit
        // is the new strict path tested separately below.
        let filter_str = Some("{invalid json}".to_string());
        let parsed = parse_filter_json(filter_str).expect("invalid-json path is lenient");
        assert_eq!(parsed.len(), 0);
    }

    #[test]
    fn test_parse_filter_json_none() {
        let parsed = parse_filter_json(None).expect("None is valid");
        assert_eq!(parsed.len(), 0);
    }

    #[test]
    fn test_parse_filter_json_empty() {
        let filter_str = Some("{}".to_string());
        let parsed = parse_filter_json(filter_str).expect("empty object is valid");
        assert_eq!(parsed.len(), 0);
    }

    #[test]
    fn test_parse_filter_json_at_limit_is_accepted() {
        let mut entries: Vec<String> = Vec::with_capacity(MAX_FILTER_CLAUSES);
        for i in 0..MAX_FILTER_CLAUSES {
            entries.push(format!("\"f{i}\":{i}"));
        }
        let filter_str = Some(format!("{{{}}}", entries.join(",")));
        let parsed = parse_filter_json(filter_str).expect("at-limit filter must be accepted");
        assert_eq!(parsed.len(), MAX_FILTER_CLAUSES);
    }

    #[test]
    fn test_parse_filter_json_rejects_when_over_limit() {
        let mut entries: Vec<String> = Vec::with_capacity(MAX_FILTER_CLAUSES + 1);
        for i in 0..=MAX_FILTER_CLAUSES {
            entries.push(format!("\"f{i}\":{i}"));
        }
        let filter_str = Some(format!("{{{}}}", entries.join(",")));
        let err = parse_filter_json(filter_str)
            .expect_err("over-limit filter must be rejected, not silently dropped");
        assert!(
            matches!(err, crate::errors::ApiError::BadRequest { .. }),
            "expected BadRequest, got {err:?}"
        );
    }

    /// An array-valued filter at the element cap is accepted, and one element over is
    /// rejected with `BadRequest` rather than fanning out into an oversized `IN (...)`.
    #[test]
    fn test_parse_filter_json_rejects_overlong_array() {
        let at_limit: Vec<i64> = (0..MAX_FILTER_ARRAY_LEN as i64).collect();
        let filter_str = Some(serde_json::json!({ "id": at_limit }).to_string());
        let parsed = parse_filter_json(filter_str).expect("array at the cap is accepted");
        assert_eq!(parsed.len(), 1);

        let over_limit: Vec<i64> = (0..=MAX_FILTER_ARRAY_LEN as i64).collect();
        let filter_str = Some(serde_json::json!({ "id": over_limit }).to_string());
        let err = parse_filter_json(filter_str)
            .expect_err("array one element over the cap must be rejected");
        assert!(
            matches!(err, crate::errors::ApiError::BadRequest { .. }),
            "expected BadRequest, got {err:?}"
        );
    }

    /// Test comparison operators with edge cases
    #[test]
    fn test_comparison_operator_edge_cases() {
        // Field name that ends with operator-like suffix but isn't one
        assert_eq!(parse_comparison_operator("created_at"), None);
        assert_eq!(parse_comparison_operator("_gte"), Some(("", ">=")));

        // Multiple suffixes (should match the longest/last one)
        assert_eq!(
            parse_comparison_operator("field_gte_lte"),
            Some(("field_gte", "<="))
        );
    }

    /// Test field name validation edge cases
    #[test]
    fn test_field_name_validation_edge_cases() {
        // Boundary cases
        assert!(is_valid_field_name("a")); // Single char
        assert!(is_valid_field_name("a".repeat(100).as_str())); // Exactly 100
        assert!(!is_valid_field_name("a".repeat(101).as_str())); // 101

        // Special chars that should be allowed
        assert!(is_valid_field_name("field_123"));
        assert!(is_valid_field_name("Field123"));

        // Special chars that should be rejected
        assert!(!is_valid_field_name("field..name"));
        assert!(!is_valid_field_name(".."));
        assert!(!is_valid_field_name("_private"));
    }

    /// Test numeric comparison with different numeric types
    #[test]
    fn test_apply_numeric_comparison_various_types() {
        // i64
        let expr_i64 = apply_numeric_comparison("count", ">=", 100_i64);
        let sql = format!("{expr_i64:?}");
        assert!(sql.contains("count"));

        // f64
        let expr_f64 = apply_numeric_comparison("price", "<=", 99.99_f64);
        let sql = format!("{expr_f64:?}");
        assert!(sql.contains("price"));

        // i32
        let expr_i32 = apply_numeric_comparison("age", ">", 18_i32);
        let sql = format!("{expr_i32:?}");
        assert!(sql.contains("age"));
    }

    // ========================================================================
    // PAGINATION TESTS - Range parsing and default pagination
    // ========================================================================

    /// Test parse_range with valid JSON array
    #[test]
    fn test_parse_range_valid() {
        let (start, end) = parse_range(Some("[0,9]".to_string()));
        assert_eq!(start, 0);
        assert_eq!(end, 9);

        let (start, end) = parse_range(Some("[10,19]".to_string()));
        assert_eq!(start, 10);
        assert_eq!(end, 19);

        let (start, end) = parse_range(Some("[50,74]".to_string()));
        assert_eq!(start, 50);
        assert_eq!(end, 74);
    }

    /// Test parse_range with invalid JSON returns default
    #[test]
    fn test_parse_range_invalid_json() {
        let (start, end) = parse_range(Some("invalid".to_string()));
        assert_eq!(start, 0);
        assert_eq!(end, 9);

        let (start, end) = parse_range(Some("[0]".to_string())); // Not enough elements
        assert_eq!(start, 0);
        assert_eq!(end, 9);

        let (start, end) = parse_range(Some("[]".to_string())); // Empty array
        assert_eq!(start, 0);
        assert_eq!(end, 9);
    }

    /// Test parse_range with None returns default
    #[test]
    fn test_parse_range_none() {
        let (start, end) = parse_range(None);
        assert_eq!(start, 0);
        assert_eq!(end, 9);
    }

    /// Test default pagination when no params provided
    #[test]
    fn test_pagination_default_values() {
        let params = crate::models::FilterOptions::default();
        let (offset, limit) = parse_pagination(&params);

        assert_eq!(offset, 0, "Default offset should be 0");
        assert_eq!(limit, 10, "Default limit should be 10");
    }

    /// Test pagination with range format calculates limit correctly
    #[test]
    fn test_pagination_range_calculates_limit() {
        let params = crate::models::FilterOptions {
            range: Some("[0,4]".to_string()),
            ..Default::default()
        };
        let (offset, limit) = parse_pagination(&params);

        assert_eq!(offset, 0, "Offset should be 0");
        assert_eq!(limit, 5, "Limit should be 5 for range [0,4]");

        // Test second page
        let params = crate::models::FilterOptions {
            range: Some("[5,9]".to_string()),
            ..Default::default()
        };
        let (offset, limit) = parse_pagination(&params);

        assert_eq!(offset, 5, "Offset should be 5");
        assert_eq!(limit, 5, "Limit should be 5 for range [5,9]");
    }

    /// Test page/per_page takes priority over range
    #[test]
    fn test_pagination_page_priority_over_range() {
        let params = crate::models::FilterOptions {
            page: Some(2),
            per_page: Some(15),
            range: Some("[0,4]".to_string()), // Should be ignored
            ..Default::default()
        };
        let (offset, limit) = parse_pagination(&params);

        assert_eq!(offset, 15, "Offset should be 15 (page 2 * 15 per_page)");
        assert_eq!(limit, 15, "Limit should be 15");
    }

    /// Test range pagination enforces max limits
    #[test]
    fn test_pagination_range_enforces_max_limits() {
        // Test max page size enforcement
        let params = crate::models::FilterOptions {
            range: Some("[0,9999]".to_string()), // Requesting 10000 items
            ..Default::default()
        };
        let (_offset, limit) = parse_pagination(&params);
        assert!(
            limit <= MAX_PAGE_SIZE,
            "Range limit should be capped at {}",
            MAX_PAGE_SIZE
        );

        // Test max offset enforcement
        let params = crate::models::FilterOptions {
            range: Some("[9999999,10000000]".to_string()), // Very large offset
            ..Default::default()
        };
        let (offset, _limit) = parse_pagination(&params);
        assert!(
            offset <= MAX_OFFSET,
            "Range offset should be capped at {}",
            MAX_OFFSET
        );
    }

    /// A3 regression: a huge `end` in the range branch must not overflow the `+ 1`
    /// (which panics under overflow-checks). Should cap cleanly instead.
    #[test]
    fn test_pagination_range_huge_end_does_not_overflow() {
        let params = crate::models::FilterOptions {
            range: Some(format!("[0,{}]", u64::MAX)),
            ..Default::default()
        };
        let (offset, limit) = parse_pagination(&params);
        assert!(limit <= MAX_PAGE_SIZE, "limit must be capped, got {limit}");
        assert!(offset <= MAX_OFFSET, "offset must be capped, got {offset}");

        // Reversed range (end < start) must not panic either.
        let params = crate::models::FilterOptions {
            range: Some(format!("[{},{}]", u64::MAX, u64::MAX)),
            ..Default::default()
        };
        let (_offset, limit) = parse_pagination(&params);
        assert!(limit <= MAX_PAGE_SIZE);
    }
}

#[cfg(test)]
mod prop_tests {
    use super::*;
    use crate::filtering::joined::FilterOperator;
    use proptest::prelude::*;

    mod pe {
        use sea_orm::entity::prelude::*;

        #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
        #[sea_orm(table_name = "pe_things")]
        pub struct Model {
            #[sea_orm(primary_key)]
            pub id: i32,
            pub name: String,
        }

        #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
        pub enum Relation {}

        impl ActiveModelBehavior for ActiveModel {}
    }

    const OPS: [FilterOperator; 9] = [
        FilterOperator::Eq,
        FilterOperator::Neq,
        FilterOperator::Gt,
        FilterOperator::Gte,
        FilterOperator::Lt,
        FilterOperator::Lte,
        FilterOperator::Like,
        FilterOperator::In,
        FilterOperator::IsNull,
    ];

    fn json_value() -> impl Strategy<Value = serde_json::Value> {
        prop_oneof![
            any::<i64>().prop_map(|n| serde_json::json!(n)),
            // u64 covers values above i64::MAX, which must bind without a lossy f64 cast.
            any::<u64>().prop_map(|n| serde_json::json!(n)),
            any::<f64>().prop_map(|f| serde_json::json!(f)),
            any::<bool>().prop_map(|b| serde_json::json!(b)),
            "[a-zA-Z0-9 %_!.-]{0,24}".prop_map(|s| serde_json::json!(s)),
            proptest::collection::vec(any::<i64>(), 0..6).prop_map(|v| serde_json::json!(v)),
            proptest::collection::vec("[a-z]{0,6}", 0..6).prop_map(|v| serde_json::json!(v)),
            proptest::collection::vec(any::<bool>(), 0..6).prop_map(|v| serde_json::json!(v)),
            Just(serde_json::Value::Null),
        ]
    }

    proptest! {
        /// `build_comparison_expr` never panics for any operator/value combination on
        /// either an integer or a string column, and is deterministic (the same input
        /// yields the same Some/None outcome). This is the joined-filter path, fed by
        /// attacker-controlled `filter={...}` JSON.
        #[test]
        fn build_comparison_expr_never_panics(value in json_value()) {
            for op in OPS {
                let a = build_comparison_expr(pe::Column::Id, op, &value).is_some();
                let b = build_comparison_expr(pe::Column::Id, op, &value).is_some();
                prop_assert_eq!(a, b);
                let c = build_comparison_expr(pe::Column::Name, op, &value).is_some();
                let d = build_comparison_expr(pe::Column::Name, op, &value).is_some();
                prop_assert_eq!(c, d);
            }
        }

        /// Attacker-controlled string filter values are always bound as parameters,
        /// never spliced into the SQL text. Proven by rendering the parameterised form
        /// and checking the value rides a placeholder.
        #[test]
        fn build_comparison_expr_binds_string_values(s in "[a-z][a-zA-Z0-9 ';-]{0,23}") {
            use sea_orm::sea_query::{Query, SqliteQueryBuilder};
            let expr = build_comparison_expr(pe::Column::Name, FilterOperator::Eq, &serde_json::json!(s));
            prop_assert!(expr.is_some());
            let (sql, values) = Query::select()
                .column(pe::Column::Id)
                .from(pe::Entity)
                .and_where(expr.unwrap())
                .build(SqliteQueryBuilder);
            prop_assert!(sql.contains('?'), "value must ride a bound placeholder: {sql}");
            prop_assert_eq!(values.0.len(), 1);
        }

        /// REST page/per_page pagination always stays within the configured caps and
        /// never panics, even for `u64::MAX` inputs (overflow-checks are on in tests).
        #[test]
        fn parse_pagination_page_respects_caps(page in any::<u64>(), per_page in any::<u64>()) {
            let params = crate::models::FilterOptions {
                page: Some(page),
                per_page: Some(per_page),
                ..Default::default()
            };
            let (offset, limit) = parse_pagination(&params);
            prop_assert!(limit <= MAX_PAGE_SIZE);
            prop_assert!(offset <= MAX_OFFSET);
        }

        /// React-Admin `range=[start,end]` pagination stays within caps and never
        /// panics, including reversed ranges and `u64::MAX` bounds.
        #[test]
        fn parse_pagination_range_respects_caps(start in any::<u64>(), end in any::<u64>()) {
            let params = crate::models::FilterOptions {
                range: Some(format!("[{start},{end}]")),
                ..Default::default()
            };
            let (offset, limit) = parse_pagination(&params);
            prop_assert!(limit <= MAX_PAGE_SIZE);
            prop_assert!(offset <= MAX_OFFSET);
        }
    }
}