ic-asset-router 0.1.1

File-based HTTP routing with IC response certification for Internet Computer canisters
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
use ic_http_certification::{HttpRequest, HttpResponse, Method};
use std::collections::HashMap;

use crate::middleware::MiddlewareFn;
use crate::route_config::RouteConfig;

/// Dynamic route parameters extracted from the URL path.
///
/// Maps parameter names to their captured values. For example, a route
/// registered as `/:postId/edit` matched against `/42/edit` produces
/// `{"postId": "42"}`. Wildcard routes store the remaining path under
/// the key `"*"`.
pub type RouteParams = HashMap<String, String>;

/// A synchronous route handler function.
///
/// Receives the full [`HttpRequest`] and the extracted [`RouteParams`],
/// and returns an [`HttpResponse`]. This is the standard handler signature
/// used by the router's middleware chain and certification pipeline.
pub type HandlerFn = fn(HttpRequest, RouteParams) -> HttpResponse<'static>;

/// Result of matching a path against the route tree (without method dispatch).
///
/// Contains references to the handler maps, the extracted route parameters,
/// and the matched route pattern (e.g. `"/:id/edit"`).
type MatchResult<'a> = (
    &'a HashMap<Method, HandlerFn>,
    &'a HashMap<Method, HandlerResultFn>,
    RouteParams,
    String,
);

/// A route handler that returns [`HandlerResult`] instead of a bare response.
///
/// This variant supports conditional regeneration: the handler can return
/// [`HandlerResult::NotModified`] to signal that the existing cached version
/// is still valid, avoiding a full recertification cycle.
///
/// A standard [`HandlerFn`] must also be registered at the same path/method
/// as a fallback for the query path and middleware chain. The
/// `HandlerResultFn` is only called during `http_request_update`.
///
/// # Note on signature
///
/// This type intentionally uses the internal `(HttpRequest, RouteParams)`
/// signature rather than the public `RouteContext`-based signature used by
/// generated route handlers. The build script currently does not generate
/// wrappers for `insert_result` calls — result handlers are registered
/// manually via [`RouteNode::insert_result`].
///
/// If `insert_result` is ever wired into `__route_tree.rs` code generation,
/// the same wrapper pattern used for `HandlerFn` (bridging `RouteParams` to
/// `RouteContext<Params, SearchParams>`) should be applied here as well.
pub type HandlerResultFn = fn(HttpRequest, RouteParams) -> HandlerResult;

/// Result type for route handlers that supports conditional regeneration.
///
/// Handlers can return `Response(...)` with a new response to certify, or
/// `NotModified` to indicate that the existing cached version is still valid.
/// When `NotModified` is returned, the library skips recertification entirely
/// and resets the TTL timer if TTL-based caching is active.
///
/// # Examples
///
/// ```rust,ignore
/// use ic_asset_router::{HandlerResult, HttpRequest, HttpResponse, RouteParams};
///
/// fn my_result_handler(req: HttpRequest, params: RouteParams) -> HandlerResult {
///     if content_unchanged() {
///         HandlerResult::NotModified
///     } else {
///         HandlerResult::Response(build_new_response())
///     }
/// }
/// ```
pub enum HandlerResult {
    /// New content — certify and cache this response.
    Response(HttpResponse<'static>),

    /// Content hasn't changed — keep the existing certified version
    /// and reset the TTL timer (if TTL-based caching is enabled).
    NotModified,
}

impl From<HttpResponse<'static>> for HandlerResult {
    fn from(resp: HttpResponse<'static>) -> Self {
        HandlerResult::Response(resp)
    }
}

/// The type of a node in the route trie.
///
/// Each segment of a route path corresponds to a [`RouteNode`] with one of
/// these types. During path resolution the trie tries `Static` first, then
/// `Param`, then `Wildcard` — giving static segments the highest priority.
#[derive(Debug, PartialEq, Eq)]
pub enum NodeType {
    /// A literal path segment (e.g. `"users"` in `/users`).
    Static(String),
    /// A dynamic parameter segment (e.g. `:id` in `/users/:id`).
    /// The contained string is the parameter name without the leading colon.
    Param(String),
    /// A catch-all wildcard (`*`). Matches one or more remaining segments
    /// and stores the captured tail in [`RouteParams`] under the key `"*"`.
    Wildcard,
}

/// Result of resolving a path and HTTP method against the route tree.
///
/// Returned by [`RouteNode::resolve`]. Callers should match on the three
/// variants to determine how to handle the request.
pub enum RouteResult {
    /// A handler was found for the given path and method.
    ///
    /// Fields: `(handler, params, result_handler, route_pattern)`.
    /// The optional `HandlerResultFn` is present when the route supports
    /// conditional regeneration via `HandlerResult::NotModified`.
    /// The `route_pattern` is the pattern string as registered (e.g.
    /// `"/:id/edit"`), used to look up per-route configuration.
    Found(HandlerFn, RouteParams, Option<HandlerResultFn>, String),
    /// The path exists but the requested method is not registered.
    /// Contains the list of methods that *are* registered for this path.
    MethodNotAllowed(Vec<Method>),
    /// No route matches the given path.
    NotFound,
}

/// A node in the radix-trie-style route tree.
///
/// The root node is always `NodeType::Static("")`. Routes are inserted by
/// splitting the path into segments and descending through (or creating)
/// child nodes. Resolution follows the same path, preferring static matches
/// over parameter matches over wildcard matches.
///
/// Middleware, the custom not-found handler, and `HandlerResultFn` overrides
/// are stored on the root node and consulted at dispatch time.
pub struct RouteNode {
    /// The type of this node (static segment, parameter, or wildcard).
    pub node_type: NodeType,
    /// Static child nodes, keyed by segment name.
    /// Lookup is O(1) via [`HashMap::get`].
    pub static_children: HashMap<String, RouteNode>,
    /// Optional single dynamic-parameter child (`:name` segments).
    /// At most one param child is allowed per node — this is enforced
    /// structurally by using `Option` instead of a collection.
    pub param_child: Option<Box<RouteNode>>,
    /// Optional single wildcard child (`*` segments).
    /// At most one wildcard child is allowed per node.
    pub wildcard_child: Option<Box<RouteNode>>,
    /// Method → handler map for this node. A handler is present only for
    /// methods that have been explicitly registered via [`insert`](Self::insert).
    pub handlers: HashMap<Method, HandlerFn>,
    /// Optional `HandlerResultFn` overrides for routes that support conditional
    /// regeneration. When present for a given method, `http_request_update` calls
    /// this handler first to check for `NotModified` before falling back to the
    /// standard `HandlerFn` + middleware pipeline.
    result_handlers: HashMap<Method, HandlerResultFn>,
    /// Middleware registry stored at the root node.
    /// Each entry is a `(prefix, middleware_fn)` pair, sorted by prefix segment
    /// count (shortest/outermost first). Only the root node's list is used at
    /// dispatch time; child nodes ignore this field.
    middlewares: Vec<(String, MiddlewareFn)>,
    /// Optional custom not-found handler. When set, this handler is called
    /// instead of the default 404 response when no route matches the request
    /// path. Only the root node's value is used at dispatch time.
    not_found_handler: Option<HandlerFn>,
    /// Per-route certification configuration, stored at the root node.
    /// Keys are route path patterns (e.g. `"/api/users"`, `"/:id"`).
    /// Only the root node's map is used at dispatch time; child nodes ignore
    /// this field.
    route_configs: HashMap<String, RouteConfig>,
}

impl RouteNode {
    /// Create a new route node with the given type and no children or handlers.
    pub fn new(node_type: NodeType) -> Self {
        Self {
            node_type,
            static_children: HashMap::new(),
            param_child: None,
            wildcard_child: None,
            handlers: HashMap::new(),
            result_handlers: HashMap::new(),
            middlewares: Vec::new(),
            not_found_handler: None,
            route_configs: HashMap::new(),
        }
    }

    /// Register a middleware at the given prefix.
    ///
    /// One middleware per prefix — calling this again with the same prefix
    /// replaces the previous middleware. The list is kept sorted by prefix
    /// segment count (shortest/outermost first) so that the middleware chain
    /// executes in root → outer → inner order.
    ///
    /// Use `"/"` for root-level middleware that runs on every request.
    pub fn set_middleware(&mut self, prefix: &str, mw: MiddlewareFn) {
        let normalized = normalize_prefix(prefix);
        if let Some(entry) = self.middlewares.iter_mut().find(|(p, _)| *p == normalized) {
            entry.1 = mw;
        } else {
            self.middlewares.push((normalized, mw));
        }
        // Sort by segment count (shortest first) for correct outer → inner ordering.
        self.middlewares.sort_by_key(|(p, _)| segment_count(p));
    }

    /// Register a custom not-found handler.
    ///
    /// When no route matches a request path, this handler is called instead of
    /// returning the default plain-text 404 response. The handler receives the
    /// full `HttpRequest` and empty `RouteParams`.
    ///
    /// Only one not-found handler can be registered; calling this again replaces
    /// the previous handler.
    pub fn set_not_found(&mut self, handler: HandlerFn) {
        self.not_found_handler = Some(handler);
    }

    /// Returns the custom not-found handler, if one has been registered.
    pub fn not_found_handler(&self) -> Option<HandlerFn> {
        self.not_found_handler
    }

    /// Register a [`RouteConfig`] for the given route path.
    ///
    /// This stores per-route certification configuration at the root node.
    /// The config is keyed by route path pattern (e.g. `"/api/users"`).
    /// Multiple methods on the same path share the same config.
    ///
    /// If a config already exists for the path, it is replaced.
    pub fn set_route_config(&mut self, path: &str, config: RouteConfig) {
        self.route_configs.insert(path.to_string(), config);
    }

    /// Look up the [`RouteConfig`] for a given route path.
    ///
    /// Returns `None` if no config has been registered for the path.
    /// Only the root node's map is consulted.
    pub fn get_route_config(&self, path: &str) -> Option<&RouteConfig> {
        self.route_configs.get(path)
    }

    /// Return all route path patterns configured with
    /// [`CertificationMode::Skip`](crate::CertificationMode::Skip).
    ///
    /// Used during `init`/`post_upgrade` to pre-register skip certification
    /// tree entries so that skip-mode routes never need to upgrade to an
    /// update call.
    pub fn skip_certified_paths(&self) -> Vec<String> {
        self.route_configs
            .iter()
            .filter(|(_, config)| {
                matches!(
                    config.certification,
                    crate::certification::CertificationMode::Skip
                )
            })
            .map(|(path, _)| path.clone())
            .collect()
    }

    /// Register a handler for the given path and HTTP method.
    ///
    /// Path segments starting with `:` are treated as dynamic parameters;
    /// a lone `*` segment is a catch-all wildcard. If a handler already
    /// exists for the same path and method it is silently replaced.
    pub fn insert(&mut self, path: &str, method: Method, handler: HandlerFn) {
        let node = self.get_or_create_node(path);
        node.handlers.insert(method, handler);
    }

    /// Register a `HandlerResultFn` for the given path and method.
    ///
    /// A `HandlerResultFn` returns `HandlerResult` instead of `HttpResponse`,
    /// enabling conditional regeneration via `HandlerResult::NotModified`.
    ///
    /// A standard `HandlerFn` must also be registered at the same path/method
    /// (via [`insert`](Self::insert)) — it serves as the fallback for the query
    /// path and middleware chain. The `HandlerResultFn` is only checked in
    /// `http_request_update`.
    pub fn insert_result(&mut self, path: &str, method: Method, handler: HandlerResultFn) {
        let node = self.get_or_create_node(path);
        node.result_handlers.insert(method, handler);
    }

    /// Walk (or create) the trie path for the given segments, returning
    /// a mutable reference to the terminal node.
    ///
    /// Each segment is parsed into a [`NodeType`]: `"*"` becomes
    /// [`Wildcard`](NodeType::Wildcard), a leading `:` becomes
    /// [`Param`](NodeType::Param), and anything else becomes
    /// [`Static`](NodeType::Static). Intermediate nodes are created on
    /// demand. Calling this twice with the same path returns the same
    /// node (idempotent).
    fn get_or_create_node(&mut self, path: &str) -> &mut RouteNode {
        let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
        let mut current = self;
        for seg in segments {
            match seg {
                "*" => {
                    if current.wildcard_child.is_none() {
                        current.wildcard_child = Some(Box::new(RouteNode::new(NodeType::Wildcard)));
                    }
                    current = current.wildcard_child.as_mut().unwrap();
                }
                s if s.starts_with(':') => {
                    let name = s[1..].to_string();
                    if current.param_child.is_none() {
                        current.param_child = Some(Box::new(RouteNode::new(NodeType::Param(name))));
                    }
                    current = current.param_child.as_mut().unwrap();
                }
                s => {
                    current = current
                        .static_children
                        .entry(s.to_string())
                        .or_insert_with(|| RouteNode::new(NodeType::Static(s.to_string())));
                }
            }
        }
        current
    }

    /// Execute the middleware chain for a resolved route.
    ///
    /// Collects all middleware whose prefix matches `path` (sorted outermost
    /// first), wraps `handler` as the innermost `next`, and executes the chain.
    /// Each middleware's `next` calls the next middleware inward, with the
    /// handler at the center.
    pub fn execute_with_middleware(
        &self,
        path: &str,
        handler: HandlerFn,
        req: HttpRequest,
        params: RouteParams,
    ) -> HttpResponse<'static> {
        let matching: Vec<MiddlewareFn> = self
            .middlewares
            .iter()
            .filter(|(prefix, _)| path_matches_prefix(path, prefix))
            .map(|(_, mw)| *mw)
            .collect();

        if matching.is_empty() {
            return handler(req, params);
        }

        // Build the chain from innermost to outermost.
        // Start with the handler as the innermost function.
        // Then wrap each middleware around it, from the last (innermost) to the
        // first (outermost).
        build_chain(&matching, handler, req, &params)
    }

    /// Execute the middleware chain for a not-found request.
    ///
    /// This is used when a custom not-found handler is registered: the
    /// middleware chain still runs (root/global middleware should execute
    /// before the 404 handler), with the not-found handler at the center
    /// instead of a route handler.
    pub fn execute_not_found_with_middleware(
        &self,
        path: &str,
        req: HttpRequest,
    ) -> Option<HttpResponse<'static>> {
        let handler = self.not_found_handler?;
        let params = RouteParams::new();
        Some(self.execute_with_middleware(path, handler, req, params))
    }

    /// Resolve a path and method to a `RouteResult`.
    ///
    /// 1. Finds the trie node matching `path`.
    /// 2. If found, looks up `method` in the node's `handlers` map.
    /// 3. Returns `Found` / `MethodNotAllowed` / `NotFound` accordingly.
    pub fn resolve(&self, path: &str, method: &Method) -> RouteResult {
        let segments: Vec<_> = path.split('/').filter(|s| !s.is_empty()).collect();
        match self._match(&segments) {
            Some((handlers, result_handlers, params, pattern)) => {
                if let Some(&handler) = handlers.get(method) {
                    let result_handler = result_handlers.get(method).copied();
                    RouteResult::Found(handler, params, result_handler, pattern)
                } else {
                    let allowed: Vec<Method> = handlers.keys().cloned().collect();
                    RouteResult::MethodNotAllowed(allowed)
                }
            }
            None => RouteResult::NotFound,
        }
    }

    /// Match a path and return the handlers map and params for the matched node.
    ///
    /// This performs path-only matching without method dispatch.
    /// For method-aware routing, use [`resolve()`](Self::resolve) instead.
    pub fn match_path(&self, path: &str) -> Option<MatchResult<'_>> {
        let segments: Vec<_> = path.split('/').filter(|s| !s.is_empty()).collect();
        self._match(&segments)
    }

    fn _match(&self, segments: &[&str]) -> Option<MatchResult<'_>> {
        if segments.is_empty() {
            if !self.handlers.is_empty() {
                return Some((
                    &self.handlers,
                    &self.result_handlers,
                    HashMap::new(),
                    "/".to_string(),
                ));
            }
            // No handlers on this node — check for a wildcard child (empty wildcard match)
            if let Some(ref wc) = self.wildcard_child {
                if !wc.handlers.is_empty() {
                    let mut params = HashMap::new();
                    params.insert("*".to_string(), String::new());
                    return Some((&wc.handlers, &wc.result_handlers, params, "/*".to_string()));
                }
            }
            return None;
        }

        let head = segments[0];
        let tail = &segments[1..];

        debug_log!("head: {:?}", head);

        // Static match — O(1) via HashMap lookup
        if let Some(child) = self.static_children.get(head) {
            if let Some((h, rh, p, pattern)) = child._match(tail) {
                debug_log!("Static match: {:?}", segments);
                let full_pattern = if pattern == "/" {
                    format!("/{head}")
                } else {
                    format!("/{head}{pattern}")
                };
                return Some((h, rh, p, full_pattern));
            }
        }

        // Param match — O(1) via Option
        if let Some(ref child) = self.param_child {
            if let NodeType::Param(ref name) = child.node_type {
                if let Some((h, rh, mut p, pattern)) = child._match(tail) {
                    p.insert(name.clone(), head.to_string());
                    debug_log!("Param match: {:?}", segments);
                    let full_pattern = if pattern == "/" {
                        format!("/:{name}")
                    } else {
                        format!("/:{name}{pattern}")
                    };
                    return Some((h, rh, p, full_pattern));
                }
            }
        }

        // Wildcard match — O(1) via Option
        if let Some(ref child) = self.wildcard_child {
            if !segments.is_empty() && !child.handlers.is_empty() {
                debug_log!("Wildcard match: {:?}", segments);
                let remaining = segments.join("/");
                let mut params = HashMap::new();
                params.insert("*".to_string(), remaining);
                return Some((
                    &child.handlers,
                    &child.result_handlers,
                    params,
                    "/*".to_string(),
                ));
            }
        }

        None
    }
}

/// Check whether a request path matches a middleware prefix.
///
/// `"/"` matches all paths. Otherwise, the path must start with the prefix
/// followed by either end-of-string or a `"/"` separator.
fn path_matches_prefix(path: &str, prefix: &str) -> bool {
    if prefix == "/" {
        return true;
    }
    path == prefix || path.starts_with(&format!("{prefix}/"))
}

/// Build and execute a nested middleware chain.
///
/// `middlewares` is sorted outermost-first. The handler is the innermost
/// function. We recurse: middleware[0] wraps a `next` that calls
/// `build_chain(middlewares[1..], handler, ...)`.
fn build_chain(
    middlewares: &[MiddlewareFn],
    handler: HandlerFn,
    req: HttpRequest,
    params: &RouteParams,
) -> HttpResponse<'static> {
    match middlewares.split_first() {
        None => handler(req, params.clone()),
        Some((&mw, rest)) => {
            let next =
                |inner_req: HttpRequest, inner_params: &RouteParams| -> HttpResponse<'static> {
                    build_chain(rest, handler, inner_req, inner_params)
                };
            mw(req, params, &next)
        }
    }
}

/// Normalize a middleware prefix to a canonical form: `"/"` for root, otherwise
/// `"/segment1/segment2"` with no trailing slash.
fn normalize_prefix(prefix: &str) -> String {
    let trimmed = prefix.trim_matches('/');
    if trimmed.is_empty() {
        "/".to_string()
    } else {
        format!("/{trimmed}")
    }
}

/// Count the number of non-empty path segments in a normalized prefix.
/// `"/"` has 0 segments; `"/api"` has 1; `"/api/v2"` has 2.
fn segment_count(prefix: &str) -> usize {
    prefix.split('/').filter(|s| !s.is_empty()).count()
}

// Test coverage audit (Session 7, Spec 5.5):
//
// Covered:
//   - Basic path matching: root, static, dynamic, wildcard, nested params, mixed params+wildcard
//   - Trailing slash normalization, double slash normalization
//   - Method dispatch: GET/POST differentiation, MethodNotAllowed with allowed list, all 7 methods
//   - Middleware: root scope, scoped prefix, chain order (root→outer→inner), short-circuit,
//     response modification, replacement on same prefix, query+update paths
//   - Custom 404: custom response, default fallback, request pass-through, JSON content-type,
//     middleware runs before 404
//   - From<HttpResponse> for HandlerResult conversion
//
// Gaps filled in this session:
//   - Empty segments in paths
//   - URL-encoded characters in path segments
//   - Very long paths (100 segments)
//   - Routes with many (4+) parameters
//   - Middleware modifying request before handler (header injection)
//   - Multiple middleware in hierarchy applied to not-found handler
#[cfg(test)]
mod tests {
    use super::*;
    use ic_http_certification::{Method, StatusCode};
    use std::{borrow::Cow, str};

    fn test_request(path: &str) -> HttpRequest<'_> {
        HttpRequest::builder()
            .with_method(Method::GET)
            .with_url(path)
            .build()
    }

    fn response_with_text(text: &str) -> HttpResponse<'static> {
        HttpResponse::builder()
            .with_body(Cow::Owned(text.as_bytes().to_vec()))
            .with_status_code(StatusCode::OK)
            .build()
    }

    /// Resolve a path as GET and unwrap the Found variant, returning (handler, params).
    fn resolve_get(root: &RouteNode, path: &str) -> (HandlerFn, RouteParams) {
        match root.resolve(path, &Method::GET) {
            RouteResult::Found(h, p, _, _) => (h, p),
            other => panic!(
                "expected Found for GET {path}, got {}",
                route_result_name(&other)
            ),
        }
    }

    fn route_result_name(r: &RouteResult) -> &'static str {
        match r {
            RouteResult::Found(_, _, _, _) => "Found",
            RouteResult::MethodNotAllowed(_) => "MethodNotAllowed",
            RouteResult::NotFound => "NotFound",
        }
    }

    fn matched_root(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
        response_with_text("root")
    }

    fn matched_404(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
        response_with_text("404")
    }

    fn matched_index2(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
        response_with_text("index2")
    }

    fn matched_about(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
        response_with_text("about")
    }

    fn matched_deep(_: HttpRequest, params: RouteParams) -> HttpResponse<'static> {
        response_with_text(&format!("deep: {params:?}"))
    }

    fn matched_folder(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
        response_with_text("folder")
    }

    fn setup_router() -> RouteNode {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/", Method::GET, matched_root);
        root.insert("/*", Method::GET, matched_404);
        root.insert("/index2", Method::GET, matched_index2);
        root.insert("/about", Method::GET, matched_about);
        root.insert("/deep/:pageId", Method::GET, matched_deep);
        root.insert("/deep/:pageId/:subpageId", Method::GET, matched_deep);
        root.insert("/alsodeep/:pageId/edit", Method::GET, matched_deep);
        root.insert("/folder/*", Method::GET, matched_folder);
        root
    }

    fn body_str(resp: HttpResponse<'static>) -> String {
        str::from_utf8(resp.body())
            .unwrap_or("<invalid utf-8>")
            .to_string()
    }

    // ---- Existing path-matching tests (updated for method-aware API) ----

    #[test]
    fn test_root_match() {
        let root = setup_router();
        let (handler, params) = resolve_get(&root, "/");
        assert_eq!(body_str(handler(test_request("/"), params)), "root");
    }

    #[test]
    fn test_404_match() {
        let root = setup_router();
        let (handler, _) = resolve_get(&root, "/nonexistent");
        assert_eq!(
            body_str(handler(test_request("/nonexistent"), HashMap::new())),
            "404"
        );
    }

    #[test]
    fn test_exact_match() {
        let root = setup_router();
        let (handler, params) = resolve_get(&root, "/index2");
        assert_eq!(body_str(handler(test_request("/index2"), params)), "index2");
    }

    #[test]
    fn test_pathless_layout_route_a() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/about", Method::GET, matched_about);
        let (handler, params) = resolve_get(&root, "/about");
        assert_eq!(body_str(handler(test_request("/about"), params)), "about");
    }

    #[test]
    fn test_dynamic_match() {
        let root = setup_router();
        let (handler, params) = resolve_get(&root, "/deep/page1");
        let body = body_str(handler(test_request("/deep/page1"), params));
        assert!(body.contains("page1"));
    }

    #[test]
    fn test_posts_postid_edit() {
        let root = setup_router();
        let (handler, params) = resolve_get(&root, "/alsodeep/page1/edit");
        let body = body_str(handler(test_request("/alsodeep/page1/edit"), params));
        assert!(body.contains("page1"));
    }

    #[test]
    fn test_nested_dynamic_match() {
        let root = setup_router();
        let (handler, params) = resolve_get(&root, "/deep/page2/subpage1");
        let body = body_str(handler(test_request("/deep/page2/subpage1"), params));
        assert!(body.contains("page2"));
        assert!(body.contains("subpage1"));
    }

    #[test]
    fn test_wildcard_match() {
        let root = setup_router();
        let (handler, _) = resolve_get(&root, "/folder/anything");
        assert_eq!(
            body_str(handler(test_request("/folder/anything"), HashMap::new())),
            "folder"
        );
    }

    #[test]
    fn test_folder_root_wildcard_match() {
        let root = setup_router();
        let (handler, _) = resolve_get(&root, "/folder/any");
        assert_eq!(
            body_str(handler(test_request("/folder/any"), HashMap::new())),
            "folder"
        );
    }

    #[test]
    fn test_deep_wildcard_multi_segments() {
        let root = setup_router();
        let (handler, _) = resolve_get(&root, "/folder/a/b/c/d");
        assert_eq!(
            body_str(handler(test_request("/folder/a/b/c/d"), HashMap::new())),
            "folder"
        );
    }

    #[test]
    fn test_trailing_slash_static_match() {
        let root = setup_router();
        let (handler, _) = resolve_get(&root, "/index2/");
        assert_eq!(
            body_str(handler(test_request("/index2/"), HashMap::new())),
            "index2"
        );
    }

    #[test]
    fn test_double_slash_matches_normalized() {
        let root = setup_router();
        let (handler, _) = resolve_get(&root, "//index2");
        assert_eq!(
            body_str(handler(test_request("//index2"), HashMap::new())),
            "index2"
        );
    }

    #[test]
    fn test_root_wildcard_captures_full_path() {
        let root = setup_router();
        let (_, params) = resolve_get(&root, "/a/b/c");
        assert_eq!(params.get("*").unwrap(), "a/b/c");
    }

    #[test]
    fn test_folder_wildcard_captures_tail() {
        let root = setup_router();
        let (handler, params) = resolve_get(&root, "/folder/docs/report.pdf");
        assert_eq!(params.get("*").unwrap(), "docs/report.pdf");
        assert_eq!(
            body_str(handler(
                test_request("/folder/docs/report.pdf"),
                params.clone()
            )),
            "folder"
        );
    }

    fn matched_user_files(_: HttpRequest, params: RouteParams) -> HttpResponse<'static> {
        response_with_text(&format!("user_files: {params:?}"))
    }

    #[test]
    fn test_mixed_params_and_wildcard() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/users/:id/files/*", Method::GET, matched_user_files);
        let (_, params) = resolve_get(&root, "/users/42/files/docs/report.pdf");
        assert_eq!(params.get("id").unwrap(), "42");
        assert_eq!(params.get("*").unwrap(), "docs/report.pdf");
    }

    #[test]
    fn test_empty_wildcard_match() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/files/*", Method::GET, matched_folder);
        let (handler, params) = resolve_get(&root, "/files/");
        assert_eq!(params.get("*").unwrap(), "");
        assert_eq!(
            body_str(handler(test_request("/files/"), params.clone())),
            "folder"
        );
    }

    // ---- 2.1 Method dispatch tests ----

    fn matched_post_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
        response_with_text("post_handler")
    }

    fn matched_get_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
        response_with_text("get_handler")
    }

    /// 2.1.7a: GET /path routes to get handler, POST /path routes to post handler
    #[test]
    fn test_method_dispatch_get_and_post() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/api/users", Method::GET, matched_get_handler);
        root.insert("/api/users", Method::POST, matched_post_handler);

        // GET resolves to get handler
        match root.resolve("/api/users", &Method::GET) {
            RouteResult::Found(handler, params, _, _) => {
                assert_eq!(
                    body_str(handler(test_request("/api/users"), params)),
                    "get_handler"
                );
            }
            other => panic!("expected Found, got {}", route_result_name(&other)),
        }

        // POST resolves to post handler
        match root.resolve("/api/users", &Method::POST) {
            RouteResult::Found(handler, params, _, _) => {
                let req = HttpRequest::builder()
                    .with_method(Method::POST)
                    .with_url("/api/users")
                    .build();
                assert_eq!(body_str(handler(req, params)), "post_handler");
            }
            other => panic!("expected Found, got {}", route_result_name(&other)),
        }
    }

    /// 2.1.7b: PUT /path returns 405 with allowed methods when only GET and POST registered
    #[test]
    fn test_method_not_allowed() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/api/users", Method::GET, matched_get_handler);
        root.insert("/api/users", Method::POST, matched_post_handler);

        match root.resolve("/api/users", &Method::PUT) {
            RouteResult::MethodNotAllowed(allowed) => {
                let mut names: Vec<&str> = allowed.iter().map(|m| m.as_str()).collect();
                names.sort();
                assert_eq!(names, vec!["GET", "POST"]);
            }
            other => panic!(
                "expected MethodNotAllowed, got {}",
                route_result_name(&other)
            ),
        }
    }

    /// 2.1.7c: Unknown path returns NotFound
    #[test]
    fn test_unknown_path_returns_not_found() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/api/users", Method::GET, matched_get_handler);

        assert!(matches!(
            root.resolve("/api/nonexistent", &Method::GET),
            RouteResult::NotFound
        ));
    }

    /// 2.1.7d: All 7 HTTP method types can be registered and resolved
    #[test]
    fn test_all_seven_methods() {
        let methods = [
            Method::GET,
            Method::POST,
            Method::PUT,
            Method::PATCH,
            Method::DELETE,
            Method::HEAD,
            Method::OPTIONS,
        ];

        let mut root = RouteNode::new(NodeType::Static("".into()));
        for method in &methods {
            root.insert("/test", method.clone(), matched_get_handler);
        }

        // All 7 methods should resolve to Found
        for method in &methods {
            match root.resolve("/test", method) {
                RouteResult::Found(_, _, _, _) => {}
                other => panic!(
                    "expected Found for method {}, got {}",
                    method.as_str(),
                    route_result_name(&other)
                ),
            }
        }
    }

    // ---- 2.2 Middleware tests ----

    use std::cell::RefCell;

    thread_local! {
        static LOG: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
    }

    fn clear_log() {
        LOG.with(|l| l.borrow_mut().clear());
    }

    fn get_log() -> Vec<String> {
        LOG.with(|l| l.borrow().clone())
    }

    fn log_entry(msg: &str) {
        LOG.with(|l| l.borrow_mut().push(msg.to_string()));
    }

    fn logging_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
        log_entry("handler");
        response_with_text("handler_response")
    }

    fn root_middleware(
        req: HttpRequest,
        params: &RouteParams,
        next: &dyn Fn(HttpRequest, &RouteParams) -> HttpResponse<'static>,
    ) -> HttpResponse<'static> {
        log_entry("root_mw_before");
        let resp = next(req, params);
        log_entry("root_mw_after");
        resp
    }

    fn api_middleware(
        req: HttpRequest,
        params: &RouteParams,
        next: &dyn Fn(HttpRequest, &RouteParams) -> HttpResponse<'static>,
    ) -> HttpResponse<'static> {
        log_entry("api_mw_before");
        let resp = next(req, params);
        log_entry("api_mw_after");
        resp
    }

    fn api_v2_middleware(
        req: HttpRequest,
        params: &RouteParams,
        next: &dyn Fn(HttpRequest, &RouteParams) -> HttpResponse<'static>,
    ) -> HttpResponse<'static> {
        log_entry("api_v2_mw_before");
        let resp = next(req, params);
        log_entry("api_v2_mw_after");
        resp
    }

    /// 2.2.6a: Root middleware runs on all requests
    #[test]
    fn test_root_middleware_runs_on_all_requests() {
        clear_log();
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/", Method::GET, logging_handler);
        root.insert("/about", Method::GET, logging_handler);
        root.insert("/api/users", Method::GET, logging_handler);
        root.set_middleware("/", root_middleware);

        // Root path
        let (handler, params) = resolve_get(&root, "/");
        root.execute_with_middleware("/", handler, test_request("/"), params);
        assert!(get_log().contains(&"root_mw_before".to_string()));
        assert!(get_log().contains(&"handler".to_string()));
        assert!(get_log().contains(&"root_mw_after".to_string()));

        // /about
        clear_log();
        let (handler, params) = resolve_get(&root, "/about");
        root.execute_with_middleware("/about", handler, test_request("/about"), params);
        assert!(get_log().contains(&"root_mw_before".to_string()));
        assert!(get_log().contains(&"handler".to_string()));

        // /api/users
        clear_log();
        let (handler, params) = resolve_get(&root, "/api/users");
        root.execute_with_middleware("/api/users", handler, test_request("/api/users"), params);
        assert!(get_log().contains(&"root_mw_before".to_string()));
        assert!(get_log().contains(&"handler".to_string()));
    }

    /// 2.2.6b: Scoped middleware runs only on matching prefix
    #[test]
    fn test_scoped_middleware_only_matching_prefix() {
        clear_log();
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/api/users", Method::GET, logging_handler);
        root.insert("/pages/home", Method::GET, logging_handler);
        root.set_middleware("/api", api_middleware);

        // /api/users — api_middleware should run
        let (handler, params) = resolve_get(&root, "/api/users");
        root.execute_with_middleware("/api/users", handler, test_request("/api/users"), params);
        assert!(get_log().contains(&"api_mw_before".to_string()));
        assert!(get_log().contains(&"handler".to_string()));

        // /pages/home — api_middleware should NOT run
        clear_log();
        let (handler, params) = resolve_get(&root, "/pages/home");
        root.execute_with_middleware("/pages/home", handler, test_request("/pages/home"), params);
        assert!(!get_log().contains(&"api_mw_before".to_string()));
        assert!(get_log().contains(&"handler".to_string()));
    }

    /// 2.2.6c: Chain order is root → outer → inner → handler → inner → outer → root
    #[test]
    fn test_middleware_chain_order() {
        clear_log();
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/api/v2/data", Method::GET, logging_handler);
        root.set_middleware("/", root_middleware);
        root.set_middleware("/api", api_middleware);
        root.set_middleware("/api/v2", api_v2_middleware);

        let (handler, params) = resolve_get(&root, "/api/v2/data");
        root.execute_with_middleware(
            "/api/v2/data",
            handler,
            test_request("/api/v2/data"),
            params,
        );

        let log = get_log();
        assert_eq!(
            log,
            vec![
                "root_mw_before",
                "api_mw_before",
                "api_v2_mw_before",
                "handler",
                "api_v2_mw_after",
                "api_mw_after",
                "root_mw_after",
            ]
        );
    }

    /// 2.2.6d: Middleware can short-circuit (return without calling next)
    #[test]
    fn test_middleware_short_circuit() {
        fn auth_middleware(
            _req: HttpRequest,
            _params: &RouteParams,
            _next: &dyn Fn(HttpRequest, &RouteParams) -> HttpResponse<'static>,
        ) -> HttpResponse<'static> {
            log_entry("auth_reject");
            HttpResponse::builder()
                .with_status_code(StatusCode::UNAUTHORIZED)
                .with_body(Cow::Owned(b"Unauthorized".to_vec()))
                .build()
        }

        clear_log();
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/secret", Method::GET, logging_handler);
        root.set_middleware("/", auth_middleware);

        let (handler, params) = resolve_get(&root, "/secret");
        let resp =
            root.execute_with_middleware("/secret", handler, test_request("/secret"), params);

        assert_eq!(resp.status_code(), StatusCode::UNAUTHORIZED);
        let log = get_log();
        assert!(log.contains(&"auth_reject".to_string()));
        assert!(!log.contains(&"handler".to_string()));
    }

    /// 2.2.6e: Middleware can modify the response from next
    #[test]
    fn test_middleware_modifies_response() {
        fn header_middleware(
            req: HttpRequest,
            params: &RouteParams,
            next: &dyn Fn(HttpRequest, &RouteParams) -> HttpResponse<'static>,
        ) -> HttpResponse<'static> {
            let resp = next(req, params);
            // Build a new response with an added header.
            let mut headers = resp.headers().to_vec();
            headers.push(("x-custom".to_string(), "injected".to_string()));
            HttpResponse::builder()
                .with_status_code(resp.status_code())
                .with_headers(headers)
                .with_body(resp.body().to_vec())
                .build()
        }

        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/test", Method::GET, logging_handler);
        root.set_middleware("/", header_middleware);

        let (handler, params) = resolve_get(&root, "/test");
        let resp = root.execute_with_middleware("/test", handler, test_request("/test"), params);

        let custom_header = resp
            .headers()
            .iter()
            .find(|(k, _)| k == "x-custom")
            .map(|(_, v)| v.clone());
        assert_eq!(custom_header, Some("injected".to_string()));
        assert_eq!(body_str(resp), "handler_response");
    }

    /// 2.2.6f: set_middleware on same prefix replaces previous middleware
    #[test]
    fn test_set_middleware_replaces_previous() {
        fn mw_a(
            req: HttpRequest,
            params: &RouteParams,
            next: &dyn Fn(HttpRequest, &RouteParams) -> HttpResponse<'static>,
        ) -> HttpResponse<'static> {
            log_entry("mw_a");
            next(req, params)
        }
        fn mw_b(
            req: HttpRequest,
            params: &RouteParams,
            next: &dyn Fn(HttpRequest, &RouteParams) -> HttpResponse<'static>,
        ) -> HttpResponse<'static> {
            log_entry("mw_b");
            next(req, params)
        }

        clear_log();
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/test", Method::GET, logging_handler);
        root.set_middleware("/", mw_a);
        root.set_middleware("/", mw_b); // should replace mw_a

        let (handler, params) = resolve_get(&root, "/test");
        root.execute_with_middleware("/test", handler, test_request("/test"), params);

        let log = get_log();
        assert!(!log.contains(&"mw_a".to_string()));
        assert!(log.contains(&"mw_b".to_string()));
    }

    /// 2.2.6g: Middleware works in both query and update paths.
    /// This tests that execute_with_middleware works correctly (same function
    /// is used by both http_request and http_request_update).
    #[test]
    fn test_middleware_works_in_both_paths() {
        clear_log();
        let mut root = RouteNode::new(NodeType::Static("".into()));

        fn post_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            log_entry("post_handler");
            response_with_text("posted")
        }

        root.insert("/api/data", Method::GET, logging_handler);
        root.insert("/api/data", Method::POST, post_handler);
        root.set_middleware("/api", api_middleware);

        // Simulate query path (GET)
        let (handler, params) = resolve_get(&root, "/api/data");
        let resp =
            root.execute_with_middleware("/api/data", handler, test_request("/api/data"), params);
        assert_eq!(body_str(resp), "handler_response");
        assert!(get_log().contains(&"api_mw_before".to_string()));

        // Simulate update path (POST)
        clear_log();
        match root.resolve("/api/data", &Method::POST) {
            RouteResult::Found(handler, params, _, _) => {
                let req = HttpRequest::builder()
                    .with_method(Method::POST)
                    .with_url("/api/data")
                    .build();
                let resp = root.execute_with_middleware("/api/data", handler, req, params);
                assert_eq!(body_str(resp), "posted");
                assert!(get_log().contains(&"api_mw_before".to_string()));
                assert!(get_log().contains(&"post_handler".to_string()));
            }
            other => panic!("expected Found, got {}", route_result_name(&other)),
        }
    }

    // ---- 2.3 Custom 404 tests ----

    fn custom_404_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
        HttpResponse::builder()
            .with_status_code(StatusCode::NOT_FOUND)
            .with_headers(vec![("content-type".to_string(), "text/html".to_string())])
            .with_body(Cow::Owned(b"<h1>Custom Not Found</h1>".to_vec()))
            .build()
    }

    /// 2.3.4a: With custom 404, unmatched route returns custom response
    #[test]
    fn test_custom_404_returns_custom_response() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/exists", Method::GET, matched_get_handler);
        root.set_not_found(custom_404_handler);

        // Unmatched path should invoke the custom 404 handler
        let resp = root
            .execute_not_found_with_middleware("/nonexistent", test_request("/nonexistent"))
            .expect("expected custom 404 response");
        assert_eq!(resp.status_code(), StatusCode::NOT_FOUND);
        assert_eq!(body_str(resp), "<h1>Custom Not Found</h1>");
    }

    /// 2.3.4b: Without custom 404, unmatched route returns default "Not Found"
    #[test]
    fn test_default_404_without_custom_handler() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/exists", Method::GET, matched_get_handler);
        // No set_not_found call

        // execute_not_found_with_middleware should return None
        let resp =
            root.execute_not_found_with_middleware("/nonexistent", test_request("/nonexistent"));
        assert!(resp.is_none(), "expected None when no custom 404 is set");
    }

    /// 2.3.4c: Custom 404 handler receives the full HttpRequest
    #[test]
    fn test_custom_404_receives_full_request() {
        fn inspecting_404(req: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            // Echo back the URL from the request to prove it was passed through
            let url = req.url().to_string();
            response_with_text(&format!("404 for: {url}"))
        }

        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.set_not_found(inspecting_404);

        let req = HttpRequest::builder()
            .with_method(Method::GET)
            .with_url("/some/missing/path")
            .build();
        let resp = root
            .execute_not_found_with_middleware("/some/missing/path", req)
            .expect("expected custom 404 response");
        let body = body_str(resp);
        assert!(
            body.contains("/some/missing/path"),
            "expected URL in response body, got: {body}"
        );
    }

    /// 2.3.4d: Custom 404 can return JSON content-type
    #[test]
    fn test_custom_404_json_content_type() {
        fn json_404(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            HttpResponse::builder()
                .with_status_code(StatusCode::NOT_FOUND)
                .with_headers(vec![(
                    "content-type".to_string(),
                    "application/json".to_string(),
                )])
                .with_body(Cow::Owned(br#"{"error":"not found"}"#.to_vec()))
                .build()
        }

        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.set_not_found(json_404);

        let resp = root
            .execute_not_found_with_middleware("/api/missing", test_request("/api/missing"))
            .expect("expected custom 404 response");
        assert_eq!(resp.status_code(), StatusCode::NOT_FOUND);
        let ct = resp
            .headers()
            .iter()
            .find(|(k, _)| k == "content-type")
            .map(|(_, v)| v.clone());
        assert_eq!(ct, Some("application/json".to_string()));
        assert_eq!(body_str(resp), r#"{"error":"not found"}"#);
    }

    /// 2.3.4e: Root middleware executes before custom 404 handler
    #[test]
    fn test_root_middleware_runs_before_custom_404() {
        fn logging_404(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            log_entry("custom_404");
            response_with_text("custom 404")
        }

        clear_log();
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/exists", Method::GET, logging_handler);
        root.set_middleware("/", root_middleware);
        root.set_not_found(logging_404);

        let resp = root
            .execute_not_found_with_middleware("/nonexistent", test_request("/nonexistent"))
            .expect("expected custom 404 response");

        let log = get_log();
        assert_eq!(
            log,
            vec!["root_mw_before", "custom_404", "root_mw_after"],
            "middleware should wrap the custom 404 handler"
        );
        assert_eq!(body_str(resp), "custom 404");
    }

    // ---- 4.3.11: From<HttpResponse> for HandlerResult conversion ----

    #[test]
    fn from_http_response_for_handler_result() {
        let response = HttpResponse::builder()
            .with_status_code(StatusCode::OK)
            .with_body(Cow::Owned(b"hello".to_vec()))
            .build();

        let result: HandlerResult = response.into();

        match result {
            HandlerResult::Response(resp) => {
                assert_eq!(resp.status_code(), StatusCode::OK);
                assert_eq!(resp.body(), b"hello");
            }
            HandlerResult::NotModified => panic!("expected Response, got NotModified"),
        }
    }

    // ---- 5.5.2: Router edge case tests ----

    /// Empty segments in paths are ignored by the trie (split + filter removes them).
    #[test]
    fn test_empty_segments_ignored() {
        let root = setup_router();
        // Triple slash between segments should still resolve
        let (handler, _) = resolve_get(&root, "/about///");
        assert_eq!(
            body_str(handler(test_request("/about"), HashMap::new())),
            "about"
        );
    }

    /// URL-encoded characters are passed as-is to the trie (the trie does not decode).
    /// The handler receives the raw URL-encoded segment.
    #[test]
    fn test_url_encoded_characters_in_static_path() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        // Register a route with a literal percent-encoded segment.
        root.insert("/hello%20world", Method::GET, matched_about);
        let (handler, params) = resolve_get(&root, "/hello%20world");
        assert_eq!(
            body_str(handler(test_request("/hello%20world"), params)),
            "about"
        );
    }

    /// URL-encoded characters captured by a param route are preserved as-is.
    #[test]
    fn test_url_encoded_characters_in_param() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/posts/:id", Method::GET, matched_deep);
        let (_, params) = resolve_get(&root, "/posts/hello%20world");
        assert_eq!(params.get("id").unwrap(), "hello%20world");
    }

    /// Very long paths (100 segments) are handled without stack overflow or panic.
    #[test]
    fn test_very_long_path() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        // Build a path with 100 static segments
        let segments: Vec<String> = (0..100).map(|i| format!("s{i}")).collect();
        let path = format!("/{}", segments.join("/"));
        root.insert(&path, Method::GET, matched_about);

        let (handler, params) = resolve_get(&root, &path);
        assert_eq!(body_str(handler(test_request(&path), params)), "about");
    }

    /// Very long path that does not match any route returns NotFound.
    #[test]
    fn test_very_long_path_not_found() {
        let root = RouteNode::new(NodeType::Static("".into()));
        let segments: Vec<String> = (0..100).map(|i| format!("s{i}")).collect();
        let path = format!("/{}", segments.join("/"));
        assert!(matches!(
            root.resolve(&path, &Method::GET),
            RouteResult::NotFound
        ));
    }

    /// Routes with many (4) dynamic parameters all capture correctly.
    #[test]
    fn test_many_parameters() {
        fn many_param_handler(_: HttpRequest, params: RouteParams) -> HttpResponse<'static> {
            response_with_text(&format!(
                "{}/{}/{}/{}",
                params.get("a").unwrap(),
                params.get("b").unwrap(),
                params.get("c").unwrap(),
                params.get("d").unwrap(),
            ))
        }

        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/:a/:b/:c/:d", Method::GET, many_param_handler);

        let (handler, params) = resolve_get(&root, "/w/x/y/z");
        assert_eq!(params.get("a").unwrap(), "w");
        assert_eq!(params.get("b").unwrap(), "x");
        assert_eq!(params.get("c").unwrap(), "y");
        assert_eq!(params.get("d").unwrap(), "z");
        assert_eq!(
            body_str(handler(test_request("/w/x/y/z"), params)),
            "w/x/y/z"
        );
    }

    /// Static route takes precedence over param route for the same segment.
    #[test]
    fn test_static_precedence_over_param() {
        fn static_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            response_with_text("static")
        }
        fn param_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            response_with_text("param")
        }

        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/items/special", Method::GET, static_handler);
        root.insert("/items/:id", Method::GET, param_handler);

        // "/items/special" should match the static route
        let (handler, _) = resolve_get(&root, "/items/special");
        assert_eq!(
            body_str(handler(test_request("/items/special"), HashMap::new())),
            "static"
        );

        // "/items/other" should match the param route
        let (handler, params) = resolve_get(&root, "/items/other");
        assert_eq!(
            body_str(handler(test_request("/items/other"), params)),
            "param"
        );
    }

    /// Param route takes precedence over wildcard route.
    #[test]
    fn test_param_precedence_over_wildcard() {
        fn param_handler(_: HttpRequest, params: RouteParams) -> HttpResponse<'static> {
            response_with_text(&format!("param:{}", params.get("id").unwrap()))
        }
        fn wildcard_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            response_with_text("wildcard")
        }

        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/items/:id", Method::GET, param_handler);
        root.insert("/items/*", Method::GET, wildcard_handler);

        // Single segment after /items/ should match param route
        let (handler, params) = resolve_get(&root, "/items/42");
        assert_eq!(
            body_str(handler(test_request("/items/42"), params.clone())),
            "param:42"
        );

        // Multiple segments should match wildcard
        let (handler, params) = resolve_get(&root, "/items/42/extra");
        assert_eq!(params.get("*").unwrap(), "42/extra");
        assert_eq!(
            body_str(handler(test_request("/items/42/extra"), params)),
            "wildcard"
        );
    }

    /// Root path "/" should not match when only nested routes exist.
    #[test]
    fn test_root_not_found_when_only_nested() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/api/data", Method::GET, matched_about);
        assert!(matches!(
            root.resolve("/", &Method::GET),
            RouteResult::NotFound
        ));
    }

    /// insert_result and resolve return the result handler.
    #[test]
    fn test_insert_result_and_resolve() {
        fn handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            response_with_text("ok")
        }
        fn result_handler(_: HttpRequest, _: RouteParams) -> HandlerResult {
            HandlerResult::NotModified
        }

        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/test", Method::GET, handler);
        root.insert_result("/test", Method::GET, result_handler);

        match root.resolve("/test", &Method::GET) {
            RouteResult::Found(_, _, Some(rh), _) => {
                // Verify the result handler returns NotModified
                let result = rh(test_request("/test"), HashMap::new());
                assert!(matches!(result, HandlerResult::NotModified));
            }
            RouteResult::Found(_, _, None, _) => panic!("expected result handler to be present"),
            other => panic!("expected Found, got {}", route_result_name(&other)),
        }
    }

    /// match_path returns handlers and params without method dispatch.
    #[test]
    fn test_match_path_returns_handlers() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/items/:id", Method::GET, matched_get_handler);
        root.insert("/items/:id", Method::POST, matched_post_handler);

        let (handlers, _, params, _) = root.match_path("/items/42").expect("should match");
        assert_eq!(params.get("id").unwrap(), "42");
        assert!(handlers.contains_key(&Method::GET));
        assert!(handlers.contains_key(&Method::POST));
        assert_eq!(handlers.len(), 2);
    }

    /// match_path returns None for non-existent paths.
    #[test]
    fn test_match_path_returns_none() {
        let root = RouteNode::new(NodeType::Static("".into()));
        assert!(root.match_path("/nonexistent").is_none());
    }

    // ---- 5.5.3: Additional middleware chain tests ----

    /// Middleware can modify the request before passing it to the handler.
    /// The handler sees the modified request (e.g. added headers).
    #[test]
    fn test_middleware_modifies_request_before_handler() {
        fn inject_header_mw(
            req: HttpRequest,
            params: &RouteParams,
            next: &dyn Fn(HttpRequest, &RouteParams) -> HttpResponse<'static>,
        ) -> HttpResponse<'static> {
            // Build a new request with an added header.
            let mut headers = req.headers().to_vec();
            headers.push(("x-injected".to_string(), "mw-value".to_string()));
            let modified = HttpRequest::builder()
                .with_method(req.method().clone())
                .with_url(req.url())
                .with_headers(headers)
                .with_body(req.body().to_vec())
                .build();
            next(modified, params)
        }

        fn header_checking_handler(req: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            let has_header = req
                .headers()
                .iter()
                .any(|(k, v)| k == "x-injected" && v == "mw-value");
            if has_header {
                response_with_text("header_present")
            } else {
                response_with_text("header_missing")
            }
        }

        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/check", Method::GET, header_checking_handler);
        root.set_middleware("/", inject_header_mw);

        let (handler, params) = resolve_get(&root, "/check");
        let resp = root.execute_with_middleware("/check", handler, test_request("/check"), params);
        assert_eq!(body_str(resp), "header_present");
    }

    /// Multiple middleware at different hierarchy levels all apply to not-found handler.
    #[test]
    fn test_multiple_middleware_on_not_found() {
        fn nf_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            log_entry("not_found_handler");
            response_with_text("not found")
        }

        clear_log();
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/api/data", Method::GET, logging_handler);
        root.set_middleware("/", root_middleware);
        root.set_middleware("/api", api_middleware);
        root.set_not_found(nf_handler);

        // Request to /api/missing — both root and /api middleware should fire
        let resp = root
            .execute_not_found_with_middleware("/api/missing", test_request("/api/missing"))
            .expect("expected not-found response");

        let log = get_log();
        assert_eq!(
            log,
            vec![
                "root_mw_before",
                "api_mw_before",
                "not_found_handler",
                "api_mw_after",
                "root_mw_after",
            ],
            "both root and /api middleware should wrap the not-found handler"
        );
        assert_eq!(body_str(resp), "not found");
    }

    /// Only root middleware applies to not-found for paths outside /api.
    #[test]
    fn test_not_found_only_root_middleware_for_non_api() {
        fn nf_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            log_entry("not_found_handler");
            response_with_text("not found")
        }

        clear_log();
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/api/data", Method::GET, logging_handler);
        root.set_middleware("/", root_middleware);
        root.set_middleware("/api", api_middleware);
        root.set_not_found(nf_handler);

        // Request to /other/missing — only root middleware, NOT /api middleware
        let resp = root
            .execute_not_found_with_middleware("/other/missing", test_request("/other/missing"))
            .expect("expected not-found response");

        let log = get_log();
        assert_eq!(
            log,
            vec!["root_mw_before", "not_found_handler", "root_mw_after"],
            "/api middleware should NOT fire for /other/missing"
        );
        assert_eq!(body_str(resp), "not found");
    }

    /// Middleware executes in correct order regardless of the registration order.
    /// (Ordering is by prefix segment count, not insertion order.)
    #[test]
    fn test_middleware_ordering_independent_of_registration_order() {
        clear_log();
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/api/v2/data", Method::GET, logging_handler);

        // Register in reverse order: inner → outer → root
        root.set_middleware("/api/v2", api_v2_middleware);
        root.set_middleware("/api", api_middleware);
        root.set_middleware("/", root_middleware);

        let (handler, params) = resolve_get(&root, "/api/v2/data");
        root.execute_with_middleware(
            "/api/v2/data",
            handler,
            test_request("/api/v2/data"),
            params,
        );

        let log = get_log();
        assert_eq!(
            log,
            vec![
                "root_mw_before",
                "api_mw_before",
                "api_v2_mw_before",
                "handler",
                "api_v2_mw_after",
                "api_mw_after",
                "root_mw_after",
            ],
            "order should be root→api→api_v2 regardless of registration order"
        );
    }

    /// No middleware registered — handler runs directly without wrapping.
    #[test]
    fn test_no_middleware_handler_runs_directly() {
        clear_log();
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/test", Method::GET, logging_handler);
        // No set_middleware calls

        let (handler, params) = resolve_get(&root, "/test");
        let resp = root.execute_with_middleware("/test", handler, test_request("/test"), params);

        let log = get_log();
        assert_eq!(log, vec!["handler"]);
        assert_eq!(body_str(resp), "handler_response");
    }

    /// normalize_prefix normalizes various formats to canonical form.
    #[test]
    fn test_normalize_prefix_canonical() {
        assert_eq!(normalize_prefix("/"), "/");
        assert_eq!(normalize_prefix(""), "/");
        assert_eq!(normalize_prefix("/api"), "/api");
        assert_eq!(normalize_prefix("/api/"), "/api");
        assert_eq!(normalize_prefix("api"), "/api");
        assert_eq!(normalize_prefix("api/v2/"), "/api/v2");
    }

    /// segment_count returns correct counts.
    #[test]
    fn test_segment_count() {
        assert_eq!(segment_count("/"), 0);
        assert_eq!(segment_count("/api"), 1);
        assert_eq!(segment_count("/api/v2"), 2);
        assert_eq!(segment_count("/api/v2/data"), 3);
    }

    /// path_matches_prefix works for various combinations.
    #[test]
    fn test_path_matches_prefix() {
        // Root prefix matches everything
        assert!(path_matches_prefix("/api/data", "/"));
        assert!(path_matches_prefix("/", "/"));

        // Exact match
        assert!(path_matches_prefix("/api", "/api"));

        // Prefix match with separator
        assert!(path_matches_prefix("/api/data", "/api"));
        assert!(path_matches_prefix("/api/v2/data", "/api"));

        // Does not match partial segment
        assert!(!path_matches_prefix("/api-v2", "/api"));
        assert!(!path_matches_prefix("/apidata", "/api"));

        // No match
        assert!(!path_matches_prefix("/other", "/api"));
    }

    // ---- 5.5.7: Property-based tests (proptest) ----

    mod proptests {
        use super::*;
        use proptest::prelude::*;

        fn dummy_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            response_with_text("dummy")
        }

        proptest! {
            /// Inserted routes are always found: any valid path that is inserted
            /// should resolve to Found for the same method.
            #[test]
            fn inserted_routes_are_always_found(path in "/[a-z]{1,5}(/[a-z]{1,5}){0,4}") {
                let mut root = RouteNode::new(NodeType::Static("".into()));
                root.insert(&path, Method::GET, dummy_handler);
                match root.resolve(&path, &Method::GET) {
                    RouteResult::Found(_, _, _, _) => {},
                    _ => panic!("expected Found for inserted path: {path}"),
                }
            }

            /// Non-inserted routes are not found: a route that was never inserted
            /// should resolve to NotFound (assuming no wildcard or param overlap).
            #[test]
            fn non_inserted_routes_are_not_found(
                inserted in "/[a-z]{1,10}",
                queried in "/[a-z]{1,10}"
            ) {
                prop_assume!(inserted != queried);
                let mut root = RouteNode::new(NodeType::Static("".into()));
                root.insert(&inserted, Method::GET, dummy_handler);
                match root.resolve(&queried, &Method::GET) {
                    RouteResult::NotFound => {},
                    _ => panic!("expected NotFound for non-inserted route: {queried} (inserted: {inserted})"),
                }
            }

            /// Param routes capture any single segment value.
            #[test]
            fn param_routes_capture_any_segment(
                prefix in "/[a-z]{1,5}",
                value in "[a-z0-9]{1,20}"
            ) {
                let route = format!("{prefix}/:id");
                let path = format!("{prefix}/{value}");
                let mut root = RouteNode::new(NodeType::Static("".into()));
                root.insert(&route, Method::GET, dummy_handler);
                match root.resolve(&path, &Method::GET) {
                    RouteResult::Found(_, params, _, _) => {
                        prop_assert_eq!(params.get("id").map(|s| s.as_str()), Some(value.as_str()));
                    },
                    other => panic!("expected Found, got {}", route_result_name(&other)),
                }
            }

            /// Wildcard routes capture the remaining path (one or more segments).
            #[test]
            fn wildcard_routes_capture_remaining_path(
                prefix in "/[a-z]{1,5}",
                tail in "[a-z0-9]{1,5}(/[a-z0-9]{1,5}){0,3}"
            ) {
                let route = format!("{prefix}/*");
                let path = format!("{prefix}/{tail}");
                let mut root = RouteNode::new(NodeType::Static("".into()));
                root.insert(&route, Method::GET, dummy_handler);
                match root.resolve(&path, &Method::GET) {
                    RouteResult::Found(_, params, _, _) => {
                        prop_assert_eq!(params.get("*").map(|s| s.as_str()), Some(tail.as_str()));
                    },
                    other => panic!("expected Found, got {}", route_result_name(&other)),
                }
            }

            /// Inserting a route does not affect resolution of a different method
            /// on the same path — it should return MethodNotAllowed, not Found.
            #[test]
            fn wrong_method_returns_method_not_allowed(path in "/[a-z]{1,5}(/[a-z]{1,5}){0,3}") {
                let mut root = RouteNode::new(NodeType::Static("".into()));
                root.insert(&path, Method::GET, dummy_handler);
                match root.resolve(&path, &Method::POST) {
                    RouteResult::MethodNotAllowed(allowed) => {
                        prop_assert!(allowed.contains(&Method::GET));
                    },
                    other => panic!("expected MethodNotAllowed, got {}", route_result_name(&other)),
                }
            }

            /// Multiple param routes with different names capture correctly.
            #[test]
            fn multi_param_routes_capture_all(
                a in "[a-z0-9]{1,10}",
                b in "[a-z0-9]{1,10}"
            ) {
                let mut root = RouteNode::new(NodeType::Static("".into()));
                root.insert("/x/:first/:second", Method::GET, dummy_handler);
                let path = format!("/x/{a}/{b}");
                match root.resolve(&path, &Method::GET) {
                    RouteResult::Found(_, params, _, _) => {
                        prop_assert_eq!(params.get("first").map(|s| s.as_str()), Some(a.as_str()));
                        prop_assert_eq!(params.get("second").map(|s| s.as_str()), Some(b.as_str()));
                    },
                    other => panic!("expected Found, got {}", route_result_name(&other)),
                }
            }
        }
    }

    // ---- 7.4 Route config and pattern tests ----

    #[test]
    fn set_and_get_route_config() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/api/users", Method::GET, matched_get_handler);

        let config = RouteConfig {
            certification: crate::certification::CertificationMode::skip(),
            ttl: Some(std::time::Duration::from_secs(60)),
            headers: vec![],
        };
        root.set_route_config("/api/users", config);

        let rc = root
            .get_route_config("/api/users")
            .expect("should find config");
        assert!(matches!(
            rc.certification,
            crate::certification::CertificationMode::Skip
        ));
        assert_eq!(rc.ttl, Some(std::time::Duration::from_secs(60)));
    }

    #[test]
    fn get_route_config_returns_none_for_unknown() {
        let root = RouteNode::new(NodeType::Static("".into()));
        assert!(root.get_route_config("/nonexistent").is_none());
    }

    #[test]
    fn set_route_config_replaces_existing() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/test", Method::GET, matched_get_handler);

        let config1 = RouteConfig {
            certification: crate::certification::CertificationMode::skip(),
            ttl: None,
            headers: vec![],
        };
        root.set_route_config("/test", config1);

        let config2 = RouteConfig {
            certification: crate::certification::CertificationMode::authenticated(),
            ttl: Some(std::time::Duration::from_secs(300)),
            headers: vec![],
        };
        root.set_route_config("/test", config2);

        let rc = root.get_route_config("/test").expect("should find config");
        assert!(matches!(
            rc.certification,
            crate::certification::CertificationMode::Full(_)
        ));
        assert_eq!(rc.ttl, Some(std::time::Duration::from_secs(300)));
    }

    #[test]
    fn routes_without_config_default_to_response_only() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/page", Method::GET, matched_get_handler);

        // No set_route_config call — get_route_config returns None,
        // and the caller should default to response_only.
        assert!(root.get_route_config("/page").is_none());
    }

    #[test]
    fn resolve_returns_correct_pattern_for_static_route() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/api/users", Method::GET, matched_get_handler);

        match root.resolve("/api/users", &Method::GET) {
            RouteResult::Found(_, _, _, pattern) => {
                assert_eq!(pattern, "/api/users");
            }
            other => panic!("expected Found, got {}", route_result_name(&other)),
        }
    }

    #[test]
    fn resolve_returns_correct_pattern_for_param_route() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/users/:id", Method::GET, matched_get_handler);

        match root.resolve("/users/42", &Method::GET) {
            RouteResult::Found(_, params, _, pattern) => {
                assert_eq!(pattern, "/users/:id");
                assert_eq!(params.get("id").unwrap(), "42");
            }
            other => panic!("expected Found, got {}", route_result_name(&other)),
        }
    }

    #[test]
    fn resolve_returns_correct_pattern_for_wildcard_route() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/files/*", Method::GET, matched_get_handler);

        match root.resolve("/files/a/b/c", &Method::GET) {
            RouteResult::Found(_, params, _, pattern) => {
                assert_eq!(pattern, "/files/*");
                assert_eq!(params.get("*").unwrap(), "a/b/c");
            }
            other => panic!("expected Found, got {}", route_result_name(&other)),
        }
    }

    #[test]
    fn resolve_returns_correct_pattern_for_root_route() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/", Method::GET, matched_get_handler);

        match root.resolve("/", &Method::GET) {
            RouteResult::Found(_, _, _, pattern) => {
                assert_eq!(pattern, "/");
            }
            other => panic!("expected Found, got {}", route_result_name(&other)),
        }
    }

    #[test]
    fn resolve_returns_correct_pattern_for_nested_param() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert(
            "/posts/:postId/comments/:commentId",
            Method::GET,
            matched_get_handler,
        );

        match root.resolve("/posts/10/comments/20", &Method::GET) {
            RouteResult::Found(_, params, _, pattern) => {
                assert_eq!(pattern, "/posts/:postId/comments/:commentId");
                assert_eq!(params.get("postId").unwrap(), "10");
                assert_eq!(params.get("commentId").unwrap(), "20");
            }
            other => panic!("expected Found, got {}", route_result_name(&other)),
        }
    }

    #[test]
    fn route_config_lookup_via_pattern() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/users/:id", Method::GET, matched_get_handler);

        let config = RouteConfig {
            certification: crate::certification::CertificationMode::skip(),
            ttl: None,
            headers: vec![],
        };
        root.set_route_config("/users/:id", config);

        // Resolve actual path, get pattern, then look up config.
        match root.resolve("/users/42", &Method::GET) {
            RouteResult::Found(_, _, _, pattern) => {
                let rc = root.get_route_config(&pattern).expect("should find config");
                assert!(matches!(
                    rc.certification,
                    crate::certification::CertificationMode::Skip
                ));
            }
            other => panic!("expected Found, got {}", route_result_name(&other)),
        }
    }

    // ---- 8.3.3: get_or_create_node tests ----

    /// get_or_create_node creates intermediate nodes on first call.
    #[test]
    fn test_get_or_create_node_creates_intermediate_nodes() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        let _node = root.get_or_create_node("/api/v2/data");

        // Root should have one static child: "api"
        assert_eq!(root.static_children.len(), 1);
        let api = root.static_children.get("api").expect("api child");
        assert_eq!(api.node_type, NodeType::Static("api".into()));

        // "api" should have one static child: "v2"
        assert_eq!(api.static_children.len(), 1);
        let v2 = api.static_children.get("v2").expect("v2 child");
        assert_eq!(v2.node_type, NodeType::Static("v2".into()));

        // "v2" should have one static child: "data"
        assert_eq!(v2.static_children.len(), 1);
        let data = v2.static_children.get("data").expect("data child");
        assert_eq!(data.node_type, NodeType::Static("data".into()));
    }

    /// get_or_create_node is idempotent: second call returns the same node
    /// without creating duplicates.
    #[test]
    fn test_get_or_create_node_idempotent() {
        let mut root = RouteNode::new(NodeType::Static("".into()));

        // First call creates nodes.
        let node = root.get_or_create_node("/api/users");
        node.handlers.insert(Method::GET, matched_get_handler);

        // Second call should find the existing node.
        let node2 = root.get_or_create_node("/api/users");
        assert!(
            node2.handlers.contains_key(&Method::GET),
            "second call should return the same node with the handler intact"
        );

        // Only one child chain should exist (no duplicates).
        assert_eq!(root.static_children.len(), 1);
        let api = root.static_children.get("api").expect("api child");
        assert_eq!(api.static_children.len(), 1);
    }

    /// get_or_create_node with root path "/" returns self.
    #[test]
    fn test_get_or_create_node_root_path() {
        let mut root = RouteNode::new(NodeType::Static("".into()));

        let node = root.get_or_create_node("/");
        node.handlers.insert(Method::GET, matched_get_handler);

        // The handler should be on the root node itself.
        assert!(root.handlers.contains_key(&Method::GET));
        // No children created for root path.
        assert!(root.static_children.is_empty());
        assert!(root.param_child.is_none());
        assert!(root.wildcard_child.is_none());
    }

    /// get_or_create_node handles param and wildcard segments.
    #[test]
    fn test_get_or_create_node_param_and_wildcard() {
        let mut root = RouteNode::new(NodeType::Static("".into()));

        let _node = root.get_or_create_node("/users/:id/files/*");

        assert_eq!(root.static_children.len(), 1);
        let users = root.static_children.get("users").expect("users child");
        assert_eq!(users.node_type, NodeType::Static("users".into()));

        let param = users.param_child.as_ref().expect("param child");
        assert_eq!(param.node_type, NodeType::Param("id".into()));

        assert_eq!(param.static_children.len(), 1);
        let files = param.static_children.get("files").expect("files child");
        assert_eq!(files.node_type, NodeType::Static("files".into()));

        let wc = files.wildcard_child.as_ref().expect("wildcard child");
        assert_eq!(wc.node_type, NodeType::Wildcard);
    }

    // ---- 8.5.6: Route trie preserves raw-encoded param values ----

    /// Param route with `%20` in the URL resolves correctly and the raw param
    /// value contains `%20` — decoding is the responsibility of generated wrapper
    /// code, not the trie itself.
    #[test]
    fn test_param_with_percent_encoded_space_resolves_raw() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/posts/:id", Method::GET, matched_deep);
        let (_, params) = resolve_get(&root, "/posts/hello%20world");
        assert_eq!(
            params.get("id").unwrap(),
            "hello%20world",
            "trie should store the raw percent-encoded value; decoding happens in generated code"
        );
    }

    /// Wildcard route with `%20` in the URL preserves the raw encoded value.
    #[test]
    fn test_wildcard_with_percent_encoded_space_resolves_raw() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/files/*", Method::GET, matched_folder);
        let (_, params) = resolve_get(&root, "/files/hello%20world/doc.pdf");
        assert_eq!(
            params.get("*").unwrap(),
            "hello%20world/doc.pdf",
            "trie should store the raw percent-encoded wildcard value"
        );
    }

    // ---- 8.6.2: Router trie edge case tests ----

    /// Inserting two param routes with different names at the same level reuses
    /// the first param child. The second insert's param name is silently ignored
    /// because `get_or_create_node` only creates a param child if none exists.
    #[test]
    fn multiple_param_children_first_wins() {
        fn handler_a(_: HttpRequest, params: RouteParams) -> HttpResponse<'static> {
            response_with_text(&format!("a:{}", params.get("a").unwrap_or(&String::new())))
        }
        fn handler_b(_: HttpRequest, params: RouteParams) -> HttpResponse<'static> {
            response_with_text(&format!("b:{}", params.get("b").unwrap_or(&String::new())))
        }

        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/items/:a", Method::GET, handler_a);
        // Second insert reuses the existing param child (named "a"), so the
        // handler is added to that same node — but the param name stays "a".
        root.insert("/items/:b", Method::POST, handler_b);

        // GET resolves and the param is captured under name "a" (first wins).
        let (handler, params) = resolve_get(&root, "/items/42");
        assert_eq!(params.get("a"), Some(&"42".to_string()));
        assert_eq!(params.get("b"), None);
        assert_eq!(body_str(handler(test_request("/items/42"), params)), "a:42");

        // POST also uses param name "a" — the `:b` name from the second insert
        // was silently discarded.
        match root.resolve("/items/99", &Method::POST) {
            RouteResult::Found(handler, params, _, _) => {
                assert_eq!(params.get("a"), Some(&"99".to_string()));
                assert_eq!(params.get("b"), None);
                // handler_b tries to read "b" which is None, so prints "b:"
                assert_eq!(body_str(handler(test_request("/items/99"), params)), "b:");
            }
            other => panic!("expected Found, got {}", route_result_name(&other)),
        }
    }

    /// Wildcard route `/files/*` consumes all remaining segments.
    #[test]
    fn wildcard_consumes_remaining_segments() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/files/*", Method::GET, matched_folder);

        // Single segment after /files/
        let (_, params) = resolve_get(&root, "/files/a");
        assert_eq!(params.get("*").unwrap(), "a");

        // Multiple segments after /files/
        let (_, params) = resolve_get(&root, "/files/a/b/c");
        assert_eq!(params.get("*").unwrap(), "a/b/c");

        // Deep nesting
        let (_, params) = resolve_get(&root, "/files/a/b/c/d/e");
        assert_eq!(params.get("*").unwrap(), "a/b/c/d/e");
    }

    /// Routes registered after a wildcard (e.g., `/files/*/edit`) are
    /// unreachable because `_match` consumes all remaining segments at the
    /// wildcard node without recursing further.
    #[test]
    fn post_wildcard_segments_unreachable() {
        fn edit_handler(_: HttpRequest, _: RouteParams) -> HttpResponse<'static> {
            response_with_text("edit")
        }

        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/files/*", Method::GET, matched_folder);
        // This creates a child under the wildcard node, but _match never
        // recurses into it — the wildcard greedily matches all segments.
        root.insert("/files/*/edit", Method::GET, edit_handler);

        // "/files/something/edit" is consumed by the wildcard, not the edit route.
        let (handler, params) = resolve_get(&root, "/files/something/edit");
        assert_eq!(params.get("*").unwrap(), "something/edit");
        assert_eq!(
            body_str(handler(test_request("/files/something/edit"), params)),
            "folder"
        );
    }

    /// Empty path "/" resolves to the root node's handler.
    #[test]
    fn empty_path_resolves_to_root() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/", Method::GET, matched_root);

        let (handler, params) = resolve_get(&root, "/");
        assert!(params.is_empty());
        assert_eq!(body_str(handler(test_request("/"), params)), "root");
    }

    /// Trailing slash is normalized: "/about/" matches "/about".
    #[test]
    fn trailing_slash_normalization() {
        let mut root = RouteNode::new(NodeType::Static("".into()));
        root.insert("/about", Method::GET, matched_about);

        // Without trailing slash
        let (handler, _) = resolve_get(&root, "/about");
        assert_eq!(
            body_str(handler(test_request("/about"), HashMap::new())),
            "about"
        );

        // With trailing slash — should match the same route
        let (handler, _) = resolve_get(&root, "/about/");
        assert_eq!(
            body_str(handler(test_request("/about/"), HashMap::new())),
            "about"
        );
    }
}