asupersync 0.3.6

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
//! Request extractors.
//!
//! Extractors pull typed data from incoming HTTP requests. Each extractor
//! implements [`FromRequest`] or [`FromRequestParts`] and can be used as a
//! handler parameter.
//!
//! # Built-in Extractors
//!
//! - [`Path<T>`]: URL path parameters
//! - [`Query<T>`]: Query string parameters
//! - [`Json<T>`]: JSON request body
//! - [`Form<T>`]: URL-encoded form body
//! - [`Header<T>`] / [`TypedHeader<T>`]: Typed request headers
//! - [`Cookie`]: Raw `Cookie` request header
//! - [`CookieJar`]: Parsed request cookies
//! - [`State<T>`]: Shared application state
//! - [`RawBody`]: Raw request body bytes

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use crate::bytes::Bytes;
use serde::de::{
    self, DeserializeOwned, DeserializeSeed, IntoDeserializer, SeqAccess, Unexpected, Visitor,
};
use serde::forward_to_deserialize_any;

const MALFORMED_HEADER_CODE: &str = "[ASUP-E503]";

// ─── Request Type ────────────────────────────────────────────────────────────

/// An incoming HTTP request.
#[derive(Debug, Clone)]
pub struct Request {
    /// HTTP method (GET, POST, etc.).
    pub method: String,
    /// Request path (e.g., "/users/42").
    pub path: String,
    /// Query string (everything after '?'), if present.
    pub query: Option<String>,
    /// Request headers.
    pub headers: HashMap<String, String>,
    /// Request body bytes.
    pub body: Bytes,
    /// Path parameters extracted by the router (e.g., `{ "id": "42" }`).
    pub path_params: HashMap<String, String>,
    /// Extensions for middleware-injected state.
    pub extensions: Extensions,
}

impl Request {
    /// Create a new request (primarily for testing).
    #[must_use]
    pub fn new(method: impl Into<String>, path: impl Into<String>) -> Self {
        Self {
            method: method.into(),
            path: path.into(),
            query: None,
            headers: HashMap::with_capacity(8),
            body: Bytes::new(),
            path_params: HashMap::with_capacity(2),
            extensions: Extensions::new(),
        }
    }

    /// Set the query string.
    #[must_use]
    pub fn with_query(mut self, query: impl Into<String>) -> Self {
        self.query = Some(query.into());
        self
    }

    /// Set the request body.
    #[must_use]
    pub fn with_body(mut self, body: impl Into<Bytes>) -> Self {
        self.body = body.into();
        self
    }

    /// Set a header.
    ///
    /// Header names are normalized to lowercase so the lightweight web stack
    /// can treat them case-insensitively.
    #[must_use]
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers
            .insert(name.into().to_ascii_lowercase(), value.into());
        self
    }

    /// Returns a header value using HTTP's case-insensitive matching rules.
    #[must_use]
    pub fn header(&self, name: &str) -> Option<&str> {
        if let Some(value) = self.headers.get(name) {
            return Some(value.as_str());
        }

        self.headers
            .iter()
            .find(|(key, _)| key.eq_ignore_ascii_case(name))
            .map(|(_, value)| value.as_str())
    }

    /// Set path parameters (used internally by the router).
    #[must_use]
    pub fn with_path_params(mut self, params: HashMap<String, String>) -> Self {
        self.path_params = params;
        self
    }
}

// ─── Extensions ──────────────────────────────────────────────────────────────

/// Type-erased extension map for middleware-injected data.
///
/// Allows middleware to inject arbitrary typed state into requests.
#[derive(Clone, Default)]
pub struct Extensions {
    string_data: HashMap<String, String>,
    typed_data: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
}

impl fmt::Debug for Extensions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Extensions")
            .field("string_keys", &self.string_data.keys().collect::<Vec<_>>())
            .field("typed_count", &self.typed_data.len())
            .finish()
    }
}

impl Extensions {
    /// Create an empty extensions map.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert a value by key.
    pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.string_data.insert(key.into(), value.into());
    }

    /// Get a value by key.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&str> {
        self.string_data.get(key).map(String::as_str)
    }

    /// Insert a typed value.
    pub fn insert_typed<T>(&mut self, value: T)
    where
        T: Send + Sync + 'static,
    {
        self.typed_data.insert(TypeId::of::<T>(), Arc::new(value));
    }

    /// Get a typed value.
    #[must_use]
    pub fn get_typed<T>(&self) -> Option<&T>
    where
        T: Send + Sync + 'static,
    {
        self.typed_data
            .get(&TypeId::of::<T>())
            .and_then(|value| value.as_ref().downcast_ref::<T>())
    }

    /// Get a cloned typed value.
    #[must_use]
    pub fn get_typed_cloned<T>(&self) -> Option<T>
    where
        T: Clone + Send + Sync + 'static,
    {
        self.get_typed::<T>().cloned()
    }

    /// Merge data from another extension map.
    pub(crate) fn extend_from(&mut self, other: &Self) {
        self.string_data.extend(other.string_data.clone());
        self.typed_data.extend(
            other
                .typed_data
                .iter()
                .map(|(type_id, value)| (*type_id, Arc::clone(value))),
        );
    }
}

// ─── Extraction Error ────────────────────────────────────────────────────────

/// Error returned when extraction fails.
#[derive(Debug, Clone)]
pub struct ExtractionError {
    /// Human-readable description.
    pub message: String,
    /// Suggested HTTP status code for the error response.
    pub status: super::response::StatusCode,
}

impl ExtractionError {
    /// Create a new extraction error.
    #[must_use]
    pub fn new(status: super::response::StatusCode, message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            status,
        }
    }

    /// Create a 400 Bad Request extraction error.
    #[must_use]
    pub fn bad_request(message: impl Into<String>) -> Self {
        Self::new(super::response::StatusCode::BAD_REQUEST, message)
    }

    /// Create a 422 Unprocessable Entity extraction error.
    #[must_use]
    pub fn unprocessable(message: impl Into<String>) -> Self {
        Self::new(super::response::StatusCode::UNPROCESSABLE_ENTITY, message)
    }
}

impl fmt::Display for ExtractionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.status, self.message)
    }
}

impl std::error::Error for ExtractionError {}

impl super::response::IntoResponse for ExtractionError {
    fn into_response(self) -> super::response::Response {
        super::response::Response::new(self.status, Bytes::copy_from_slice(self.message.as_bytes()))
            .header("content-type", "text/plain; charset=utf-8")
    }
}

// ─── FromRequest / FromRequestParts ──────────────────────────────────────────

/// Extract a value from request parts (headers, path, query).
///
/// Extractors implementing this trait can be used without consuming the body.
pub trait FromRequestParts: Sized {
    /// Attempt to extract from request parts.
    fn from_request_parts(req: &Request) -> Result<Self, ExtractionError>;
}

/// Extract a value from the full request (may consume the body).
///
/// Only one body-consuming extractor can be used per handler.
pub trait FromRequest: Sized {
    /// Attempt to extract from the request.
    fn from_request(req: Request) -> Result<Self, ExtractionError>;
}

// Blanket: anything that implements FromRequestParts also implements FromRequest.
impl<T: FromRequestParts> FromRequest for T {
    fn from_request(req: Request) -> Result<Self, ExtractionError> {
        Self::from_request_parts(&req)
    }
}

// ─── Path<T> ─────────────────────────────────────────────────────────────────

/// Extract path parameters.
///
/// For a single parameter, primitive/owned types can be extracted directly
/// (for example `Path<u64>` or `Path<String>`). For named parameters, extract
/// into a `Deserialize` type (for example a struct or `HashMap<String, String>`).
///
/// ```ignore
/// async fn get_user(Path(id): Path<String>) -> String {
///     format!("User {id}")
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Path<T>(pub T);

impl<T> FromRequestParts for Path<T>
where
    T: DeserializeOwned,
{
    fn from_request_parts(req: &Request) -> Result<Self, ExtractionError> {
        if req.path_params.is_empty() {
            return Err(ExtractionError::bad_request("no path parameters found"));
        }

        if req.path_params.len() == 1
            && let Some(first) = req.path_params.values().next()
            && let Some(value) = deserialize_single_value::<T>(first)
        {
            return Ok(Self(value));
        }

        deserialize_from_string_map(&req.path_params, "path parameters").map(Self)
    }
}

// ─── Query<T> ────────────────────────────────────────────────────────────────

/// Extract query string parameters.
///
/// Deserializes query pairs into typed values.
///
/// ```ignore
/// #[derive(Deserialize)]
/// struct Pagination { page: u32, per_page: u32 }
///
/// async fn list(Query(p): Query<Pagination>) -> String {
///     format!("Page {} ({} per page)", p.page, p.per_page)
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Query<T>(pub T);

impl<T> FromRequestParts for Query<T>
where
    T: DeserializeOwned,
{
    fn from_request_parts(req: &Request) -> Result<Self, ExtractionError> {
        let qs = req.query.as_deref().unwrap_or("");
        let parsed = parse_urlencoded(qs, "query parameter")?;

        if parsed.len() == 1
            && let Some(first) = parsed.values().next()
            && let Some(value) = deserialize_single_value::<T>(first)
        {
            return Ok(Self(value));
        }

        deserialize_from_string_map(&parsed, "query parameters").map(Self)
    }
}

fn deserialize_single_value<T>(raw: &str) -> Option<T>
where
    T: DeserializeOwned,
{
    if let Ok(parsed) = serde_json::from_value::<T>(serde_json::Value::String(raw.to_string())) {
        return Some(parsed);
    }

    serde_json::from_value::<T>(coerce_json_scalar(raw)).ok()
}

#[allow(clippy::implicit_hasher)]
fn deserialize_from_string_map<T>(
    values: &HashMap<String, String>,
    context: &str,
) -> Result<T, ExtractionError>
where
    T: DeserializeOwned,
{
    // Use the same type-directed deserializer as `Form`: it coerces each value
    // based on the *target field's* requested type (string fields stay strings
    // via `deserialize_str`/`deserialize_any`; numeric/bool fields parse),
    // rather than the previous per-value guessing. The old two-pass approach
    // (all-strings, then coerce-every-value-to-its-looks-like type) broke any
    // struct mixing a `String` field with a numeric field: a string field
    // holding a numeric-looking value (an all-digit username, a numeric id or
    // ZIP passed as text, "true"/"false" strings) was coerced to a JSON
    // number/bool in the fallback pass and then failed to deserialize into
    // `String`, returning a confusing 400 to legitimate clients.
    //
    // Query and Path are always single-valued here (duplicate query keys are
    // rejected upstream in `parse_urlencoded`, and path params are a
    // single-value map), so each value becomes a one-element slice.
    let multi: HashMap<String, Vec<String>> = values
        .iter()
        .map(|(key, value)| (key.clone(), vec![value.clone()]))
        .collect();
    deserialize_from_multi_value_map(&multi, context)
}

fn coerce_json_scalar(raw: &str) -> serde_json::Value {
    if let Ok(boolean) = raw.parse::<bool>() {
        return serde_json::Value::Bool(boolean);
    }
    if let Ok(integer) = raw.parse::<i64>() {
        return serde_json::Value::Number(integer.into());
    }
    if let Ok(unsigned) = raw.parse::<u64>() {
        return serde_json::Value::Number(unsigned.into());
    }
    if let Ok(float) = raw.parse::<f64>()
        && let Some(number) = serde_json::Number::from_f64(float)
    {
        return serde_json::Value::Number(number);
    }
    serde_json::Value::String(raw.to_string())
}

/// Deserialize from multi-value map (for forms with duplicate keys).
///
/// Handles both single values and Vec<String> according to target type.
/// For single-value fields, uses the first value. For Vec fields, preserves all values.
fn deserialize_from_multi_value_map<T>(
    parsed: &HashMap<String, Vec<String>>,
    context: &str,
) -> Result<T, ExtractionError>
where
    T: DeserializeOwned,
{
    let fields = parsed
        .iter()
        .map(|(key, values)| (key.as_str(), FormValueDeserializer { values }));
    let deserializer = de::value::MapDeserializer::new(fields);
    T::deserialize(deserializer)
        .map_err(|e| ExtractionError::bad_request(format!("invalid {context}: {e}")))
}

#[derive(Clone, Copy)]
struct FormValueDeserializer<'a> {
    values: &'a [String],
}

impl<'a> FormValueDeserializer<'a> {
    fn first<E>(self) -> Result<&'a str, E>
    where
        E: de::Error,
    {
        self.values
            .first()
            .map(String::as_str)
            .ok_or_else(|| E::invalid_value(Unexpected::Seq, &"at least one form value"))
    }

    fn parse<T, E>(self, expected: &'static str) -> Result<T, E>
    where
        T: std::str::FromStr,
        E: de::Error,
    {
        let raw = self.first::<E>()?;
        raw.parse::<T>()
            .map_err(|_| E::invalid_value(Unexpected::Str(raw), &expected))
    }
}

impl<'de> IntoDeserializer<'de, de::value::Error> for FormValueDeserializer<'de> {
    type Deserializer = Self;

    fn into_deserializer(self) -> Self::Deserializer {
        self
    }
}

impl<'de> de::Deserializer<'de> for FormValueDeserializer<'de> {
    type Error = de::value::Error;

    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_str(self.first::<Self::Error>()?)
    }

    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_bool(self.parse("a boolean")?)
    }

    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i8(self.parse("an i8")?)
    }

    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i16(self.parse("an i16")?)
    }

    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i32(self.parse("an i32")?)
    }

    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_i64(self.parse("an i64")?)
    }

    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_u8(self.parse("a u8")?)
    }

    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_u16(self.parse("a u16")?)
    }

    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_u32(self.parse("a u32")?)
    }

    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_u64(self.parse("a u64")?)
    }

    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_f32(self.parse("an f32")?)
    }

    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_f64(self.parse("an f64")?)
    }

    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let raw = self.first::<Self::Error>()?;
        let mut chars = raw.chars();
        match (chars.next(), chars.next()) {
            (Some(c), None) => visitor.visit_char(c),
            _ => Err(de::Error::invalid_value(Unexpected::Str(raw), &"a char")),
        }
    }

    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_str(self.first::<Self::Error>()?)
    }

    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_string(self.first::<Self::Error>()?.to_string())
    }

    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_bytes(self.first::<Self::Error>()?.as_bytes())
    }

    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_byte_buf(self.first::<Self::Error>()?.as_bytes().to_vec())
    }

    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        if self.values.is_empty() {
            visitor.visit_none()
        } else {
            visitor.visit_some(self)
        }
    }

    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        if self.first::<Self::Error>()?.is_empty() {
            visitor.visit_unit()
        } else {
            Err(de::Error::invalid_value(
                Unexpected::Str(self.first::<Self::Error>()?),
                &"an empty form value",
            ))
        }
    }

    fn deserialize_newtype_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_seq(FormSeqDeserializer {
            values: self.values.iter(),
        })
    }

    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.deserialize_seq(visitor)
    }

    fn deserialize_tuple_struct<V>(
        self,
        _name: &'static str,
        _len: usize,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.deserialize_seq(visitor)
    }

    fn deserialize_enum<V>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_enum(self.first::<Self::Error>()?.into_deserializer())
    }

    forward_to_deserialize_any! {
        unit_struct map struct identifier ignored_any
    }
}

struct FormSeqDeserializer<'a> {
    values: std::slice::Iter<'a, String>,
}

impl<'de> SeqAccess<'de> for FormSeqDeserializer<'de> {
    type Error = de::value::Error;

    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
    where
        T: DeserializeSeed<'de>,
    {
        self.values
            .next()
            .map(|value| {
                seed.deserialize(FormValueDeserializer {
                    values: std::slice::from_ref(value),
                })
            })
            .transpose()
    }
}

/// Parse a URL-encoded string into key-value pairs.
///
/// Per HTML form specification, duplicate keys should preserve all values
/// as Vec<String> rather than rejecting or overwriting. This correctly
/// handles forms like `a=1&a=2` -> `{"a": ["1", "2"]}`.
fn parse_urlencoded_multi(
    input: &str,
    _field_kind: &str,
) -> Result<HashMap<String, Vec<String>>, ExtractionError> {
    let mut parsed: HashMap<String, Vec<String>> = HashMap::new();
    for pair in input.split('&').filter(|s| !s.is_empty()) {
        let mut parts = pair.splitn(2, '=');
        let Some(key) = parts.next() else {
            continue;
        };
        let key = percent_decode(key);
        let value = percent_decode(parts.next().unwrap_or(""));
        parsed.entry(key).or_default().push(value);
    }
    Ok(parsed)
}

/// Legacy parse function for backward compatibility with single values.
/// Used by Query extractor which may want different duplicate key behavior.
fn parse_urlencoded(
    input: &str,
    field_kind: &str,
) -> Result<HashMap<String, String>, ExtractionError> {
    let multi_values = parse_urlencoded_multi(input, field_kind)?;
    let mut single_values = HashMap::new();

    for (key, values) in multi_values {
        if values.len() == 1 {
            // Safe: length check ensures exactly one element exists
            if let Some(value) = values.into_iter().next() {
                single_values.insert(key, value);
            } else {
                // Should never happen given length check, but handle gracefully
                return Err(ExtractionError::bad_request(format!(
                    "internal error: expected value for {field_kind} `{key}`"
                )));
            }
        } else {
            return Err(ExtractionError::bad_request(format!(
                "duplicate {field_kind} `{key}` (use multi-value extractor for forms)"
            )));
        }
    }
    Ok(single_values)
}

/// Simple percent-decoding (handles %XX and + as space).
fn percent_decode(input: &str) -> String {
    let input = input.as_bytes();
    let mut output = Vec::with_capacity(input.len());
    let mut i = 0;
    while i < input.len() {
        match input[i] {
            b'+' => {
                output.push(b' ');
                i += 1;
            }
            b'%' => {
                if i.saturating_add(2) < input.len() {
                    let hi = hex_val(input[i.saturating_add(1)]);
                    let lo = hex_val(input[i.saturating_add(2)]);
                    if let (Some(h), Some(l)) = (hi, lo) {
                        output.push(h << 4 | l);
                        i += 3;
                    } else {
                        output.push(b'%');
                        i += 1;
                    }
                } else {
                    output.push(b'%');
                    i += 1;
                }
            }
            b => {
                output.push(b);
                i += 1;
            }
        }
    }
    String::from_utf8(output).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
}

fn hex_val(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

// ─── Header<T> / TypedHeader<T> ─────────────────────────────────────────────

/// Error returned by a typed header parser.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HeaderParseError {
    message: String,
}

impl HeaderParseError {
    /// Create a typed header parse error.
    #[must_use]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }

    /// Human-readable parse failure.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for HeaderParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for HeaderParseError {}

/// Convert one request header value into a typed extractor value.
pub trait FromHeaderValue: Sized {
    /// Canonical header name used by the extractor.
    const NAME: &'static str;

    /// Parse a header value.
    fn from_header_value(value: &str) -> Result<Self, HeaderParseError>;
}

/// Extract a typed request header.
///
/// ```
/// use asupersync::web::extract::{
///     ContentType, FromRequestParts, Header, Request,
/// };
///
/// let req = Request::new("POST", "/items")
///     .with_header("Content-Type", "application/json; charset=utf-8");
///
/// let Header(content_type) =
///     Header::<ContentType>::from_request_parts(&req).expect("content type");
/// assert_eq!(content_type.media_type(), "application/json");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Header<T>(pub T);

impl<T> FromRequestParts for Header<T>
where
    T: FromHeaderValue,
{
    fn from_request_parts(req: &Request) -> Result<Self, ExtractionError> {
        extract_typed_header::<T>(req).map(Self)
    }
}

/// Extract a typed request header.
///
/// This is a naming alias in behavior, not a global header map. It extracts
/// exactly one typed header through [`FromHeaderValue`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypedHeader<T>(pub T);

impl<T> FromRequestParts for TypedHeader<T>
where
    T: FromHeaderValue,
{
    fn from_request_parts(req: &Request) -> Result<Self, ExtractionError> {
        extract_typed_header::<T>(req).map(Self)
    }
}

/// `Content-Type` request header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContentType(pub String);

impl ContentType {
    /// Full header value.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Media type without parameters.
    #[must_use]
    pub fn media_type(&self) -> &str {
        self.0.split(';').next().unwrap_or("").trim()
    }
}

impl FromHeaderValue for ContentType {
    const NAME: &'static str = "content-type";

    fn from_header_value(value: &str) -> Result<Self, HeaderParseError> {
        let trimmed = checked_header_value(Self::NAME, value)?;
        let media_type = trimmed.split(';').next().unwrap_or("").trim();
        validate_media_range(media_type, false)?;
        Ok(Self(trimmed.to_string()))
    }
}

/// `Authorization` request header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Authorization {
    /// Authorization scheme, e.g. `Bearer`.
    pub scheme: String,
    /// Scheme credentials.
    pub credentials: String,
}

impl Authorization {
    /// Reconstruct the header value.
    #[must_use]
    pub fn as_str(&self) -> String {
        format!("{} {}", self.scheme, self.credentials)
    }
}

impl FromHeaderValue for Authorization {
    const NAME: &'static str = "authorization";

    fn from_header_value(value: &str) -> Result<Self, HeaderParseError> {
        let trimmed = checked_header_value(Self::NAME, value)?;
        let mut parts = trimmed.splitn(2, char::is_whitespace);
        let scheme = parts.next().unwrap_or("");
        let credentials = parts.next().unwrap_or("").trim();

        if scheme.is_empty() || !scheme.bytes().all(is_http_token_char) {
            return Err(HeaderParseError::new(
                "Authorization scheme must be a non-empty HTTP token",
            ));
        }
        if credentials.is_empty() {
            return Err(HeaderParseError::new(
                "Authorization credentials must be present",
            ));
        }

        Ok(Self {
            scheme: scheme.to_string(),
            credentials: credentials.to_string(),
        })
    }
}

/// `User-Agent` request header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserAgent(pub String);

impl UserAgent {
    /// Full header value.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromHeaderValue for UserAgent {
    const NAME: &'static str = "user-agent";

    fn from_header_value(value: &str) -> Result<Self, HeaderParseError> {
        Ok(Self(checked_header_value(Self::NAME, value)?.to_string()))
    }
}

/// `Accept` request header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Accept(pub String);

impl Accept {
    /// Full header value.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromHeaderValue for Accept {
    const NAME: &'static str = "accept";

    fn from_header_value(value: &str) -> Result<Self, HeaderParseError> {
        let trimmed = checked_header_value(Self::NAME, value)?;
        for raw_range in trimmed.split(',') {
            let media_range = raw_range.split(';').next().unwrap_or("").trim();
            validate_media_range(media_range, true)?;
        }
        Ok(Self(trimmed.to_string()))
    }
}

fn extract_typed_header<T>(req: &Request) -> Result<T, ExtractionError>
where
    T: FromHeaderValue,
{
    let value = header_value_ci(req, T::NAME)
        .ok_or_else(|| malformed_header_rejection(T::NAME, "missing header"))?;
    T::from_header_value(value).map_err(|err| malformed_header_rejection(T::NAME, err.message()))
}

fn malformed_header_rejection(header_name: &str, reason: impl fmt::Display) -> ExtractionError {
    ExtractionError::new(
        super::response::StatusCode::BAD_REQUEST,
        format!("{MALFORMED_HEADER_CODE} malformed request header `{header_name}`: {reason}"),
    )
}

fn checked_header_value<'a>(
    header_name: &str,
    value: &'a str,
) -> Result<&'a str, HeaderParseError> {
    if value
        .as_bytes()
        .iter()
        .any(|byte| matches!(*byte, b'\r' | b'\n' | 0))
    {
        return Err(HeaderParseError::new(format!(
            "{header_name} contains a forbidden control character"
        )));
    }

    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err(HeaderParseError::new(format!(
            "{header_name} must not be empty"
        )));
    }
    Ok(trimmed)
}

fn validate_media_range(media_range: &str, allow_wildcards: bool) -> Result<(), HeaderParseError> {
    let Some((ty, subtype)) = media_range.split_once('/') else {
        return Err(HeaderParseError::new(
            "media range must contain type and subtype",
        ));
    };
    let ty = ty.trim();
    let subtype = subtype.trim();

    let type_ok =
        (ty == "*" && allow_wildcards) || (!ty.is_empty() && ty.bytes().all(is_http_token_char));
    let subtype_ok = subtype == "*" && allow_wildcards
        || !subtype.is_empty() && subtype.bytes().all(is_http_token_char);
    if !type_ok || !subtype_ok {
        return Err(HeaderParseError::new(
            "media range type and subtype must be HTTP tokens",
        ));
    }
    Ok(())
}

fn is_http_token_char(byte: u8) -> bool {
    matches!(
        byte,
        b'0'..=b'9'
            | b'a'..=b'z'
            | b'A'..=b'Z'
            | b'!'
            | b'#'
            | b'$'
            | b'%'
            | b'&'
            | b'\''
            | b'*'
            | b'+'
            | b'-'
            | b'.'
            | b'^'
            | b'_'
            | b'`'
            | b'|'
            | b'~'
    )
}

// ─── Cookie / CookieJar ─────────────────────────────────────────────────────

/// Extract the raw `Cookie` request header.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cookie(pub String);

impl FromRequestParts for Cookie {
    fn from_request_parts(req: &Request) -> Result<Self, ExtractionError> {
        header_value_ci(req, "cookie")
            .map(|value| Self(value.to_string()))
            .ok_or_else(|| ExtractionError::bad_request("missing Cookie header"))
    }
}

/// Parsed request cookies.
///
/// `CookieJar` is extracted from the `Cookie` header and provides convenient
/// accessors for cookie lookup.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CookieJar {
    cookies: HashMap<String, String>,
}

impl CookieJar {
    /// Returns the cookie value for `name`, if present.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&str> {
        self.cookies.get(name).map(String::as_str)
    }

    /// Returns true when a cookie with `name` exists.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        self.cookies.contains_key(name)
    }

    /// Returns the number of cookies in the jar.
    #[must_use]
    pub fn len(&self) -> usize {
        self.cookies.len()
    }

    /// Returns true when no cookies are present.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.cookies.is_empty()
    }

    /// Iterates over cookie key/value pairs.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> + '_ {
        self.cookies
            .iter()
            .map(|(name, value)| (name.as_str(), value.as_str()))
    }
}

impl FromRequestParts for CookieJar {
    fn from_request_parts(req: &Request) -> Result<Self, ExtractionError> {
        let cookies = header_value_ci(req, "cookie")
            .map(parse_cookie_header)
            .unwrap_or_default();
        Ok(Self { cookies })
    }
}

pub(super) fn header_value_ci<'a>(req: &'a Request, header_name: &str) -> Option<&'a str> {
    req.headers
        .iter()
        .find(|(name, _)| name.eq_ignore_ascii_case(header_name))
        .map(|(_, value)| value.as_str())
}

fn matches_content_type_media_type(content_type: &str, expected: &str) -> bool {
    content_type
        .split(';')
        .next()
        .is_some_and(|media_type| media_type.trim().eq_ignore_ascii_case(expected))
}

fn matches_json_content_type(content_type: &str) -> bool {
    let Some(media_type) = content_type.split(';').next() else {
        return false;
    };
    let Some((ty, subtype)) = media_type.trim().split_once('/') else {
        return false;
    };
    if !ty.trim().eq_ignore_ascii_case("application") {
        return false;
    }

    let subtype = subtype.trim();
    subtype.eq_ignore_ascii_case("json")
        || subtype.rsplit_once('+').is_some_and(|(prefix, suffix)| {
            !prefix.trim().is_empty() && suffix.eq_ignore_ascii_case("json")
        })
}

#[allow(clippy::implicit_hasher)]
fn parse_cookie_header(raw: &str) -> HashMap<String, String> {
    let mut parsed = HashMap::new();
    for segment in raw.split(';') {
        let trimmed = segment.trim();
        if trimmed.is_empty() {
            continue;
        }
        let Some((name, value)) = trimmed.split_once('=') else {
            continue;
        };
        let name = name.trim();
        if name.is_empty() {
            continue;
        }
        let value = value.trim().trim_matches('"').to_string();
        parsed.insert(name.to_string(), value);
    }
    parsed
}

fn invalid_content_length() -> ExtractionError {
    ExtractionError::new(
        super::response::StatusCode::BAD_REQUEST,
        "invalid Content-Length header",
    )
}

pub(super) fn parse_content_length(value: &str) -> Result<usize, ExtractionError> {
    let mut parsed = None;

    for raw_part in value.split(',') {
        let part = raw_part.trim();
        if part.is_empty() {
            return Err(invalid_content_length());
        }

        // RFC 9110 §8.6: Content-Length = 1*DIGIT. Rust's `usize` parser also
        // accepts a leading '+' (e.g. "+5" -> 5); reject any non-digit byte so
        // a fronting proxy cannot frame such a value differently than we do
        // (the classic request-smuggling / framing-desync precondition).
        if !part.bytes().all(|b| b.is_ascii_digit()) {
            return Err(invalid_content_length());
        }
        let declared = part
            .parse::<usize>()
            .map_err(|_| invalid_content_length())?;
        if let Some(previous) = parsed {
            if previous != declared {
                return Err(ExtractionError::new(
                    super::response::StatusCode::BAD_REQUEST,
                    "conflicting Content-Length header values",
                ));
            }
        } else {
            parsed = Some(declared);
        }
    }

    parsed.ok_or_else(invalid_content_length)
}

/// Validates that request body length matches Content-Length, when present.
fn validate_content_length(req: &Request) -> Result<(), ExtractionError> {
    if let Some(cl_value) = header_value_ci(req, "content-length") {
        let declared_length = parse_content_length(cl_value)?;
        let actual_length = req.body.len();
        if actual_length != declared_length {
            return Err(ExtractionError::new(
                super::response::StatusCode::BAD_REQUEST,
                format!(
                    "Content-Length mismatch: declared {} bytes, received {} bytes",
                    declared_length, actual_length
                ),
            ));
        }
    }
    Ok(())
}

/// Check Content-Length header against size limit before reading body.
///
/// This prevents DoS attacks where large bodies are fully buffered into memory
/// before size checking occurs. Per RFC 9110, we should return 413 Payload Too Large
/// based on Content-Length header before body processing.
fn check_content_length_limit(req: &Request, limit: usize) -> Result<(), ExtractionError> {
    if let Some(cl_value) = header_value_ci(req, "content-length") {
        let declared_length = parse_content_length(cl_value)?;
        if declared_length > limit {
            return Err(ExtractionError::new(
                super::response::StatusCode::PAYLOAD_TOO_LARGE,
                format!(
                    "Content-Length {} bytes exceeds limit {} bytes",
                    declared_length, limit
                ),
            ));
        }
    }
    Ok(())
}

// ─── BodyLimits ──────────────────────────────────────────────────────────────

/// Default maximum JSON body size (10 MiB).
const DEFAULT_MAX_JSON_BODY_SIZE: usize = 10 * 1024 * 1024;

/// Default maximum form body size (2 MiB).
const DEFAULT_MAX_FORM_BODY_SIZE: usize = 2 * 1024 * 1024;

/// Default maximum raw body size (10 MiB).
const DEFAULT_MAX_RAW_BODY_SIZE: usize = 10 * 1024 * 1024;

/// Configurable body size limits for request extractors.
///
/// Middleware can inject this into request extensions to override the default
/// limits on a per-route or per-server basis. Extractors (`Json`, `Form`,
/// `RawBody`)
/// check for this type in extensions and fall back to defaults if absent.
///
/// # Example
///
/// ```ignore
/// // Server-wide: allow 50 MiB JSON bodies
/// let limits = BodyLimits::new()
///     .max_json_body_size(50 * 1024 * 1024);
/// // Inject via middleware into request.extensions.insert_typed(limits)
/// ```
#[derive(Debug, Clone, Copy)]
pub struct BodyLimits {
    /// Maximum JSON body size in bytes.
    pub max_json_body_size: usize,
    /// Maximum form body size in bytes.
    pub max_form_body_size: usize,
    /// Maximum raw body size in bytes.
    pub max_raw_body_size: usize,
}

impl Default for BodyLimits {
    fn default() -> Self {
        Self {
            max_json_body_size: DEFAULT_MAX_JSON_BODY_SIZE,
            max_form_body_size: DEFAULT_MAX_FORM_BODY_SIZE,
            max_raw_body_size: DEFAULT_MAX_RAW_BODY_SIZE,
        }
    }
}

impl BodyLimits {
    /// Create body limits with defaults (10 MiB JSON, 2 MiB form, 10 MiB raw).
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the maximum JSON body size.
    #[must_use]
    pub fn max_json_body_size(mut self, bytes: usize) -> Self {
        self.max_json_body_size = bytes;
        self
    }

    /// Set the maximum form body size.
    #[must_use]
    pub fn max_form_body_size(mut self, bytes: usize) -> Self {
        self.max_form_body_size = bytes;
        self
    }

    /// Set the maximum raw body size.
    #[must_use]
    pub fn max_raw_body_size(mut self, bytes: usize) -> Self {
        self.max_raw_body_size = bytes;
        self
    }
}

// ─── Json<T> ─────────────────────────────────────────────────────────────────

/// Extract JSON request body.
///
/// Deserializes the request body as JSON.
///
/// The body size limit defaults to 10 MiB but can be overridden by injecting
/// [`BodyLimits`] into the request extensions via middleware.
///
/// ```ignore
/// async fn create_user(Json(user): Json<CreateUser>) -> StatusCode {
///     // ...
///     StatusCode::CREATED
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Json<T>(pub T);

impl<T: serde::de::DeserializeOwned> FromRequest for Json<T> {
    fn from_request(req: Request) -> Result<Self, ExtractionError> {
        let limit = req
            .extensions
            .get_typed::<BodyLimits>()
            .map_or(DEFAULT_MAX_JSON_BODY_SIZE, |l| l.max_json_body_size);

        // SECURITY: Check Content-Length header BEFORE reading body to prevent DoS
        check_content_length_limit(&req, limit)?;

        if req.body.len() > limit {
            return Err(ExtractionError::new(
                super::response::StatusCode::PAYLOAD_TOO_LARGE,
                format!(
                    "JSON body too large: {} bytes (limit {})",
                    req.body.len(),
                    limit
                ),
            ));
        }

        // Reject invalid or mismatched framing metadata before parsing body bytes.
        validate_content_length(&req)?;

        let Some(ct) = header_value_ci(&req, "content-type") else {
            return Err(ExtractionError::new(
                super::response::StatusCode::UNSUPPORTED_MEDIA_TYPE,
                "Json requires Content-Type: application/json",
            ));
        };
        if !matches_json_content_type(ct) {
            return Err(ExtractionError::new(
                super::response::StatusCode::UNSUPPORTED_MEDIA_TYPE,
                format!("expected application/json, got {ct}"),
            ));
        }

        // br-asupersync-y4mc96: keep serde error in server-side log only;
        // return a generic message to the client so byte offsets, expected
        // type names, and partial-parse context don't reach an attacker.
        // The detailed `e` is recorded via tracing for operator forensics.
        serde_json::from_slice(req.body.as_ref())
            .map(Json)
            .map_err(|_err| {
                crate::tracing_compat::warn!(
                    error = %_err,
                    "web/extract: Json deserialization failed"
                );
                ExtractionError::unprocessable("invalid JSON body")
            })
    }
}

// ─── Form<T> ─────────────────────────────────────────────────────────────────

/// Extract URL-encoded form data from the request body.
///
/// ```ignore
/// #[derive(Deserialize)]
/// struct Login { username: String, password: String }
///
/// async fn login(Form(data): Form<Login>) -> Redirect {
///     // ...
///     Redirect::to("/dashboard")
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Form<T>(pub T);

#[allow(clippy::implicit_hasher)]
impl<T: DeserializeOwned> FromRequest for Form<T> {
    fn from_request(req: Request) -> Result<Self, ExtractionError> {
        let limit = req
            .extensions
            .get_typed::<BodyLimits>()
            .map_or(DEFAULT_MAX_FORM_BODY_SIZE, |l| l.max_form_body_size);

        // SECURITY: Check Content-Length header BEFORE reading body to prevent DoS
        check_content_length_limit(&req, limit)?;

        if req.body.len() > limit {
            return Err(ExtractionError::new(
                super::response::StatusCode::PAYLOAD_TOO_LARGE,
                format!(
                    "form body too large: {} bytes (limit {})",
                    req.body.len(),
                    limit
                ),
            ));
        }

        // Reject invalid or mismatched framing metadata before parsing body bytes.
        validate_content_length(&req)?;

        // br-asupersync-mxqraw: Content-Type MUST be present AND must be
        // application/x-www-form-urlencoded. Previously we accepted any
        // body when Content-Type was absent, parsing arbitrary payloads
        // (JSON, XML, raw bytes) as form-encoded — so an attacker could
        // forge a Form<T> deserialisation by sending a JSON body without
        // a Content-Type header. Default-deny: missing header is a 415.
        let Some(ct) = header_value_ci(&req, "content-type") else {
            return Err(ExtractionError::new(
                super::response::StatusCode::UNSUPPORTED_MEDIA_TYPE,
                "Form requires Content-Type: application/x-www-form-urlencoded",
            ));
        };
        if !matches_content_type_media_type(ct, "application/x-www-form-urlencoded") {
            return Err(ExtractionError::new(
                super::response::StatusCode::UNSUPPORTED_MEDIA_TYPE,
                format!("expected application/x-www-form-urlencoded, got {ct}"),
            ));
        }

        let body_str = std::str::from_utf8(req.body.as_ref())
            .map_err(|e| ExtractionError::bad_request(format!("invalid UTF-8 body: {e}")))?;

        let parsed = parse_urlencoded_multi(body_str, "form field")?;

        deserialize_from_multi_value_map(&parsed, "form data").map(Self)
    }
}

// ─── State<T> ────────────────────────────────────────────────────────────────

/// Extract shared application state.
///
/// State must be injected via `Router::with_state()`. The state is stored
/// in the request extensions by the router.
///
/// ```ignore
/// #[derive(Clone)]
/// struct AppState { db: DbPool }
///
/// async fn handler(State(state): State<AppState>) -> String {
///     // use state.db
///     "ok".into()
/// }
///
/// let app = Router::new()
///     .route("/", get(handler))
///     .with_state(AppState { db });
/// ```
#[derive(Debug, Clone)]
pub struct State<T>(pub T);

impl<T> FromRequestParts for State<T>
where
    T: Clone + Send + Sync + 'static,
{
    fn from_request_parts(req: &Request) -> Result<Self, ExtractionError> {
        req.extensions
            .get_typed_cloned::<T>()
            .map(Self)
            .ok_or_else(|| {
                ExtractionError::new(
                    super::response::StatusCode::INTERNAL_SERVER_ERROR,
                    format!("state not configured for {}", std::any::type_name::<T>()),
                )
            })
    }
}

// ─── Extension<T> ────────────────────────────────────────────────────────────

/// Extract a typed value injected by middleware.
///
/// Middleware inserts values into the request's [`Extensions`] store with
/// [`Extensions::insert_typed`]; handlers extract them with `Extension<T>`.
/// The value lives on the [`Request`] itself, so it is request-scoped: each
/// request carries its own extensions map, with no bleed between requests,
/// and the map is dropped with the request when handling completes (inside
/// the request region when the server dispatches through one).
///
/// Difference from [`State<T>`]: `State` carries application-lifetime shared
/// state injected once via `Router::with_state`; `Extension` carries
/// per-request values injected by middleware (auth principals, request
/// metadata, trace context, ...). Both read the same typed store.
///
/// Missing extensions are a server-side wiring bug, so extraction failure
/// maps to `500 Internal Server Error` (matching [`State<T>`]).
///
/// ```
/// use asupersync::web::extract::{Extension, FromRequestParts, Request};
///
/// #[derive(Clone, Debug, PartialEq)]
/// struct CurrentUser {
///     id: u64,
/// }
///
/// // Middleware inserts:
/// let mut req = Request::new("GET", "/me");
/// req.extensions.insert_typed(CurrentUser { id: 42 });
///
/// // Handler extracts:
/// let Extension(user) =
///     Extension::<CurrentUser>::from_request_parts(&req).expect("extension present");
/// assert_eq!(user, CurrentUser { id: 42 });
/// ```
#[derive(Debug, Clone)]
pub struct Extension<T>(pub T);

impl<T> FromRequestParts for Extension<T>
where
    T: Clone + Send + Sync + 'static,
{
    fn from_request_parts(req: &Request) -> Result<Self, ExtractionError> {
        req.extensions
            .get_typed_cloned::<T>()
            .map(Self)
            .ok_or_else(|| {
                ExtractionError::new(
                    super::response::StatusCode::INTERNAL_SERVER_ERROR,
                    format!("missing request extension {}", std::any::type_name::<T>()),
                )
            })
    }
}

// ─── RawBody ─────────────────────────────────────────────────────────────────

/// Extract the raw request body as bytes.
#[derive(Debug, Clone)]
pub struct RawBody(pub Bytes);

impl FromRequest for RawBody {
    fn from_request(req: Request) -> Result<Self, ExtractionError> {
        let limit = req
            .extensions
            .get_typed::<BodyLimits>()
            .map_or(DEFAULT_MAX_RAW_BODY_SIZE, |l| l.max_raw_body_size);

        // SECURITY: Check Content-Length header BEFORE reading body to prevent DoS
        check_content_length_limit(&req, limit)?;

        if req.body.len() > limit {
            return Err(ExtractionError::new(
                super::response::StatusCode::PAYLOAD_TOO_LARGE,
                format!(
                    "raw body too large: {} bytes (limit {})",
                    req.body.len(),
                    limit
                ),
            ));
        }

        // Reject invalid or mismatched framing metadata before exposing body bytes.
        validate_content_length(&req)?;

        Ok(Self(req.body))
    }
}

// ─── HeaderMap Extractor ─────────────────────────────────────────────────────

#[allow(clippy::implicit_hasher)]
impl FromRequestParts for HashMap<String, String> {
    fn from_request_parts(req: &Request) -> Result<Self, ExtractionError> {
        Ok(req.headers.clone())
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;

    #[test]
    fn path_extraction() {
        let mut params = HashMap::new();
        params.insert("id".to_string(), "42".to_string());
        let req = Request::new("GET", "/users/42").with_path_params(params);

        let Path(id) = Path::<String>::from_request_parts(&req).unwrap();
        assert_eq!(id, "42");
    }

    #[test]
    fn query_extraction() {
        let req = Request::new("GET", "/items").with_query("page=3&sort=name");
        let Query(params) = Query::<HashMap<String, String>>::from_request_parts(&req).unwrap();
        assert_eq!(params.get("page").unwrap(), "3");
        assert_eq!(params.get("sort").unwrap(), "name");
    }

    #[test]
    fn path_typed_numeric_extraction() {
        let mut params = HashMap::new();
        params.insert("id".to_string(), "42".to_string());
        let req = Request::new("GET", "/users/42").with_path_params(params);

        let Path(id) = Path::<u64>::from_request_parts(&req).unwrap();
        assert_eq!(id, 42);
    }

    #[test]
    fn path_typed_struct_extraction() {
        #[derive(Debug, serde::Deserialize, PartialEq, Eq)]
        struct Params {
            user_id: u64,
            post_id: u32,
        }

        let mut params = HashMap::new();
        params.insert("user_id".to_string(), "7".to_string());
        params.insert("post_id".to_string(), "11".to_string());
        let req = Request::new("GET", "/users/7/posts/11").with_path_params(params);

        let Path(extracted) = Path::<Params>::from_request_parts(&req).unwrap();
        assert_eq!(
            extracted,
            Params {
                user_id: 7,
                post_id: 11
            }
        );
    }

    #[test]
    fn path_typed_deserialization_error() {
        let mut params = HashMap::new();
        params.insert("id".to_string(), "not-a-number".to_string());
        let req = Request::new("GET", "/users/not-a-number").with_path_params(params);

        let err = Path::<u64>::from_request_parts(&req).unwrap_err();
        assert_eq!(err.status, crate::web::response::StatusCode::BAD_REQUEST);
        assert!(err.message.contains("invalid path parameters"));
    }

    #[test]
    fn content_length_parser_accepts_single_and_identical_combined_values() {
        assert_eq!(parse_content_length("42").unwrap(), 42);
        assert_eq!(parse_content_length("42, 42").unwrap(), 42);
        assert_eq!(parse_content_length("0042, 42").unwrap(), 42);
    }

    #[test]
    fn content_length_parser_rejects_invalid_or_conflicting_values() {
        // "+5"/"+42": Rust's usize parser accepts a leading '+', but RFC 9110
        // §8.6 forbids it — a fronting proxy may frame it differently
        // (smuggling/desync), so it must be rejected.
        for value in [
            "",
            "5, ",
            "5, 6",
            "not-a-number",
            "-1",
            "+5",
            "+42",
            "5, +5",
            "0x10",
            "1 2",
        ] {
            let err = parse_content_length(value).unwrap_err();
            assert_eq!(err.status, crate::web::response::StatusCode::BAD_REQUEST);
        }
    }

    #[test]
    fn json_extraction() {
        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct Input {
            name: String,
        }

        let req = Request::new("POST", "/users")
            .with_header("content-type", "application/json")
            .with_body(Bytes::from_static(b"{\"name\":\"alice\"}"));

        let Json(input) = Json::<Input>::from_request(req).unwrap();
        assert_eq!(input.name, "alice");
    }

    #[test]
    fn json_wrong_content_type() {
        #[derive(Debug, serde::Deserialize)]
        struct Input {
            #[allow(dead_code)]
            name: String,
        }

        let req = Request::new("POST", "/users")
            .with_header("content-type", "text/plain")
            .with_body(Bytes::from_static(b"{\"name\":\"alice\"}"));

        let result = Json::<Input>::from_request(req);
        assert!(result.is_err());
    }

    #[test]
    fn form_extraction() {
        let req = Request::new("POST", "/login")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_body(Bytes::from_static(b"user=alice&pass=secret"));

        let Form(data) = Form::<HashMap<String, String>>::from_request(req).unwrap();
        assert_eq!(data.get("user").unwrap(), "alice");
        assert_eq!(data.get("pass").unwrap(), "secret");
    }

    #[test]
    fn raw_body_extraction() {
        let req = Request::new("POST", "/upload").with_body(Bytes::from_static(b"raw data"));

        let RawBody(body) = RawBody::from_request(req).unwrap();
        assert_eq!(body.as_ref(), b"raw data");
    }

    #[test]
    fn headers_extraction() {
        let req = Request::new("GET", "/").with_header("x-request-id", "abc123");

        let headers = HashMap::<String, String>::from_request_parts(&req).unwrap();
        assert_eq!(headers.get("x-request-id").unwrap(), "abc123");
    }

    #[test]
    fn request_header_lookup_is_case_insensitive() {
        let mut req = Request::new("GET", "/").with_header("X-Trace-Id", "trace-123");
        req.headers
            .insert("Authorization".to_string(), "Bearer token".to_string());

        assert_eq!(req.header("x-trace-id"), Some("trace-123"));
        assert_eq!(req.header("X-TRACE-ID"), Some("trace-123"));
        assert_eq!(req.header("authorization"), Some("Bearer token"));
        assert_eq!(req.header("AUTHORIZATION"), Some("Bearer token"));
        assert_eq!(req.header("missing"), None);
    }

    #[test]
    fn typed_header_content_type_extracts_case_insensitively() {
        let req = Request::new("POST", "/items")
            .with_header("Content-Type", "application/json; charset=utf-8");

        let Header(content_type) = Header::<ContentType>::from_request_parts(&req).unwrap();
        assert_eq!(content_type.as_str(), "application/json; charset=utf-8");
        assert_eq!(content_type.media_type(), "application/json");
    }

    #[test]
    fn typed_header_alias_extracts_authorization() {
        let req = Request::new("GET", "/admin").with_header("Authorization", "Bearer token-123");

        let TypedHeader(auth) = TypedHeader::<Authorization>::from_request_parts(&req).unwrap();
        assert_eq!(auth.scheme, "Bearer");
        assert_eq!(auth.credentials, "token-123");
        assert_eq!(auth.as_str(), "Bearer token-123");
    }

    #[test]
    fn shipped_typed_headers_cover_user_agent_and_accept() {
        let req = Request::new("GET", "/")
            .with_header("User-Agent", "asupersync-test/1")
            .with_header("Accept", "application/json, text/plain;q=0.8, */*;q=0.1");

        let Header(user_agent) = Header::<UserAgent>::from_request_parts(&req).unwrap();
        let Header(accept) = Header::<Accept>::from_request_parts(&req).unwrap();
        assert_eq!(user_agent.as_str(), "asupersync-test/1");
        assert_eq!(
            accept.as_str(),
            "application/json, text/plain;q=0.8, */*;q=0.1"
        );
    }

    #[test]
    fn missing_typed_header_rejects_with_asup_code() {
        let req = Request::new("GET", "/");

        let err = Header::<ContentType>::from_request_parts(&req).unwrap_err();
        assert_eq!(err.status, crate::web::response::StatusCode::BAD_REQUEST);
        assert!(err.message.starts_with("[ASUP-E503]"));
        assert!(err.message.contains("content-type"));
        assert!(err.message.contains("missing header"));
    }

    #[test]
    fn malformed_typed_header_rejects_with_asup_code() {
        let bad_content_type =
            Request::new("POST", "/items").with_header("content-type", "application");
        let err = Header::<ContentType>::from_request_parts(&bad_content_type).unwrap_err();
        assert_eq!(err.status, crate::web::response::StatusCode::BAD_REQUEST);
        assert!(err.message.starts_with("[ASUP-E503]"));
        assert!(err.message.contains("media range"));

        let bad_authorization =
            Request::new("GET", "/admin").with_header("authorization", "Bearer   ");
        let err = TypedHeader::<Authorization>::from_request_parts(&bad_authorization).unwrap_err();
        assert_eq!(err.status, crate::web::response::StatusCode::BAD_REQUEST);
        assert!(err.message.starts_with("[ASUP-E503]"));
        assert!(err.message.contains("credentials"));
    }

    #[test]
    fn missing_path_params() {
        let req = Request::new("GET", "/");
        let result = Path::<String>::from_request_parts(&req);
        assert!(result.is_err());
    }

    #[test]
    fn percent_decode_preserves_invalid_sequences() {
        assert_eq!(percent_decode("a%2"), "a%2");
        assert_eq!(percent_decode("x%G1"), "x%G1");
        assert_eq!(percent_decode("x%1G"), "x%1G");
        assert_eq!(percent_decode("%"), "%");
        assert_eq!(percent_decode("%A"), "%A");
        assert_eq!(percent_decode("%%41"), "%A"); // first % invalid, then valid %41
    }

    #[test]
    fn request_debug_clone() {
        let r = Request::new("GET", "/api/v1");
        let dbg = format!("{r:?}");
        assert!(dbg.contains("Request"));
        assert!(dbg.contains("GET"));

        let r2 = r;
        assert_eq!(r2.method, "GET");
        assert_eq!(r2.path, "/api/v1");
    }

    #[test]
    fn extensions_debug_clone_default() {
        let e = Extensions::default();
        let dbg = format!("{e:?}");
        assert!(dbg.contains("Extensions"));

        let e2 = e;
        assert!(e2.get("missing").is_none());
    }

    #[test]
    fn extraction_error_debug_clone() {
        let e = ExtractionError::bad_request("missing field");
        let dbg = format!("{e:?}");
        assert!(dbg.contains("ExtractionError"));
        assert!(dbg.contains("missing field"));

        let e2 = e;
        assert_eq!(e2.message, "missing field");
    }

    #[test]
    fn typed_state_extraction() {
        #[derive(Clone, Debug, PartialEq, Eq)]
        struct AppState {
            name: String,
        }

        let mut req = Request::new("GET", "/");
        req.extensions.insert_typed(AppState {
            name: "alpha".to_string(),
        });

        let State(state) = State::<AppState>::from_request_parts(&req).unwrap();
        assert_eq!(
            state,
            AppState {
                name: "alpha".to_string()
            }
        );
    }

    #[test]
    fn typed_state_missing_returns_error() {
        #[derive(Clone, Debug)]
        struct AppState;

        let req = Request::new("GET", "/");
        let err = State::<AppState>::from_request_parts(&req).unwrap_err();
        assert_eq!(
            err.status,
            crate::web::response::StatusCode::INTERNAL_SERVER_ERROR
        );
        assert!(err.message.contains("state not configured"));
    }

    #[test]
    fn form_body_too_large() {
        let oversized = vec![b'a'; DEFAULT_MAX_FORM_BODY_SIZE + 1];
        let req = Request::new("POST", "/form").with_body(Bytes::from(oversized));
        let result = Form::<HashMap<String, String>>::from_request(req);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(
            err.status,
            crate::web::response::StatusCode::PAYLOAD_TOO_LARGE
        );
    }

    #[test]
    fn json_body_too_large() {
        let oversized = vec![b'a'; DEFAULT_MAX_JSON_BODY_SIZE + 1];
        let req = Request::new("POST", "/data")
            .with_header("content-type", "application/json")
            .with_body(Bytes::from(oversized));
        let result = Json::<serde_json::Value>::from_request(req);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(
            err.status,
            crate::web::response::StatusCode::PAYLOAD_TOO_LARGE
        );
    }

    #[test]
    fn json_content_type_header_name_case_insensitive() {
        let req = Request::new("POST", "/data")
            .with_header("Content-Type", "application/json")
            .with_body(Bytes::from_static(br#"{"ok":true}"#));
        let Json(value) = Json::<serde_json::Value>::from_request(req).unwrap();
        assert_eq!(value.get("ok"), Some(&serde_json::Value::Bool(true)));
    }

    #[test]
    fn json_content_type_allows_parameters_but_rejects_substring_tricks() {
        let with_charset = Request::new("POST", "/data")
            .with_header("content-type", "application/json; charset=utf-8")
            .with_body(Bytes::from_static(br#"{"ok":true}"#));
        let Json(value) = Json::<serde_json::Value>::from_request(with_charset).unwrap();
        assert_eq!(value.get("ok"), Some(&serde_json::Value::Bool(true)));

        let structured_suffix = Request::new("POST", "/data")
            .with_header("content-type", "application/cloudevents+json")
            .with_body(Bytes::from_static(br#"{"ok":true}"#));
        let Json(value) = Json::<serde_json::Value>::from_request(structured_suffix).unwrap();
        assert_eq!(value.get("ok"), Some(&serde_json::Value::Bool(true)));

        let misleading = Request::new("POST", "/data")
            .with_header("content-type", "text/plain; note=application/json")
            .with_body(Bytes::from_static(br#"{"ok":true}"#));
        let err = Json::<serde_json::Value>::from_request(misleading).unwrap_err();
        assert_eq!(
            err.status,
            crate::web::response::StatusCode::UNSUPPORTED_MEDIA_TYPE
        );

        let wrong_top_level = Request::new("POST", "/data")
            .with_header("content-type", "text/cloudevents+json")
            .with_body(Bytes::from_static(br#"{"ok":true}"#));
        let err = Json::<serde_json::Value>::from_request(wrong_top_level).unwrap_err();
        assert_eq!(
            err.status,
            crate::web::response::StatusCode::UNSUPPORTED_MEDIA_TYPE
        );

        let empty_structured_prefix = Request::new("POST", "/data")
            .with_header("content-type", "application/+json")
            .with_body(Bytes::from_static(br#"{"ok":true}"#));
        let err = Json::<serde_json::Value>::from_request(empty_structured_prefix).unwrap_err();
        assert_eq!(
            err.status,
            crate::web::response::StatusCode::UNSUPPORTED_MEDIA_TYPE
        );
    }

    #[test]
    fn json_missing_content_type_rejects_with_415() {
        let req = Request::new("POST", "/data").with_body(Bytes::from_static(br#"{"ok":true}"#));
        let err = Json::<serde_json::Value>::from_request(req).unwrap_err();
        assert_eq!(
            err.status,
            crate::web::response::StatusCode::UNSUPPORTED_MEDIA_TYPE
        );
        assert_eq!(err.message, "Json requires Content-Type: application/json");
    }

    #[test]
    fn json_top_level_scalar_matches_rfc7159() {
        let req = Request::new("POST", "/data")
            .with_header("content-type", "application/json")
            .with_body(Bytes::from_static(b"123"));
        let Json(value) = Json::<serde_json::Value>::from_request(req).unwrap();
        assert_eq!(value, serde_json::Value::Number(123.into()));
    }

    #[test]
    fn json_surrounded_by_rfc8259_whitespace_parses() {
        let req = Request::new("POST", "/data")
            .with_header("content-type", "application/json")
            .with_body(Bytes::from_static(b"\r\n\t {\"ok\":true} \n"));
        let Json(value) = Json::<serde_json::Value>::from_request(req).unwrap();
        assert_eq!(value.get("ok"), Some(&serde_json::Value::Bool(true)));
    }

    #[test]
    fn metamorphic_body_extractors_preserve_body_semantics_and_limits() {
        let json_body = Bytes::from_static(br#"{"user":"alice","admin":true}"#);
        let json_req = Request::new("POST", "/json")
            .with_header("content-type", "application/json")
            .with_body(json_body.clone());
        let RawBody(raw_json) = RawBody::from_request(json_req.clone()).unwrap();
        assert_eq!(raw_json.as_ref(), json_body.as_ref());
        let Json(parsed_json) = Json::<serde_json::Value>::from_request(json_req).unwrap();
        assert_eq!(
            parsed_json,
            serde_json::from_slice::<serde_json::Value>(raw_json.as_ref()).unwrap()
        );

        let form_body = Bytes::from_static(b"user=alice&admin=boss");
        let form_req = Request::new("POST", "/form")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_body(form_body.clone());
        let RawBody(raw_form) = RawBody::from_request(form_req.clone()).unwrap();
        assert_eq!(raw_form.as_ref(), form_body.as_ref());
        let Form(parsed_form) = Form::<HashMap<String, String>>::from_request(form_req).unwrap();
        assert_eq!(
            parsed_form,
            parse_urlencoded(
                std::str::from_utf8(raw_form.as_ref()).unwrap(),
                "form field"
            )
            .unwrap()
        );

        let limit = 8;
        let limits = BodyLimits::new()
            .max_json_body_size(limit)
            .max_form_body_size(limit)
            .max_raw_body_size(limit);

        let mut oversized_json_req = Request::new("POST", "/json")
            .with_header("content-type", "application/json")
            .with_body(Bytes::from_static(br#"{"k":"123456789"}"#));
        oversized_json_req.extensions.insert_typed(limits);
        let json_err = Json::<serde_json::Value>::from_request(oversized_json_req).unwrap_err();
        assert_eq!(
            json_err.status,
            crate::web::response::StatusCode::PAYLOAD_TOO_LARGE
        );

        let mut oversized_form_req = Request::new("POST", "/form")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_body(Bytes::from_static(b"k=123456789"));
        oversized_form_req.extensions.insert_typed(limits);
        let form_err =
            Form::<HashMap<String, String>>::from_request(oversized_form_req).unwrap_err();
        assert_eq!(
            form_err.status,
            crate::web::response::StatusCode::PAYLOAD_TOO_LARGE
        );

        let mut oversized_raw_req =
            Request::new("POST", "/raw").with_body(Bytes::from_static(b"123456789"));
        oversized_raw_req.extensions.insert_typed(limits);
        let raw_err = RawBody::from_request(oversized_raw_req).unwrap_err();
        assert_eq!(
            raw_err.status,
            crate::web::response::StatusCode::PAYLOAD_TOO_LARGE
        );
    }

    #[test]
    fn form_wrong_content_type() {
        let req = Request::new("POST", "/form")
            .with_header("content-type", "text/plain")
            .with_body(Bytes::from_static(b"user=alice"));
        let result = Form::<HashMap<String, String>>::from_request(req);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(
            err.status,
            crate::web::response::StatusCode::UNSUPPORTED_MEDIA_TYPE
        );
    }

    #[test]
    fn form_content_type_header_name_case_insensitive() {
        let req = Request::new("POST", "/form")
            .with_header("Content-Type", "application/x-www-form-urlencoded")
            .with_body(Bytes::from_static(b"user=alice&role=admin"));
        let Form(values) = Form::<HashMap<String, String>>::from_request(req).unwrap();
        assert_eq!(values.get("user").map(String::as_str), Some("alice"));
        assert_eq!(values.get("role").map(String::as_str), Some("admin"));
    }

    #[test]
    fn form_content_type_allows_parameters_but_rejects_substring_tricks() {
        let with_charset = Request::new("POST", "/form")
            .with_header(
                "content-type",
                "application/x-www-form-urlencoded; charset=utf-8",
            )
            .with_body(Bytes::from_static(b"user=alice&role=admin"));
        let Form(values) = Form::<HashMap<String, String>>::from_request(with_charset).unwrap();
        assert_eq!(values.get("user").map(String::as_str), Some("alice"));
        assert_eq!(values.get("role").map(String::as_str), Some("admin"));

        let misleading = Request::new("POST", "/form")
            .with_header(
                "content-type",
                "application/x-www-form-urlencoded-bogus; charset=utf-8",
            )
            .with_body(Bytes::from_static(b"user=alice"));
        let err = Form::<HashMap<String, String>>::from_request(misleading).unwrap_err();
        assert_eq!(
            err.status,
            crate::web::response::StatusCode::UNSUPPORTED_MEDIA_TYPE
        );
    }

    #[test]
    fn form_missing_content_type_rejects_with_415() {
        // br-asupersync-mxqraw: Form requires Content-Type:
        // application/x-www-form-urlencoded. Missing Content-Type is a
        // 415 — default-deny prevents an attacker from forging Form<T>
        // deserialisation by submitting a foreign-format body (JSON, XML,
        // raw bytes) without declaring its media type.
        let req = Request::new("POST", "/form").with_body(Bytes::from_static(b"user=alice"));
        let err = Form::<HashMap<String, String>>::from_request(req).unwrap_err();
        assert_eq!(
            err.status,
            crate::web::response::StatusCode::UNSUPPORTED_MEDIA_TYPE
        );
    }

    #[test]
    fn form_invalid_utf8() {
        let req = Request::new("POST", "/form")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_body(Bytes::from_static(b"\xff\xfe"));
        let result = Form::<HashMap<String, String>>::from_request(req);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.status, crate::web::response::StatusCode::BAD_REQUEST);
    }

    #[test]
    fn form_duplicate_keys_preserved_as_vec() {
        use serde::Deserialize;

        #[derive(Deserialize, Debug, PartialEq)]
        struct MultiForm {
            role: Vec<String>,
            name: String,
        }

        let req = Request::new("POST", "/form")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_body(Bytes::from_static(b"role=user&role=admin&name=alice"));

        let Form(data) = Form::<MultiForm>::from_request(req).unwrap();
        assert_eq!(data.role, vec!["user", "admin"]);
        assert_eq!(data.name, "alice");
    }

    #[test]
    fn form_duplicate_keys_html_spec_compliance_audit() {
        println!("=== FORM DUPLICATE KEYS HTML SPEC COMPLIANCE AUDIT ===");

        use serde::Deserialize;

        // Test Case 1: Multiple values for same key should be preserved as Vec
        #[derive(Deserialize, Debug, PartialEq)]
        struct TestForm {
            tags: Vec<String>,
            category: String,
            flags: Option<Vec<String>>,
        }

        println!("✓ Test Case 1: Multiple values preserved as Vec<String>");

        let req1 = Request::new("POST", "/form")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_body(Bytes::from_static(
                b"tags=red&tags=blue&tags=green&category=test",
            ));

        let Form(data1) = Form::<TestForm>::from_request(req1).unwrap();
        assert_eq!(data1.tags, vec!["red", "blue", "green"]);
        assert_eq!(data1.category, "test");
        assert_eq!(data1.flags, None);

        println!("  ✅ tags=red&tags=blue&tags=green → Vec![\"red\", \"blue\", \"green\"]");

        // Test Case 2: Single values should work normally
        println!("✓ Test Case 2: Single values work normally");

        let req2 = Request::new("POST", "/form")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_body(Bytes::from_static(b"tags=solo&category=single"));

        let Form(data2) = Form::<TestForm>::from_request(req2).unwrap();
        assert_eq!(data2.tags, vec!["solo"]);
        assert_eq!(data2.category, "single");

        println!("  ✅ tags=solo → Vec![\"solo\"] (single item as Vec)");

        // Test Case 3: Mixed single and multiple values
        println!("✓ Test Case 3: Mixed single and multiple values");

        let req3 = Request::new("POST", "/form")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_body(Bytes::from_static(
                b"tags=first&category=mixed&tags=second&flags=a&flags=b",
            ));

        let Form(data3) = Form::<TestForm>::from_request(req3).unwrap();
        assert_eq!(data3.tags, vec!["first", "second"]);
        assert_eq!(data3.category, "mixed");
        assert_eq!(data3.flags, Some(vec!["a".to_string(), "b".to_string()]));

        println!("  ✅ Mixed form: single category + multiple tags + multiple flags");

        // Test Case 4: HTML checkbox scenario (common use case)
        #[derive(Deserialize, Debug)]
        struct CheckboxForm {
            #[serde(default)]
            permissions: Vec<String>,
            username: String,
        }

        println!("✓ Test Case 4: HTML checkbox scenario");

        let req4 = Request::new("POST", "/form")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_body(Bytes::from_static(
                b"permissions=read&permissions=write&permissions=delete&username=admin",
            ));

        let Form(data4) = Form::<CheckboxForm>::from_request(req4).unwrap();
        assert_eq!(data4.permissions, vec!["read", "write", "delete"]);
        assert_eq!(data4.username, "admin");

        println!("  ✅ Checkbox form: permissions=[read, write, delete]");

        // Test Case 5: Type coercion with duplicates
        #[derive(Deserialize, Debug)]
        struct TypedForm {
            numbers: Vec<i32>,
            enabled: bool,
        }

        println!("✓ Test Case 5: Type coercion with duplicates");

        let req5 = Request::new("POST", "/form")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_body(Bytes::from_static(
                b"numbers=42&numbers=123&numbers=999&enabled=true",
            ));

        let Form(data5) = Form::<TypedForm>::from_request(req5).unwrap();
        assert_eq!(data5.numbers, vec![42, 123, 999]);
        assert_eq!(data5.enabled, true);

        println!("  ✅ Type coercion: string numbers → Vec<i32>");

        println!("\n📋 HTML FORM SPEC COMPLIANCE VERIFIED:");
        println!("  1. Duplicate keys preserved: ✅ OPTION (a) - Vec<String> (CORRECT)");
        println!("  2. Single values supported: ✅ BACKWARD COMPATIBLE");
        println!("  3. Type coercion works: ✅ STRING → NUMBER/BOOL");
        println!("  4. HTML checkboxes: ✅ MULTIPLE SELECTIONS PRESERVED");
        println!("  5. Mixed forms: ✅ SINGLE + MULTIPLE FIELDS");

        println!("\n✅ STATUS: FORM DUPLICATE KEY HANDLING IS COMPLIANT");
        println!("BEHAVIOR: Option (a) - return Vec<String> for duplicate keys (CORRECT)");
        println!("COMPLIANCE: HTML Form Specification - preserves all submitted values");
        println!("IMPACT: Applications can now handle multi-select forms correctly");
    }

    #[test]
    fn form_scalar_extraction_does_not_ignore_field_names() {
        let req = Request::new("POST", "/form")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_body(Bytes::from_static(b"flag=true"));
        let err = Form::<bool>::from_request(req).unwrap_err();
        assert_eq!(err.status, crate::web::response::StatusCode::BAD_REQUEST);
        assert!(err.message.contains("invalid form data"));
    }

    #[test]
    fn json_invalid_body() {
        let req = Request::new("POST", "/data")
            .with_header("content-type", "application/json")
            .with_body(Bytes::from_static(b"not json"));
        let result = Json::<serde_json::Value>::from_request(req);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(
            err.status,
            crate::web::response::StatusCode::UNPROCESSABLE_ENTITY
        );
    }

    #[test]
    fn query_empty_string() {
        let req = Request::new("GET", "/items");
        let Query(params) = Query::<HashMap<String, String>>::from_request_parts(&req).unwrap();
        assert!(params.is_empty());
    }

    #[test]
    fn query_percent_encoded_values() {
        let req = Request::new("GET", "/search").with_query("q=hello+world&tag=%23rust");
        let Query(params) = Query::<HashMap<String, String>>::from_request_parts(&req).unwrap();
        assert_eq!(params.get("q").unwrap(), "hello world");
        assert_eq!(params.get("tag").unwrap(), "#rust");
    }

    #[test]
    fn query_typed_struct_extraction() {
        #[derive(Debug, serde::Deserialize, PartialEq, Eq)]
        struct Pagination {
            page: u32,
            per_page: u16,
            active: bool,
        }

        let req = Request::new("GET", "/items").with_query("page=3&per_page=25&active=true");
        let Query(pagination) = Query::<Pagination>::from_request_parts(&req).unwrap();
        assert_eq!(
            pagination,
            Pagination {
                page: 3,
                per_page: 25,
                active: true
            }
        );
    }

    #[test]
    fn query_typed_scalar_extraction() {
        let req = Request::new("GET", "/items").with_query("value=17");
        let Query(value) = Query::<u32>::from_request_parts(&req).unwrap();
        assert_eq!(value, 17);
    }

    #[test]
    fn query_typed_deserialization_error() {
        let req = Request::new("GET", "/items").with_query("page=abc");
        let err = Query::<u32>::from_request_parts(&req).unwrap_err();
        assert_eq!(err.status, crate::web::response::StatusCode::BAD_REQUEST);
        assert!(err.message.contains("invalid query parameters"));
    }

    #[test]
    fn query_duplicate_keys_reject_instead_of_collapsing_to_scalar() {
        let req = Request::new("GET", "/items").with_query("value=17&value=18");
        let err = Query::<u32>::from_request_parts(&req).unwrap_err();
        assert_eq!(err.status, crate::web::response::StatusCode::BAD_REQUEST);
        assert_eq!(
            err.message,
            "duplicate query parameter `value` (use multi-value extractor for forms)"
        );
    }

    #[test]
    fn path_multiple_params() {
        let mut params = HashMap::new();
        params.insert("user_id".to_string(), "42".to_string());
        params.insert("post_id".to_string(), "7".to_string());
        let req = Request::new("GET", "/users/42/posts/7").with_path_params(params.clone());

        let Path(extracted) = Path::<HashMap<String, String>>::from_request_parts(&req).unwrap();
        assert_eq!(extracted, params);
    }

    #[test]
    fn query_string_field_accepts_numeric_looking_value() {
        // A `String` field holding a numeric/bool-looking value (all-digit
        // username, numeric id passed as text, "true"/"false" string) must be
        // kept as a string, not coerced to a JSON number/bool and rejected.
        #[derive(Debug, serde::Deserialize, PartialEq, Eq)]
        struct Mixed {
            name: String,
            flag: String,
            age: u32,
        }
        let req = Request::new("GET", "/u").with_query("name=42&flag=true&age=30");
        let Query(m) = Query::<Mixed>::from_request_parts(&req).unwrap();
        assert_eq!(
            m,
            Mixed {
                name: "42".to_string(),
                flag: "true".to_string(),
                age: 30,
            }
        );
    }

    #[test]
    fn path_string_field_accepts_numeric_looking_value() {
        #[derive(Debug, serde::Deserialize, PartialEq, Eq)]
        struct Params {
            token: String,
            id: u64,
        }
        let mut params = HashMap::new();
        params.insert("token".to_string(), "1234".to_string());
        params.insert("id".to_string(), "9".to_string());
        let req = Request::new("GET", "/x").with_path_params(params);
        let Path(p) = Path::<Params>::from_request_parts(&req).unwrap();
        assert_eq!(
            p,
            Params {
                token: "1234".to_string(),
                id: 9,
            }
        );
    }

    #[test]
    fn raw_body_empty() {
        let req = Request::new("POST", "/upload");
        let RawBody(body) = RawBody::from_request(req).unwrap();
        assert!(body.is_empty());
    }

    #[test]
    fn cookie_extraction_raw_header() {
        let req = Request::new("GET", "/").with_header("Cookie", "session=abc; theme=dark");
        let Cookie(raw) = Cookie::from_request_parts(&req).unwrap();
        assert_eq!(raw, "session=abc; theme=dark");
    }

    #[test]
    fn cookie_extraction_missing_header_is_error() {
        let req = Request::new("GET", "/");
        let err = Cookie::from_request_parts(&req).unwrap_err();
        assert_eq!(err.status, crate::web::response::StatusCode::BAD_REQUEST);
    }

    #[test]
    fn cookie_jar_parses_cookie_pairs() {
        let req = Request::new("GET", "/").with_header("cookie", "session=abc; theme=dark; id=42");
        let jar = CookieJar::from_request_parts(&req).unwrap();
        assert_eq!(jar.get("session"), Some("abc"));
        assert_eq!(jar.get("theme"), Some("dark"));
        assert_eq!(jar.get("id"), Some("42"));
        assert_eq!(jar.len(), 3);
    }

    #[test]
    fn cookie_jar_last_duplicate_wins() {
        let req = Request::new("GET", "/").with_header("cookie", "mode=old; mode=new");
        let jar = CookieJar::from_request_parts(&req).unwrap();
        assert_eq!(jar.get("mode"), Some("new"));
    }

    #[test]
    fn cookie_jar_ignores_malformed_segments() {
        let req = Request::new("GET", "/").with_header(
            "cookie",
            "good=1; malformed; =missing_name; spaced = ok ; quoted=\"v\"",
        );
        let jar = CookieJar::from_request_parts(&req).unwrap();
        assert_eq!(jar.get("good"), Some("1"));
        assert_eq!(jar.get("spaced"), Some("ok"));
        assert_eq!(jar.get("quoted"), Some("v"));
        assert!(!jar.contains("malformed"));
    }

    #[test]
    fn cookie_jar_missing_header_is_empty() {
        let req = Request::new("GET", "/");
        let jar = CookieJar::from_request_parts(&req).unwrap();
        assert!(jar.is_empty());
    }

    #[test]
    fn extraction_error_into_response() {
        use crate::web::response::IntoResponse;
        let err = ExtractionError::bad_request("missing field");
        let resp = err.into_response();
        assert_eq!(resp.status, crate::web::response::StatusCode::BAD_REQUEST);
        assert_eq!(
            resp.headers.get("content-type").map(String::as_str),
            Some("text/plain; charset=utf-8")
        );
    }

    #[test]
    fn extensions_extend_preserves_string_and_typed_values() {
        #[derive(Clone, Debug, PartialEq, Eq)]
        struct AppState {
            id: u32,
        }

        let mut base = Extensions::new();
        base.insert("trace_id", "abc");
        base.insert_typed(AppState { id: 7 });

        let mut req_extensions = Extensions::new();
        req_extensions.insert("request_id", "r-1");
        req_extensions.extend_from(&base);

        assert_eq!(req_extensions.get("trace_id"), Some("abc"));
        assert_eq!(req_extensions.get("request_id"), Some("r-1"));
        assert_eq!(
            req_extensions.get_typed_cloned::<AppState>(),
            Some(AppState { id: 7 })
        );
    }

    #[test]
    fn extensions_hold_multiple_typed_values_and_override_same_type() {
        #[derive(Clone, Debug, PartialEq, Eq)]
        struct AppState {
            id: u32,
        }

        #[derive(Clone, Debug, PartialEq, Eq)]
        struct FeatureFlags {
            experimental: bool,
        }

        let mut extensions = Extensions::new();
        extensions.insert_typed(AppState { id: 1 });
        extensions.insert_typed(FeatureFlags { experimental: true });
        // Same TypeId should be replaced by the most recent insert.
        extensions.insert_typed(AppState { id: 2 });

        assert_eq!(
            extensions.get_typed_cloned::<AppState>(),
            Some(AppState { id: 2 })
        );
        assert_eq!(
            extensions.get_typed_cloned::<FeatureFlags>(),
            Some(FeatureFlags { experimental: true })
        );
    }

    // ── Scalar-guard regression tests ────────────────────────────────────

    #[test]
    fn path_scalar_with_multiple_params_falls_through_to_struct() {
        // Before the len()==1 guard, Path<u32> with 2+ params would
        // nondeterministically pick whichever value HashMap yielded first.
        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct PostRef {
            user_id: u32,
            post_id: u32,
        }

        let mut params = HashMap::new();
        params.insert("user_id".to_string(), "42".to_string());
        params.insert("post_id".to_string(), "7".to_string());
        let req = Request::new("GET", "/users/42/posts/7").with_path_params(params);

        // Scalar extraction must NOT succeed — falls through to struct deser.
        assert!(Path::<u32>::from_request_parts(&req).is_err());

        // Struct extraction succeeds deterministically.
        let Path(post_ref) = Path::<PostRef>::from_request_parts(&req).unwrap();
        assert_eq!(
            post_ref,
            PostRef {
                user_id: 42,
                post_id: 7
            }
        );
    }

    #[test]
    fn query_scalar_with_multiple_params_falls_through_to_struct() {
        #[derive(Debug, serde::Deserialize, PartialEq)]
        struct Pagination {
            page: u32,
            per_page: u32,
        }

        let req = Request::new("GET", "/items").with_query("page=3&per_page=25");

        // Scalar extraction must NOT succeed with 2 query params.
        assert!(Query::<u32>::from_request_parts(&req).is_err());

        // Struct extraction works correctly.
        let Query(pg) = Query::<Pagination>::from_request_parts(&req).unwrap();
        assert_eq!(
            pg,
            Pagination {
                page: 3,
                per_page: 25
            }
        );
    }

    #[test]
    fn body_size_limit_checks_content_length_before_reading_body_dos_prevention() {
        // AUDIT TEST: Verify that Content-Length is checked BEFORE reading body
        // to prevent DoS attacks via memory exhaustion.
        // Per RFC 9110, should return 413 Payload Too Large based on Content-Length header.

        println!("=== WEB BODY SIZE LIMIT DoS PREVENTION AUDIT ===");

        // Test 1: JSON extractor checks Content-Length early
        let oversized_json_req = Request::new("POST", "/json")
            .with_header("content-type", "application/json")
            .with_header("content-length", "20971520") // 20MB declared
            .with_body(Bytes::from_static(b"{\"small\":\"body\"}")); // But small actual body

        let json_err = Json::<serde_json::Value>::from_request(oversized_json_req).unwrap_err();
        assert_eq!(
            json_err.status,
            crate::web::response::StatusCode::PAYLOAD_TOO_LARGE,
            "JSON extractor should reject based on Content-Length header before body processing"
        );
        assert!(
            json_err.message.contains("Content-Length"),
            "Error message should mention Content-Length header check, got: {}",
            json_err.message
        );

        // Test 2: Form extractor checks Content-Length early
        let oversized_form_req = Request::new("POST", "/form")
            .with_header("content-type", "application/x-www-form-urlencoded")
            .with_header("content-length", "5242880") // 5MB declared
            .with_body(Bytes::from_static(b"name=test")); // But small actual body

        let form_err =
            Form::<HashMap<String, String>>::from_request(oversized_form_req).unwrap_err();
        assert_eq!(
            form_err.status,
            crate::web::response::StatusCode::PAYLOAD_TOO_LARGE,
            "Form extractor should reject based on Content-Length header before body processing"
        );
        assert!(
            form_err.message.contains("Content-Length"),
            "Error message should mention Content-Length header check, got: {}",
            form_err.message
        );

        // Test 3: RawBody extractor checks Content-Length early
        let oversized_raw_req = Request::new("POST", "/upload")
            .with_header("content-length", "15728640") // 15MB declared
            .with_body(Bytes::from_static(b"small data")); // But small actual body

        let raw_err = RawBody::from_request(oversized_raw_req).unwrap_err();
        assert_eq!(
            raw_err.status,
            crate::web::response::StatusCode::PAYLOAD_TOO_LARGE,
            "RawBody extractor should reject based on Content-Length header before body processing"
        );
        assert!(
            raw_err.message.contains("Content-Length"),
            "Error message should mention Content-Length header check, got: {}",
            raw_err.message
        );

        // Test 4: Verify that requests within limit still work
        let valid_json_req = Request::new("POST", "/json")
            .with_header("content-type", "application/json")
            .with_header("content-length", "19") // Small declared size
            .with_body(Bytes::from_static(b"{\"valid\":\"request\"}"));

        let json_result = Json::<serde_json::Value>::from_request(valid_json_req);
        assert!(
            json_result.is_ok(),
            "Valid requests with Content-Length within limit should be processed"
        );

        println!("✅ AUDIT PASSED: Content-Length checked before body processing");
        println!("📋 DoS PROTECTION VERIFIED:");
        println!("  1. Content-Length header checked BEFORE body buffering: ✅");
        println!("  2. 413 Payload Too Large returned early: ✅");
        println!("  3. Memory exhaustion attack prevented: ✅");
        println!("  4. RFC 9110 compliance: ✅");
        println!("\n✅ STATUS: WEB BODY SIZE LIMITS ARE SECURE");
    }
}