rustapi-core 0.1.450

The core engine of the RustAPI framework. Provides the hyper-based HTTP server, router, extraction logic, and foundational traits.
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
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
//! Extractors for RustAPI
//!
//! Extractors automatically parse and validate data from incoming HTTP requests.
//! They implement the [`FromRequest`] or [`FromRequestParts`] traits and can be
//! used as handler function parameters.
//!
//! # Available Extractors
//!
//! | Extractor | Description | Consumes Body |
//! |-----------|-------------|---------------|
//! | [`Json<T>`] | Parse JSON request body | Yes |
//! | [`ValidatedJson<T>`] | Parse and validate JSON body | Yes |
//! | [`Query<T>`] | Parse query string parameters | No |
//! | [`Path<T>`] | Extract path parameters | No |
//! | [`State<T>`] | Access shared application state | No |
//! | [`Body`] | Raw request body bytes | Yes |
//! | [`Headers`] | Access all request headers | No |
//! | [`HeaderValue`] | Extract a specific header | No |
//! | [`Extension<T>`] | Access middleware-injected data | No |
//! | [`ClientIp`] | Extract client IP address | No |
//! | [`Cookies`] | Parse request cookies (requires `cookies` feature) | No |
//!
//! # Example
//!
//! ```rust,ignore
//! use rustapi_core::{Json, Query, Path, State};
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Deserialize)]
//! struct CreateUser {
//!     name: String,
//!     email: String,
//! }
//!
//! #[derive(Deserialize)]
//! struct Pagination {
//!     page: Option<u32>,
//!     limit: Option<u32>,
//! }
//!
//! // Multiple extractors can be combined
//! async fn create_user(
//!     State(db): State<DbPool>,
//!     Query(pagination): Query<Pagination>,
//!     Json(body): Json<CreateUser>,
//! ) -> impl IntoResponse {
//!     // Use db, pagination, and body...
//! }
//! ```
//!
//! # Extractor Order
//!
//! When using multiple extractors, body-consuming extractors (like `Json` or `Body`)
//! must come last since they consume the request body. Non-body extractors can be
//! in any order.

use crate::error::{ApiError, Result};
use crate::json;
use crate::request::Request;
use crate::response::IntoResponse;
use crate::stream::{StreamingBody, StreamingConfig};
use crate::validation::Validatable;
use bytes::Bytes;
use http::{header, StatusCode};
use rustapi_validate::v2::{AsyncValidate, ValidationContext};

use rustapi_openapi::schema::{RustApiSchema, SchemaCtx, SchemaRef};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::collections::BTreeMap;
use std::future::Future;
use std::ops::{Deref, DerefMut};
use std::str::FromStr;

/// Trait for extracting data from request parts (headers, path, query)
///
/// This is used for extractors that don't need the request body.
///
/// # Example: Implementing a custom extractor that requires a specific header
///
/// ```rust
/// use rustapi_core::FromRequestParts;
/// use rustapi_core::{Request, ApiError, Result};
/// use http::StatusCode;
///
/// struct ApiKey(String);
///
/// impl FromRequestParts for ApiKey {
///     fn from_request_parts(req: &Request) -> Result<Self> {
///         if let Some(key) = req.headers().get("x-api-key") {
///             if let Ok(key_str) = key.to_str() {
///                 return Ok(ApiKey(key_str.to_string()));
///             }
///         }
///         Err(ApiError::unauthorized("Missing or invalid API key"))
///     }
/// }
/// ```
pub trait FromRequestParts: Sized {
    /// Extract from request parts
    fn from_request_parts(req: &Request) -> Result<Self>;
}

/// Trait for extracting data from the full request (including body)
///
/// This is used for extractors that consume the request body.
///
/// # Example: Implementing a custom extractor that consumes the body
///
/// ```rust
/// use rustapi_core::FromRequest;
/// use rustapi_core::{Request, ApiError, Result};
/// use std::future::Future;
///
/// struct PlainText(String);
///
/// impl FromRequest for PlainText {
///     async fn from_request(req: &mut Request) -> Result<Self> {
///         // Ensure body is loaded
///         req.load_body().await?;
///         
///         // Consume the body
///         if let Some(bytes) = req.take_body() {
///             if let Ok(text) = String::from_utf8(bytes.to_vec()) {
///                 return Ok(PlainText(text));
///             }
///         }
///         
///         Err(ApiError::bad_request("Invalid plain text body"))
///     }
/// }
/// ```
pub trait FromRequest: Sized {
    /// Extract from the full request
    fn from_request(req: &mut Request) -> impl Future<Output = Result<Self>> + Send;
}

// Blanket impl: FromRequestParts -> FromRequest
impl<T: FromRequestParts> FromRequest for T {
    async fn from_request(req: &mut Request) -> Result<Self> {
        T::from_request_parts(req)
    }
}

/// JSON body extractor
///
/// Parses the request body as JSON and deserializes into type `T`.
/// Also works as a response type when T: Serialize.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Deserialize)]
/// struct CreateUser {
///     name: String,
///     email: String,
/// }
///
/// async fn create_user(Json(body): Json<CreateUser>) -> impl IntoResponse {
///     // body is already deserialized
/// }
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct Json<T>(pub T);

impl<T: DeserializeOwned + Send> FromRequest for Json<T> {
    async fn from_request(req: &mut Request) -> Result<Self> {
        req.load_body().await?;
        let body = req
            .take_body()
            .ok_or_else(|| ApiError::internal("Body already consumed"))?;

        // Use simd-json accelerated parsing when available (2-4x faster)
        let value: T = json::from_slice(&body)?;
        Ok(Json(value))
    }
}

impl<T> Deref for Json<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Json<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> From<T> for Json<T> {
    fn from(value: T) -> Self {
        Json(value)
    }
}

/// Default pre-allocation size for JSON response buffers (256 bytes)
/// This covers most small to medium JSON responses without reallocation.
const JSON_RESPONSE_INITIAL_CAPACITY: usize = 256;

// IntoResponse for Json - allows using Json<T> as a return type
impl<T: Serialize> IntoResponse for Json<T> {
    fn into_response(self) -> crate::response::Response {
        // Use pre-allocated buffer to reduce allocations
        match json::to_vec_with_capacity(&self.0, JSON_RESPONSE_INITIAL_CAPACITY) {
            Ok(body) => http::Response::builder()
                .status(StatusCode::OK)
                .header(header::CONTENT_TYPE, "application/json")
                .body(crate::response::Body::from(body))
                .unwrap(),
            Err(err) => {
                ApiError::internal(format!("Failed to serialize response: {}", err)).into_response()
            }
        }
    }
}

/// Validated JSON body extractor
///
/// Parses the request body as JSON, deserializes into type `T`, and validates
/// using the `Validate` trait. Returns a 422 Unprocessable Entity error with
/// detailed field-level validation errors if validation fails.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
/// use validator::Validate;
///
/// #[derive(Deserialize, Validate)]
/// struct CreateUser {
///     #[validate(email)]
///     email: String,
///     #[validate(length(min = 8))]
///     password: String,
/// }
///
/// async fn register(ValidatedJson(body): ValidatedJson<CreateUser>) -> impl IntoResponse {
///     // body is already validated!
///     // If email is invalid or password too short, a 422 error is returned automatically
/// }
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct ValidatedJson<T>(pub T);

impl<T> ValidatedJson<T> {
    /// Create a new ValidatedJson wrapper
    pub fn new(value: T) -> Self {
        Self(value)
    }

    /// Get the inner value
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T: DeserializeOwned + Validatable + Send> FromRequest for ValidatedJson<T> {
    async fn from_request(req: &mut Request) -> Result<Self> {
        req.load_body().await?;
        // First, deserialize the JSON body using simd-json when available
        let body = req
            .take_body()
            .ok_or_else(|| ApiError::internal("Body already consumed"))?;

        let value: T = json::from_slice(&body)?;

        // Then, validate it using the unified Validatable trait
        value.do_validate()?;

        Ok(ValidatedJson(value))
    }
}

impl<T> Deref for ValidatedJson<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for ValidatedJson<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> From<T> for ValidatedJson<T> {
    fn from(value: T) -> Self {
        ValidatedJson(value)
    }
}

impl<T: Serialize> IntoResponse for ValidatedJson<T> {
    fn into_response(self) -> crate::response::Response {
        Json(self.0).into_response()
    }
}

/// Async validated JSON body extractor
///
/// Parses the request body as JSON, deserializes into type `T`, and validates
/// using the `AsyncValidate` trait from `rustapi-validate`.
///
/// This extractor supports async validation rules, such as database uniqueness checks.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_rs::prelude::*;
/// use rustapi_validate::v2::prelude::*;
///
/// #[derive(Deserialize, Validate, AsyncValidate)]
/// struct CreateUser {
///     #[validate(email)]
///     email: String,
///     
///     #[validate(async_unique(table = "users", column = "email"))]
///     username: String,
/// }
///
/// async fn register(AsyncValidatedJson(body): AsyncValidatedJson<CreateUser>) -> impl IntoResponse {
///     // body is validated asynchronously (e.g. checked existing email in DB)
/// }
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct AsyncValidatedJson<T>(pub T);

impl<T> AsyncValidatedJson<T> {
    /// Create a new AsyncValidatedJson wrapper
    pub fn new(value: T) -> Self {
        Self(value)
    }

    /// Get the inner value
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> Deref for AsyncValidatedJson<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for AsyncValidatedJson<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> From<T> for AsyncValidatedJson<T> {
    fn from(value: T) -> Self {
        AsyncValidatedJson(value)
    }
}

impl<T: Serialize> IntoResponse for AsyncValidatedJson<T> {
    fn into_response(self) -> crate::response::Response {
        Json(self.0).into_response()
    }
}

impl<T: DeserializeOwned + AsyncValidate + Send + Sync> FromRequest for AsyncValidatedJson<T> {
    async fn from_request(req: &mut Request) -> Result<Self> {
        req.load_body().await?;

        let body = req
            .take_body()
            .ok_or_else(|| ApiError::internal("Body already consumed"))?;

        let value: T = json::from_slice(&body)?;

        // Create validation context from request
        // Check if validators are configured in App State
        let ctx = if let Some(ctx) = req.state().get::<ValidationContext>() {
            ctx.clone()
        } else {
            ValidationContext::default()
        };

        // Perform full validation (sync + async)
        if let Err(errors) = value.validate_full(&ctx).await {
            // Convert v2 ValidationErrors to ApiError
            let field_errors: Vec<crate::error::FieldError> = errors
                .fields
                .iter()
                .flat_map(|(field, errs)| {
                    let field_name = field.to_string();
                    errs.iter().map(move |e| crate::error::FieldError {
                        field: field_name.clone(),
                        code: e.code.to_string(),
                        message: e.message.clone(),
                    })
                })
                .collect();

            return Err(ApiError::validation(field_errors));
        }

        Ok(AsyncValidatedJson(value))
    }
}

/// Query string extractor
///
/// Parses the query string into type `T`.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Deserialize)]
/// struct Pagination {
///     page: Option<u32>,
///     limit: Option<u32>,
/// }
///
/// async fn list_users(Query(params): Query<Pagination>) -> impl IntoResponse {
///     // params.page, params.limit
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Query<T>(pub T);

impl<T: DeserializeOwned> FromRequestParts for Query<T> {
    fn from_request_parts(req: &Request) -> Result<Self> {
        let query = req.query_string().unwrap_or("");
        let value: T = serde_urlencoded::from_str(query)
            .map_err(|e| ApiError::bad_request(format!("Invalid query string: {}", e)))?;
        Ok(Query(value))
    }
}

impl<T> Deref for Query<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Path parameter extractor
///
/// Extracts path parameters defined in the route pattern.
///
/// # Example
///
/// For route `/users/{id}`:
///
/// ```rust,ignore
/// async fn get_user(Path(id): Path<i64>) -> impl IntoResponse {
///     // id is extracted from path
/// }
/// ```
///
/// For multiple params `/users/{user_id}/posts/{post_id}`:
///
/// ```rust,ignore
/// async fn get_post(Path((user_id, post_id)): Path<(i64, i64)>) -> impl IntoResponse {
///     // Both params extracted
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Path<T>(pub T);

impl<T: FromStr> FromRequestParts for Path<T>
where
    T::Err: std::fmt::Display,
{
    fn from_request_parts(req: &Request) -> Result<Self> {
        let params = req.path_params();

        // For single param, get the first one
        if let Some((_, value)) = params.iter().next() {
            let parsed = value
                .parse::<T>()
                .map_err(|e| ApiError::bad_request(format!("Invalid path parameter: {}", e)))?;
            return Ok(Path(parsed));
        }

        Err(ApiError::internal("Missing path parameter"))
    }
}

impl<T> Deref for Path<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Typed path extractor
///
/// Extracts path parameters and deserializes them into a struct implementing `Deserialize`.
/// This is similar to `Path<T>`, but supports complex structs that can be deserialized
/// from a map of parameter names to values (e.g. via `serde_json`).
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Deserialize)]
/// struct UserParams {
///     id: u64,
///     category: String,
/// }
///
/// async fn get_user(Typed(params): Typed<UserParams>) -> impl IntoResponse {
///     // params.id, params.category
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Typed<T>(pub T);

impl<T: DeserializeOwned + Send> FromRequestParts for Typed<T> {
    fn from_request_parts(req: &Request) -> Result<Self> {
        let params = req.path_params();
        let mut map = serde_json::Map::new();
        for (k, v) in params.iter() {
            map.insert(k.to_string(), serde_json::Value::String(v.to_string()));
        }
        let value = serde_json::Value::Object(map);
        let parsed: T = serde_json::from_value(value)
            .map_err(|e| ApiError::bad_request(format!("Invalid path parameters: {}", e)))?;
        Ok(Typed(parsed))
    }
}

impl<T> Deref for Typed<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// State extractor
///
/// Extracts shared application state.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Clone)]
/// struct AppState {
///     db: DbPool,
/// }
///
/// async fn handler(State(state): State<AppState>) -> impl IntoResponse {
///     // Use state.db
/// }
/// ```
#[derive(Debug, Clone)]
pub struct State<T>(pub T);

impl<T: Clone + Send + Sync + 'static> FromRequestParts for State<T> {
    fn from_request_parts(req: &Request) -> Result<Self> {
        req.state().get::<T>().cloned().map(State).ok_or_else(|| {
            ApiError::internal(format!(
                "State of type `{}` not found. Did you forget to call .state()?",
                std::any::type_name::<T>()
            ))
        })
    }
}

impl<T> Deref for State<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Raw body bytes extractor
#[derive(Debug, Clone)]
pub struct Body(pub Bytes);

impl FromRequest for Body {
    async fn from_request(req: &mut Request) -> Result<Self> {
        req.load_body().await?;
        let body = req
            .take_body()
            .ok_or_else(|| ApiError::internal("Body already consumed"))?;
        Ok(Body(body))
    }
}

impl Deref for Body {
    type Target = Bytes;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Streaming body extractor
pub struct BodyStream(pub StreamingBody);

impl FromRequest for BodyStream {
    async fn from_request(req: &mut Request) -> Result<Self> {
        let config = StreamingConfig::default();

        if let Some(stream) = req.take_stream() {
            Ok(BodyStream(StreamingBody::new(stream, config.max_body_size)))
        } else if let Some(bytes) = req.take_body() {
            // Handle buffered body as stream
            let stream = futures_util::stream::once(async move { Ok(bytes) });
            Ok(BodyStream(StreamingBody::from_stream(
                stream,
                config.max_body_size,
            )))
        } else {
            Err(ApiError::internal("Body already consumed"))
        }
    }
}

impl Deref for BodyStream {
    type Target = StreamingBody;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for BodyStream {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

// Forward stream implementation
impl futures_util::Stream for BodyStream {
    type Item = Result<Bytes, ApiError>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        std::pin::Pin::new(&mut self.0).poll_next(cx)
    }
}

/// Optional extractor wrapper
///
/// Makes any extractor optional - returns None instead of error on failure.
impl<T: FromRequestParts> FromRequestParts for Option<T> {
    fn from_request_parts(req: &Request) -> Result<Self> {
        Ok(T::from_request_parts(req).ok())
    }
}

/// Headers extractor
///
/// Provides access to all request headers as a typed map.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::extract::Headers;
///
/// async fn handler(headers: Headers) -> impl IntoResponse {
///     if let Some(content_type) = headers.get("content-type") {
///         format!("Content-Type: {:?}", content_type)
///     } else {
///         "No Content-Type header".to_string()
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Headers(pub http::HeaderMap);

impl Headers {
    /// Get a header value by name
    pub fn get(&self, name: &str) -> Option<&http::HeaderValue> {
        self.0.get(name)
    }

    /// Check if a header exists
    pub fn contains(&self, name: &str) -> bool {
        self.0.contains_key(name)
    }

    /// Get the number of headers
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Check if headers are empty
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Iterate over all headers
    pub fn iter(&self) -> http::header::Iter<'_, http::HeaderValue> {
        self.0.iter()
    }
}

impl FromRequestParts for Headers {
    fn from_request_parts(req: &Request) -> Result<Self> {
        Ok(Headers(req.headers().clone()))
    }
}

impl Deref for Headers {
    type Target = http::HeaderMap;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Single header value extractor
///
/// Extracts a specific header value by name. Returns an error if the header is missing.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::extract::HeaderValue;
///
/// async fn handler(
///     auth: HeaderValue<{ "authorization" }>,
/// ) -> impl IntoResponse {
///     format!("Auth header: {}", auth.0)
/// }
/// ```
///
/// Note: Due to Rust's const generics limitations, you may need to use the
/// `HeaderValueOf` type alias or extract headers manually using the `Headers` extractor.
#[derive(Debug, Clone)]
pub struct HeaderValue(pub String, pub &'static str);

impl HeaderValue {
    /// Create a new HeaderValue extractor for a specific header name
    pub fn new(name: &'static str, value: String) -> Self {
        Self(value, name)
    }

    /// Get the header value
    pub fn value(&self) -> &str {
        &self.0
    }

    /// Get the header name
    pub fn name(&self) -> &'static str {
        self.1
    }

    /// Extract a specific header from a request
    pub fn extract(req: &Request, name: &'static str) -> Result<Self> {
        req.headers()
            .get(name)
            .and_then(|v| v.to_str().ok())
            .map(|s| HeaderValue(s.to_string(), name))
            .ok_or_else(|| ApiError::bad_request(format!("Missing required header: {}", name)))
    }
}

impl Deref for HeaderValue {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Extension extractor
///
/// Retrieves typed data from request extensions that was inserted by middleware.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::extract::Extension;
///
/// // Middleware inserts user data
/// #[derive(Clone)]
/// struct CurrentUser { id: i64 }
///
/// async fn handler(Extension(user): Extension<CurrentUser>) -> impl IntoResponse {
///     format!("User ID: {}", user.id)
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Extension<T>(pub T);

impl<T: Clone + Send + Sync + 'static> FromRequestParts for Extension<T> {
    fn from_request_parts(req: &Request) -> Result<Self> {
        req.extensions()
            .get::<T>()
            .cloned()
            .map(Extension)
            .ok_or_else(|| {
                ApiError::internal(format!(
                    "Extension of type `{}` not found. Did middleware insert it?",
                    std::any::type_name::<T>()
                ))
            })
    }
}

impl<T> Deref for Extension<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Extension<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Client IP address extractor
///
/// Extracts the client IP address from the request. When `trust_proxy` is enabled,
/// it will use the `X-Forwarded-For` header if present.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::extract::ClientIp;
///
/// async fn handler(ClientIp(ip): ClientIp) -> impl IntoResponse {
///     format!("Your IP: {}", ip)
/// }
/// ```
#[derive(Debug, Clone)]
pub struct ClientIp(pub std::net::IpAddr);

impl ClientIp {
    /// Extract client IP, optionally trusting X-Forwarded-For header
    pub fn extract_with_config(req: &Request, trust_proxy: bool) -> Result<Self> {
        if trust_proxy {
            // Try X-Forwarded-For header first
            if let Some(forwarded) = req.headers().get("x-forwarded-for") {
                if let Ok(forwarded_str) = forwarded.to_str() {
                    // X-Forwarded-For can contain multiple IPs, take the first one
                    if let Some(first_ip) = forwarded_str.split(',').next() {
                        if let Ok(ip) = first_ip.trim().parse() {
                            return Ok(ClientIp(ip));
                        }
                    }
                }
            }
        }

        // Fall back to socket address from extensions (if set by server)
        if let Some(addr) = req.extensions().get::<std::net::SocketAddr>() {
            return Ok(ClientIp(addr.ip()));
        }

        // Default to localhost if no IP information available
        Ok(ClientIp(std::net::IpAddr::V4(std::net::Ipv4Addr::new(
            127, 0, 0, 1,
        ))))
    }
}

impl FromRequestParts for ClientIp {
    fn from_request_parts(req: &Request) -> Result<Self> {
        // By default, trust proxy headers
        Self::extract_with_config(req, true)
    }
}

/// Cookies extractor
///
/// Parses and provides access to request cookies from the Cookie header.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::extract::Cookies;
///
/// async fn handler(cookies: Cookies) -> impl IntoResponse {
///     if let Some(session) = cookies.get("session_id") {
///         format!("Session: {}", session.value())
///     } else {
///         "No session cookie".to_string()
///     }
/// }
/// ```
#[cfg(feature = "cookies")]
#[derive(Debug, Clone)]
pub struct Cookies(pub cookie::CookieJar);

#[cfg(feature = "cookies")]
impl Cookies {
    /// Get a cookie by name
    pub fn get(&self, name: &str) -> Option<&cookie::Cookie<'static>> {
        self.0.get(name)
    }

    /// Iterate over all cookies
    pub fn iter(&self) -> impl Iterator<Item = &cookie::Cookie<'static>> {
        self.0.iter()
    }

    /// Check if a cookie exists
    pub fn contains(&self, name: &str) -> bool {
        self.0.get(name).is_some()
    }
}

#[cfg(feature = "cookies")]
impl FromRequestParts for Cookies {
    fn from_request_parts(req: &Request) -> Result<Self> {
        let mut jar = cookie::CookieJar::new();

        if let Some(cookie_header) = req.headers().get(header::COOKIE) {
            if let Ok(cookie_str) = cookie_header.to_str() {
                // Parse each cookie from the header
                for cookie_part in cookie_str.split(';') {
                    let trimmed = cookie_part.trim();
                    if !trimmed.is_empty() {
                        if let Ok(cookie) = cookie::Cookie::parse(trimmed.to_string()) {
                            jar.add_original(cookie.into_owned());
                        }
                    }
                }
            }
        }

        Ok(Cookies(jar))
    }
}

#[cfg(feature = "cookies")]
impl Deref for Cookies {
    type Target = cookie::CookieJar;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

// Implement FromRequestParts for common primitive types (path params)
macro_rules! impl_from_request_parts_for_primitives {
    ($($ty:ty),*) => {
        $(
            impl FromRequestParts for $ty {
                fn from_request_parts(req: &Request) -> Result<Self> {
                    let Path(value) = Path::<$ty>::from_request_parts(req)?;
                    Ok(value)
                }
            }
        )*
    };
}

impl_from_request_parts_for_primitives!(
    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, bool, String
);

// OperationModifier implementations for extractors

use rustapi_openapi::{
    MediaType, Operation, OperationModifier, Parameter, RequestBody, ResponseModifier, ResponseSpec,
};

// ValidatedJson - Adds request body
impl<T: RustApiSchema> OperationModifier for ValidatedJson<T> {
    fn update_operation(op: &mut Operation) {
        let mut ctx = SchemaCtx::new();
        let schema_ref = T::schema(&mut ctx);

        let mut content = BTreeMap::new();
        content.insert(
            "application/json".to_string(),
            MediaType {
                schema: Some(schema_ref),
                example: None,
            },
        );

        op.request_body = Some(RequestBody {
            description: None,
            required: Some(true),
            content,
        });

        // Add 422 Validation Error response
        let mut responses_content = BTreeMap::new();
        responses_content.insert(
            "application/json".to_string(),
            MediaType {
                schema: Some(SchemaRef::Ref {
                    reference: "#/components/schemas/ValidationErrorSchema".to_string(),
                }),
                example: None,
            },
        );

        op.responses.insert(
            "422".to_string(),
            ResponseSpec {
                description: "Validation Error".to_string(),
                content: responses_content,
                headers: BTreeMap::new(),
            },
        );
    }

    fn register_components(spec: &mut rustapi_openapi::OpenApiSpec) {
        spec.register_in_place::<T>();
        spec.register_in_place::<rustapi_openapi::ValidationErrorSchema>();
        spec.register_in_place::<rustapi_openapi::ValidationErrorBodySchema>();
        spec.register_in_place::<rustapi_openapi::FieldErrorSchema>();
    }
}

// AsyncValidatedJson - Adds request body + 422 response (same as ValidatedJson)
impl<T: RustApiSchema> OperationModifier for AsyncValidatedJson<T> {
    fn update_operation(op: &mut Operation) {
        let mut ctx = SchemaCtx::new();
        let schema_ref = T::schema(&mut ctx);

        let mut content = BTreeMap::new();
        content.insert(
            "application/json".to_string(),
            MediaType {
                schema: Some(schema_ref),
                example: None,
            },
        );

        op.request_body = Some(RequestBody {
            description: None,
            required: Some(true),
            content,
        });

        // Add 422 Validation Error response
        let mut responses_content = BTreeMap::new();
        responses_content.insert(
            "application/json".to_string(),
            MediaType {
                schema: Some(SchemaRef::Ref {
                    reference: "#/components/schemas/ValidationErrorSchema".to_string(),
                }),
                example: None,
            },
        );

        op.responses.insert(
            "422".to_string(),
            ResponseSpec {
                description: "Validation Error".to_string(),
                content: responses_content,
                headers: BTreeMap::new(),
            },
        );
    }

    fn register_components(spec: &mut rustapi_openapi::OpenApiSpec) {
        spec.register_in_place::<T>();
        spec.register_in_place::<rustapi_openapi::ValidationErrorSchema>();
        spec.register_in_place::<rustapi_openapi::ValidationErrorBodySchema>();
        spec.register_in_place::<rustapi_openapi::FieldErrorSchema>();
    }
}

// Json - Adds request body (Same as ValidatedJson)
impl<T: RustApiSchema> OperationModifier for Json<T> {
    fn update_operation(op: &mut Operation) {
        let mut ctx = SchemaCtx::new();
        let schema_ref = T::schema(&mut ctx);

        let mut content = BTreeMap::new();
        content.insert(
            "application/json".to_string(),
            MediaType {
                schema: Some(schema_ref),
                example: None,
            },
        );

        op.request_body = Some(RequestBody {
            description: None,
            required: Some(true),
            content,
        });
    }

    fn register_components(spec: &mut rustapi_openapi::OpenApiSpec) {
        spec.register_in_place::<T>();
    }
}

// Path - No op (handled by app routing)
impl<T> OperationModifier for Path<T> {
    fn update_operation(_op: &mut Operation) {}
}

// Typed - No op
impl<T> OperationModifier for Typed<T> {
    fn update_operation(_op: &mut Operation) {}
}

// Query - Extracts query params using field_schemas
impl<T: RustApiSchema> OperationModifier for Query<T> {
    fn update_operation(op: &mut Operation) {
        let mut ctx = SchemaCtx::new();
        if let Some(fields) = T::field_schemas(&mut ctx) {
            let new_params: Vec<Parameter> = fields
                .into_iter()
                .map(|(name, schema)| {
                    Parameter {
                        name,
                        location: "query".to_string(),
                        required: false, // Assume optional
                        deprecated: None,
                        description: None,
                        schema: Some(schema),
                    }
                })
                .collect();

            op.parameters.extend(new_params);
        }
    }

    fn register_components(spec: &mut rustapi_openapi::OpenApiSpec) {
        spec.register_in_place::<T>();
    }
}

// State - No op
impl<T> OperationModifier for State<T> {
    fn update_operation(_op: &mut Operation) {}
}

// Body - Generic binary body
impl OperationModifier for Body {
    fn update_operation(op: &mut Operation) {
        let mut content = BTreeMap::new();
        content.insert(
            "application/octet-stream".to_string(),
            MediaType {
                schema: Some(SchemaRef::Inline(
                    serde_json::json!({ "type": "string", "format": "binary" }),
                )),
                example: None,
            },
        );

        op.request_body = Some(RequestBody {
            description: None,
            required: Some(true),
            content,
        });
    }
}

// BodyStream - Generic binary stream
impl OperationModifier for BodyStream {
    fn update_operation(op: &mut Operation) {
        let mut content = BTreeMap::new();
        content.insert(
            "application/octet-stream".to_string(),
            MediaType {
                schema: Some(SchemaRef::Inline(
                    serde_json::json!({ "type": "string", "format": "binary" }),
                )),
                example: None,
            },
        );

        op.request_body = Some(RequestBody {
            description: None,
            required: Some(true),
            content,
        });
    }
}

// ResponseModifier implementations for extractors

// Json<T> - 200 OK with schema T
impl<T: RustApiSchema> ResponseModifier for Json<T> {
    fn update_response(op: &mut Operation) {
        let mut ctx = SchemaCtx::new();
        let schema_ref = T::schema(&mut ctx);

        let mut content = BTreeMap::new();
        content.insert(
            "application/json".to_string(),
            MediaType {
                schema: Some(schema_ref),
                example: None,
            },
        );

        op.responses.insert(
            "200".to_string(),
            ResponseSpec {
                description: "Successful response".to_string(),
                content,
                headers: BTreeMap::new(),
            },
        );
    }

    fn register_components(spec: &mut rustapi_openapi::OpenApiSpec) {
        spec.register_in_place::<T>();
    }
}

// RustApiSchema implementations

impl<T: RustApiSchema> RustApiSchema for Json<T> {
    fn schema(ctx: &mut SchemaCtx) -> SchemaRef {
        T::schema(ctx)
    }
}

impl<T: RustApiSchema> RustApiSchema for ValidatedJson<T> {
    fn schema(ctx: &mut SchemaCtx) -> SchemaRef {
        T::schema(ctx)
    }
}

impl<T: RustApiSchema> RustApiSchema for AsyncValidatedJson<T> {
    fn schema(ctx: &mut SchemaCtx) -> SchemaRef {
        T::schema(ctx)
    }
}

impl<T: RustApiSchema> RustApiSchema for Query<T> {
    fn schema(ctx: &mut SchemaCtx) -> SchemaRef {
        T::schema(ctx)
    }
    fn field_schemas(ctx: &mut SchemaCtx) -> Option<BTreeMap<String, SchemaRef>> {
        T::field_schemas(ctx)
    }
}

// ─── Pagination Extractors ──────────────────────────────────────────────────

/// Default page number (1-indexed)
const DEFAULT_PAGE: u64 = 1;
/// Default items per page
const DEFAULT_PER_PAGE: u64 = 20;
/// Maximum items per page (prevents abuse)
const MAX_PER_PAGE: u64 = 100;

/// Offset-based pagination extractor
///
/// Extracts pagination parameters from the query string.
/// Supports `?page=1&per_page=20` (defaults: page=1, per_page=20, max=100).
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::Paginate;
///
/// async fn list_users(paginate: Paginate) -> impl IntoResponse {
///     let offset = paginate.offset();
///     let limit = paginate.limit();
///     // SELECT * FROM users LIMIT $limit OFFSET $offset
/// }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Paginate {
    /// Current page (1-indexed)
    pub page: u64,
    /// Items per page (capped at MAX_PER_PAGE)
    pub per_page: u64,
}

impl Paginate {
    /// Create a new Paginate with given page and per_page
    pub fn new(page: u64, per_page: u64) -> Self {
        Self {
            page: page.max(1),
            per_page: per_page.clamp(1, MAX_PER_PAGE),
        }
    }

    /// Calculate the SQL OFFSET value
    pub fn offset(&self) -> u64 {
        (self.page - 1) * self.per_page
    }

    /// Get the LIMIT value (alias for per_page)
    pub fn limit(&self) -> u64 {
        self.per_page
    }

    /// Build a `Paginated<T>` response from this pagination and results
    pub fn paginate<T>(self, items: Vec<T>, total: u64) -> crate::hateoas::Paginated<T> {
        crate::hateoas::Paginated {
            items,
            page: self.page,
            per_page: self.per_page,
            total,
        }
    }
}

impl Default for Paginate {
    fn default() -> Self {
        Self {
            page: DEFAULT_PAGE,
            per_page: DEFAULT_PER_PAGE,
        }
    }
}

impl FromRequestParts for Paginate {
    fn from_request_parts(req: &Request) -> Result<Self> {
        let query = req.query_string().unwrap_or("");

        #[derive(serde::Deserialize)]
        struct PaginateQuery {
            page: Option<u64>,
            per_page: Option<u64>,
        }

        let params: PaginateQuery = serde_urlencoded::from_str(query).unwrap_or(PaginateQuery {
            page: None,
            per_page: None,
        });

        Ok(Paginate::new(
            params.page.unwrap_or(DEFAULT_PAGE),
            params.per_page.unwrap_or(DEFAULT_PER_PAGE),
        ))
    }
}

/// Cursor-based pagination extractor
///
/// Extracts cursor pagination parameters from the query string.
/// Supports `?cursor=abc123&limit=20` (defaults: cursor=None, limit=20, max=100).
///
/// Cursor-based pagination is preferred for large datasets or real-time data
/// where offset-based pagination would skip or duplicate items.
///
/// # Example
///
/// ```rust,ignore
/// use rustapi_core::CursorPaginate;
///
/// async fn list_events(cursor: CursorPaginate) -> impl IntoResponse {
///     let limit = cursor.limit();
///     if let Some(after) = cursor.after() {
///         // SELECT * FROM events WHERE id > $after ORDER BY id LIMIT $limit
///     } else {
///         // SELECT * FROM events ORDER BY id LIMIT $limit
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct CursorPaginate {
    /// Opaque cursor token (None = start from beginning)
    pub cursor: Option<String>,
    /// Items per page (capped at MAX_PER_PAGE)
    pub per_page: u64,
}

impl CursorPaginate {
    /// Create a new CursorPaginate
    pub fn new(cursor: Option<String>, per_page: u64) -> Self {
        Self {
            cursor,
            per_page: per_page.clamp(1, MAX_PER_PAGE),
        }
    }

    /// Get the cursor value (if any)
    pub fn after(&self) -> Option<&str> {
        self.cursor.as_deref()
    }

    /// Get the LIMIT value
    pub fn limit(&self) -> u64 {
        self.per_page
    }

    /// Check if this is the first page (no cursor)
    pub fn is_first_page(&self) -> bool {
        self.cursor.is_none()
    }
}

impl Default for CursorPaginate {
    fn default() -> Self {
        Self {
            cursor: None,
            per_page: DEFAULT_PER_PAGE,
        }
    }
}

impl FromRequestParts for CursorPaginate {
    fn from_request_parts(req: &Request) -> Result<Self> {
        let query = req.query_string().unwrap_or("");

        #[derive(serde::Deserialize)]
        struct CursorQuery {
            cursor: Option<String>,
            limit: Option<u64>,
        }

        let params: CursorQuery = serde_urlencoded::from_str(query).unwrap_or(CursorQuery {
            cursor: None,
            limit: None,
        });

        Ok(CursorPaginate::new(
            params.cursor,
            params.limit.unwrap_or(DEFAULT_PER_PAGE),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::path_params::PathParams;
    use bytes::Bytes;
    use http::{Extensions, Method};
    use proptest::prelude::*;
    use proptest::test_runner::TestCaseError;
    use std::sync::Arc;

    /// Create a test request with the given method, path, and headers
    fn create_test_request_with_headers(
        method: Method,
        path: &str,
        headers: Vec<(&str, &str)>,
    ) -> Request {
        let uri: http::Uri = path.parse().unwrap();
        let mut builder = http::Request::builder().method(method).uri(uri);

        for (name, value) in headers {
            builder = builder.header(name, value);
        }

        let req = builder.body(()).unwrap();
        let (parts, _) = req.into_parts();

        Request::new(
            parts,
            crate::request::BodyVariant::Buffered(Bytes::new()),
            Arc::new(Extensions::new()),
            PathParams::new(),
        )
    }

    /// Create a test request with extensions
    fn create_test_request_with_extensions<T: Clone + Send + Sync + 'static>(
        method: Method,
        path: &str,
        extension: T,
    ) -> Request {
        let uri: http::Uri = path.parse().unwrap();
        let builder = http::Request::builder().method(method).uri(uri);

        let req = builder.body(()).unwrap();
        let (mut parts, _) = req.into_parts();
        parts.extensions.insert(extension);

        Request::new(
            parts,
            crate::request::BodyVariant::Buffered(Bytes::new()),
            Arc::new(Extensions::new()),
            PathParams::new(),
        )
    }

    // **Feature: phase3-batteries-included, Property 14: Headers extractor completeness**
    //
    // For any request with headers H, the `Headers` extractor SHALL return a map
    // containing all key-value pairs in H.
    //
    // **Validates: Requirements 5.1**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_headers_extractor_completeness(
            // Generate random header names and values
            // Using alphanumeric strings to ensure valid header names/values
            headers in prop::collection::vec(
                (
                    "[a-z][a-z0-9-]{0,20}",  // Valid header name pattern
                    "[a-zA-Z0-9 ]{1,50}"     // Valid header value pattern
                ),
                0..10
            )
        ) {
            let result: Result<(), TestCaseError> = (|| {
                // Convert to header tuples
                let header_tuples: Vec<(&str, &str)> = headers
                    .iter()
                    .map(|(k, v)| (k.as_str(), v.as_str()))
                    .collect();

                // Create request with headers
                let request = create_test_request_with_headers(
                    Method::GET,
                    "/test",
                    header_tuples.clone(),
                );

                // Extract headers
                let extracted = Headers::from_request_parts(&request)
                    .map_err(|e| TestCaseError::fail(format!("Failed to extract headers: {}", e)))?;

                // Verify all original headers are present
                // HTTP allows duplicate headers - get_all() returns all values for a header name
                for (name, value) in &headers {
                    // Check that the header name exists
                    let all_values: Vec<_> = extracted.get_all(name.as_str()).iter().collect();
                    prop_assert!(
                        !all_values.is_empty(),
                        "Header '{}' not found",
                        name
                    );

                    // Check that the value is among the extracted values
                    let value_found = all_values.iter().any(|v| {
                        v.to_str().map(|s| s == value.as_str()).unwrap_or(false)
                    });

                    prop_assert!(
                        value_found,
                        "Header '{}' value '{}' not found in extracted values",
                        name,
                        value
                    );
                }

                Ok(())
            })();
            result?;
        }
    }

    // **Feature: phase3-batteries-included, Property 15: HeaderValue extractor correctness**
    //
    // For any request with header "X" having value V, `HeaderValue::extract(req, "X")` SHALL return V;
    // for requests without header "X", it SHALL return an error.
    //
    // **Validates: Requirements 5.2**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_header_value_extractor_correctness(
            header_name in "[a-z][a-z0-9-]{0,20}",
            header_value in "[a-zA-Z0-9 ]{1,50}",
            has_header in prop::bool::ANY,
        ) {
            let result: Result<(), TestCaseError> = (|| {
                let headers = if has_header {
                    vec![(header_name.as_str(), header_value.as_str())]
                } else {
                    vec![]
                };

                let _request = create_test_request_with_headers(Method::GET, "/test", headers);

                // We need to use a static string for the header name in the extractor
                // So we'll test with a known header name
                let test_header = "x-test-header";
                let request_with_known_header = if has_header {
                    create_test_request_with_headers(
                        Method::GET,
                        "/test",
                        vec![(test_header, header_value.as_str())],
                    )
                } else {
                    create_test_request_with_headers(Method::GET, "/test", vec![])
                };

                let result = HeaderValue::extract(&request_with_known_header, test_header);

                if has_header {
                    let extracted = result
                        .map_err(|e| TestCaseError::fail(format!("Expected header to be found: {}", e)))?;
                    prop_assert_eq!(
                        extracted.value(),
                        header_value.as_str(),
                        "Header value mismatch"
                    );
                } else {
                    prop_assert!(
                        result.is_err(),
                        "Expected error when header is missing"
                    );
                }

                Ok(())
            })();
            result?;
        }
    }

    // **Feature: phase3-batteries-included, Property 17: ClientIp extractor with forwarding**
    //
    // For any request with socket IP S and X-Forwarded-For header F, when forwarding is enabled,
    // `ClientIp` SHALL return the first IP in F; when disabled, it SHALL return S.
    //
    // **Validates: Requirements 5.4**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_client_ip_extractor_with_forwarding(
            // Generate valid IPv4 addresses
            forwarded_ip in (0u8..=255, 0u8..=255, 0u8..=255, 0u8..=255)
                .prop_map(|(a, b, c, d)| format!("{}.{}.{}.{}", a, b, c, d)),
            socket_ip in (0u8..=255, 0u8..=255, 0u8..=255, 0u8..=255)
                .prop_map(|(a, b, c, d)| std::net::IpAddr::V4(std::net::Ipv4Addr::new(a, b, c, d))),
            has_forwarded_header in prop::bool::ANY,
            trust_proxy in prop::bool::ANY,
        ) {
            let result: Result<(), TestCaseError> = (|| {
                let headers = if has_forwarded_header {
                    vec![("x-forwarded-for", forwarded_ip.as_str())]
                } else {
                    vec![]
                };

                // Create request with headers
                let uri: http::Uri = "/test".parse().unwrap();
                let mut builder = http::Request::builder().method(Method::GET).uri(uri);
                for (name, value) in &headers {
                    builder = builder.header(*name, *value);
                }
                let req = builder.body(()).unwrap();
                let (mut parts, _) = req.into_parts();

                // Add socket address to extensions
                let socket_addr = std::net::SocketAddr::new(socket_ip, 8080);
                parts.extensions.insert(socket_addr);

                let request = Request::new(
                    parts,
                    crate::request::BodyVariant::Buffered(Bytes::new()),
                    Arc::new(Extensions::new()),
                    PathParams::new(),
                );

                let extracted = ClientIp::extract_with_config(&request, trust_proxy)
                    .map_err(|e| TestCaseError::fail(format!("Failed to extract ClientIp: {}", e)))?;

                if trust_proxy && has_forwarded_header {
                    // Should use X-Forwarded-For
                    let expected_ip: std::net::IpAddr = forwarded_ip.parse()
                        .map_err(|e| TestCaseError::fail(format!("Invalid IP: {}", e)))?;
                    prop_assert_eq!(
                        extracted.0,
                        expected_ip,
                        "Should use X-Forwarded-For IP when trust_proxy is enabled"
                    );
                } else {
                    // Should use socket IP
                    prop_assert_eq!(
                        extracted.0,
                        socket_ip,
                        "Should use socket IP when trust_proxy is disabled or no X-Forwarded-For"
                    );
                }

                Ok(())
            })();
            result?;
        }
    }

    // **Feature: phase3-batteries-included, Property 18: Extension extractor retrieval**
    //
    // For any type T and value V inserted into request extensions by middleware,
    // `Extension<T>` SHALL return V.
    //
    // **Validates: Requirements 5.5**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_extension_extractor_retrieval(
            value in any::<i64>(),
            has_extension in prop::bool::ANY,
        ) {
            let result: Result<(), TestCaseError> = (|| {
                // Create a simple wrapper type for testing
                #[derive(Clone, Debug, PartialEq)]
                struct TestExtension(i64);

                let uri: http::Uri = "/test".parse().unwrap();
                let builder = http::Request::builder().method(Method::GET).uri(uri);
                let req = builder.body(()).unwrap();
                let (mut parts, _) = req.into_parts();

                if has_extension {
                    parts.extensions.insert(TestExtension(value));
                }

                let request = Request::new(
                    parts,
                    crate::request::BodyVariant::Buffered(Bytes::new()),
                    Arc::new(Extensions::new()),
                    PathParams::new(),
                );

                let result = Extension::<TestExtension>::from_request_parts(&request);

                if has_extension {
                    let extracted = result
                        .map_err(|e| TestCaseError::fail(format!("Expected extension to be found: {}", e)))?;
                    prop_assert_eq!(
                        extracted.0,
                        TestExtension(value),
                        "Extension value mismatch"
                    );
                } else {
                    prop_assert!(
                        result.is_err(),
                        "Expected error when extension is missing"
                    );
                }

                Ok(())
            })();
            result?;
        }
    }

    // Unit tests for basic functionality

    #[test]
    fn test_headers_extractor_basic() {
        let request = create_test_request_with_headers(
            Method::GET,
            "/test",
            vec![
                ("content-type", "application/json"),
                ("accept", "text/html"),
            ],
        );

        let headers = Headers::from_request_parts(&request).unwrap();

        assert!(headers.contains("content-type"));
        assert!(headers.contains("accept"));
        assert!(!headers.contains("x-custom"));
        assert_eq!(headers.len(), 2);
    }

    #[test]
    fn test_header_value_extractor_present() {
        let request = create_test_request_with_headers(
            Method::GET,
            "/test",
            vec![("authorization", "Bearer token123")],
        );

        let result = HeaderValue::extract(&request, "authorization");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().value(), "Bearer token123");
    }

    #[test]
    fn test_header_value_extractor_missing() {
        let request = create_test_request_with_headers(Method::GET, "/test", vec![]);

        let result = HeaderValue::extract(&request, "authorization");
        assert!(result.is_err());
    }

    #[test]
    fn test_client_ip_from_forwarded_header() {
        let request = create_test_request_with_headers(
            Method::GET,
            "/test",
            vec![("x-forwarded-for", "192.168.1.100, 10.0.0.1")],
        );

        let ip = ClientIp::extract_with_config(&request, true).unwrap();
        assert_eq!(ip.0, "192.168.1.100".parse::<std::net::IpAddr>().unwrap());
    }

    #[test]
    fn test_client_ip_ignores_forwarded_when_not_trusted() {
        let uri: http::Uri = "/test".parse().unwrap();
        let builder = http::Request::builder()
            .method(Method::GET)
            .uri(uri)
            .header("x-forwarded-for", "192.168.1.100");
        let req = builder.body(()).unwrap();
        let (mut parts, _) = req.into_parts();

        let socket_addr = std::net::SocketAddr::new(
            std::net::IpAddr::V4(std::net::Ipv4Addr::new(10, 0, 0, 1)),
            8080,
        );
        parts.extensions.insert(socket_addr);

        let request = Request::new(
            parts,
            crate::request::BodyVariant::Buffered(Bytes::new()),
            Arc::new(Extensions::new()),
            PathParams::new(),
        );

        let ip = ClientIp::extract_with_config(&request, false).unwrap();
        assert_eq!(ip.0, "10.0.0.1".parse::<std::net::IpAddr>().unwrap());
    }

    #[test]
    fn test_extension_extractor_present() {
        #[derive(Clone, Debug, PartialEq)]
        struct MyData(String);

        let request =
            create_test_request_with_extensions(Method::GET, "/test", MyData("hello".to_string()));

        let result = Extension::<MyData>::from_request_parts(&request);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().0, MyData("hello".to_string()));
    }

    #[test]
    fn test_extension_extractor_missing() {
        #[derive(Clone, Debug)]
        #[allow(dead_code)]
        struct MyData(String);

        let request = create_test_request_with_headers(Method::GET, "/test", vec![]);

        let result = Extension::<MyData>::from_request_parts(&request);
        assert!(result.is_err());
    }

    // Cookies tests (feature-gated)
    #[cfg(feature = "cookies")]
    mod cookies_tests {
        use super::*;

        // **Feature: phase3-batteries-included, Property 16: Cookies extractor parsing**
        //
        // For any request with Cookie header containing cookies C, the `Cookies` extractor
        // SHALL return a CookieJar containing exactly the cookies in C.
        // Note: Duplicate cookie names result in only the last value being kept.
        //
        // **Validates: Requirements 5.3**
        proptest! {
            #![proptest_config(ProptestConfig::with_cases(100))]

            #[test]
            fn prop_cookies_extractor_parsing(
                // Generate random cookie names and values
                // Using alphanumeric strings to ensure valid cookie names/values
                cookies in prop::collection::vec(
                    (
                        "[a-zA-Z][a-zA-Z0-9_]{0,15}",  // Valid cookie name pattern
                        "[a-zA-Z0-9]{1,30}"            // Valid cookie value pattern (no special chars)
                    ),
                    0..5
                )
            ) {
                let result: Result<(), TestCaseError> = (|| {
                    // Build cookie header string
                    let cookie_header = cookies
                        .iter()
                        .map(|(name, value)| format!("{}={}", name, value))
                        .collect::<Vec<_>>()
                        .join("; ");

                    let headers = if !cookies.is_empty() {
                        vec![("cookie", cookie_header.as_str())]
                    } else {
                        vec![]
                    };

                    let request = create_test_request_with_headers(Method::GET, "/test", headers);

                    // Extract cookies
                    let extracted = Cookies::from_request_parts(&request)
                        .map_err(|e| TestCaseError::fail(format!("Failed to extract cookies: {}", e)))?;

                    // Build expected cookies map - last value wins for duplicate names
                    let mut expected_cookies: std::collections::HashMap<&str, &str> = std::collections::HashMap::new();
                    for (name, value) in &cookies {
                        expected_cookies.insert(name.as_str(), value.as_str());
                    }

                    // Verify all expected cookies are present with correct values
                    for (name, expected_value) in &expected_cookies {
                        let cookie = extracted.get(name)
                            .ok_or_else(|| TestCaseError::fail(format!("Cookie '{}' not found", name)))?;

                        prop_assert_eq!(
                            cookie.value(),
                            *expected_value,
                            "Cookie '{}' value mismatch",
                            name
                        );
                    }

                    // Count cookies in jar should match unique cookie names
                    let extracted_count = extracted.iter().count();
                    prop_assert_eq!(
                        extracted_count,
                        expected_cookies.len(),
                        "Expected {} unique cookies, got {}",
                        expected_cookies.len(),
                        extracted_count
                    );

                    Ok(())
                })();
                result?;
            }
        }

        #[test]
        fn test_cookies_extractor_basic() {
            let request = create_test_request_with_headers(
                Method::GET,
                "/test",
                vec![("cookie", "session=abc123; user=john")],
            );

            let cookies = Cookies::from_request_parts(&request).unwrap();

            assert!(cookies.contains("session"));
            assert!(cookies.contains("user"));
            assert!(!cookies.contains("other"));

            assert_eq!(cookies.get("session").unwrap().value(), "abc123");
            assert_eq!(cookies.get("user").unwrap().value(), "john");
        }

        #[test]
        fn test_cookies_extractor_empty() {
            let request = create_test_request_with_headers(Method::GET, "/test", vec![]);

            let cookies = Cookies::from_request_parts(&request).unwrap();
            assert_eq!(cookies.iter().count(), 0);
        }

        #[test]
        fn test_cookies_extractor_single() {
            let request = create_test_request_with_headers(
                Method::GET,
                "/test",
                vec![("cookie", "token=xyz789")],
            );

            let cookies = Cookies::from_request_parts(&request).unwrap();
            assert_eq!(cookies.iter().count(), 1);
            assert_eq!(cookies.get("token").unwrap().value(), "xyz789");
        }
    }

    #[tokio::test]
    async fn test_async_validated_json_with_state_context() {
        use async_trait::async_trait;
        use rustapi_validate::prelude::*;
        use rustapi_validate::v2::{
            AsyncValidationRule, DatabaseValidator, ValidationContextBuilder,
        };
        use serde::{Deserialize, Serialize};

        struct MockDbValidator {
            unique_values: Vec<String>,
        }

        #[async_trait]
        impl DatabaseValidator for MockDbValidator {
            async fn exists(
                &self,
                _table: &str,
                _column: &str,
                _value: &str,
            ) -> Result<bool, String> {
                Ok(true)
            }
            async fn is_unique(
                &self,
                _table: &str,
                _column: &str,
                value: &str,
            ) -> Result<bool, String> {
                Ok(!self.unique_values.contains(&value.to_string()))
            }
            async fn is_unique_except(
                &self,
                _table: &str,
                _column: &str,
                value: &str,
                _except_id: &str,
            ) -> Result<bool, String> {
                Ok(!self.unique_values.contains(&value.to_string()))
            }
        }

        #[derive(Debug, Deserialize, Serialize)]
        struct TestUser {
            email: String,
        }

        impl Validate for TestUser {
            fn validate_with_group(
                &self,
                _group: rustapi_validate::v2::ValidationGroup,
            ) -> Result<(), rustapi_validate::v2::ValidationErrors> {
                Ok(())
            }
        }

        #[async_trait]
        impl AsyncValidate for TestUser {
            async fn validate_async_with_group(
                &self,
                ctx: &ValidationContext,
                _group: rustapi_validate::v2::ValidationGroup,
            ) -> Result<(), rustapi_validate::v2::ValidationErrors> {
                let mut errors = rustapi_validate::v2::ValidationErrors::new();

                let rule = AsyncUniqueRule::new("users", "email");
                if let Err(e) = rule.validate_async(&self.email, ctx).await {
                    errors.add("email", e);
                }

                errors.into_result()
            }
        }

        // Test 1: Without context in state (should fail due to missing validator)
        let uri: http::Uri = "/test".parse().unwrap();
        let user = TestUser {
            email: "new@example.com".to_string(),
        };
        let body_bytes = serde_json::to_vec(&user).unwrap();

        let builder = http::Request::builder()
            .method(Method::POST)
            .uri(uri.clone())
            .header("content-type", "application/json");
        let req = builder.body(()).unwrap();
        let (parts, _) = req.into_parts();

        // Construct Request with BodyVariant::Buffered
        let mut request = Request::new(
            parts,
            crate::request::BodyVariant::Buffered(Bytes::from(body_bytes.clone())),
            Arc::new(Extensions::new()),
            PathParams::new(),
        );

        let result = AsyncValidatedJson::<TestUser>::from_request(&mut request).await;

        assert!(result.is_err(), "Expected error when validator is missing");
        let err = result.unwrap_err();
        let err_str = format!("{:?}", err);
        assert!(
            err_str.contains("Database validator not configured")
                || err_str.contains("async_unique"),
            "Error should mention missing configuration or rule: {:?}",
            err_str
        );

        // Test 2: With context in state (should succeed)
        let db_validator = MockDbValidator {
            unique_values: vec!["taken@example.com".to_string()],
        };
        let ctx = ValidationContextBuilder::new()
            .database(db_validator)
            .build();

        let mut extensions = Extensions::new();
        extensions.insert(ctx);

        let builder = http::Request::builder()
            .method(Method::POST)
            .uri(uri.clone())
            .header("content-type", "application/json");
        let req = builder.body(()).unwrap();
        let (parts, _) = req.into_parts();

        let mut request = Request::new(
            parts,
            crate::request::BodyVariant::Buffered(Bytes::from(body_bytes.clone())),
            Arc::new(extensions),
            PathParams::new(),
        );

        let result = AsyncValidatedJson::<TestUser>::from_request(&mut request).await;
        assert!(
            result.is_ok(),
            "Expected success when validator is present and value is unique. Error: {:?}",
            result.err()
        );

        // Test 3: With context in state (should fail validation logic)
        let user_taken = TestUser {
            email: "taken@example.com".to_string(),
        };
        let body_taken = serde_json::to_vec(&user_taken).unwrap();

        let db_validator = MockDbValidator {
            unique_values: vec!["taken@example.com".to_string()],
        };
        let ctx = ValidationContextBuilder::new()
            .database(db_validator)
            .build();

        let mut extensions = Extensions::new();
        extensions.insert(ctx);

        let builder = http::Request::builder()
            .method(Method::POST)
            .uri("/test")
            .header("content-type", "application/json");
        let req = builder.body(()).unwrap();
        let (parts, _) = req.into_parts();

        let mut request = Request::new(
            parts,
            crate::request::BodyVariant::Buffered(Bytes::from(body_taken)),
            Arc::new(extensions),
            PathParams::new(),
        );

        let result = AsyncValidatedJson::<TestUser>::from_request(&mut request).await;
        assert!(result.is_err(), "Expected validation error for taken email");
    }
}