cot 0.8.0

The Rust web framework for lazy developers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
//! Router for passing requests to their respective views.
//!
//! # Examples
//!
//! ```
//! use cot::request::Request;
//! use cot::response::Response;
//! use cot::router::{Route, Router};
//!
//! async fn home(request: Request) -> cot::Result<Response> {
//!     Ok(cot::reverse_redirect!(request, "get_page", page = 123)?)
//! }
//!
//! async fn get_page(request: Request) -> cot::Result<Response> {
//!     unimplemented!()
//! }
//!
//! let router = Router::with_urls([Route::with_handler_and_name(
//!     "/{page}", get_page, "get_page",
//! )]);
//! ```

use std::collections::HashMap;
use std::fmt::Formatter;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use cot::router::path::AbsolutePath;
use cot_core::error::impl_into_cot_error;
use cot_core::handler::{BoxRequestHandler, RequestHandler, into_box_request_handler};
use cot_core::request::{AppName, RouteName};
use derive_more::with_trait::Debug;
use tracing::debug;

use crate::error::NotFound;
use crate::request::{PathParams, Request, RequestExt, RequestHead};
use crate::response::Response;
use crate::router::path::{PathMatcher, ReverseParamMap};
use crate::router::tree::{Entry, MatchitPattern, RouteTrie};
use crate::{Error, ProjectContext, Result};

pub mod method;
pub mod path;
mod tree;

type RouteMap = HashMap<RouteName, Vec<(Option<AppName>, Arc<PathMatcher>)>>;

/// A router that can be used to route requests to their respective views.
///
/// This struct is responsible for routing requests to their respective views.
/// It can be created directly by calling the [`Router::with_urls`] method, and
/// that's what is typically done in [`cot::App::router`] implementations.
///
/// # Examples
///
/// ```
/// use cot::request::Request;
/// use cot::response::Response;
/// use cot::router::{Route, Router};
///
/// async fn home(request: Request) -> cot::Result<Response> {
///     unimplemented!()
/// }
///
/// let router = Router::with_urls([Route::with_handler_and_name("/", home, "home")]);
/// ```
#[derive(Clone, Debug)]
pub struct Router {
    app_name: Option<AppName>,
    urls: Vec<Route>,
    names: RouteMap,
    route_tree: RouteTrie,
}

impl Router {
    /// Create an empty router.
    ///
    /// This router will not route any requests.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::router::Router;
    ///
    /// let router = Router::empty();
    /// ```
    #[must_use]
    pub fn empty() -> Self {
        Self::with_urls(&[])
    }

    /// Create a router with the given routes.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::{Route, Router};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     unimplemented!()
    /// }
    ///
    /// let router = Router::with_urls([Route::with_handler_and_name("/", home, "home")]);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics when a url string could not be parsed into a [`Route`]
    #[must_use]
    pub fn with_urls<T: Into<Vec<Route>>>(urls: T) -> Self {
        Self::try_with_urls(urls).expect("could not construct `Router` with given routes")
    }

    /// Create a router with the given routes. This is a fallible version
    /// of [`Self::with_urls`]
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::{Route, Router};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     unimplemented!()
    /// }
    ///
    /// let router = Router::try_with_urls([Route::with_handler_and_name("/", home, "home")]).unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// This method fails when the underlying trie fails to build.
    pub fn try_with_urls<T: Into<Vec<Route>>>(urls: T) -> Result<Self> {
        let urls = Self::merge_conflicting_routers(urls.into())?;
        let mut names: RouteMap = HashMap::new();

        for url in &urls {
            if let Some(name) = &url.name {
                let requested = url.app_name.as_ref().map(|a| a.0.as_str());
                let bucket = names.entry(name.clone()).or_default();
                if let Some((_, existing_url)) = bucket
                    .iter()
                    .find(|(app, _)| app.as_ref().map(|a| a.0.as_str()) == requested)
                {
                    // we found another route in the same app with the same
                    // name. This is unacceptable
                    return Err(RouteConflictError::DuplicateRouteName {
                        name: name.0.clone(),
                        existing: existing_url.to_string(),
                        new: url.url(),
                    }
                    .into());
                }
                bucket.push((url.app_name.clone(), url.url.clone()));
            }
        }
        let route_tree = RouteTrie::build(&urls)?;
        Ok(Self {
            app_name: None,
            urls,
            names,
            route_tree,
        })
    }

    fn merge_conflicting_routers(urls: Vec<Route>) -> Result<Vec<Route>> {
        let mut merged: Vec<Route> = Vec::with_capacity(urls.len());
        let mut positions: HashMap<MatchitPattern, usize> = HashMap::new();

        for route in urls {
            if route.kind() != RouteKind::Router {
                merged.push(route);
                continue;
            }
            // we want to merge/fold routers that have the same mount
            // point(pattern). This can be useful especially in cases
            // where multiple apps are registered with the same pattern
            // as shown in the example below:
            //
            // fn register_apps(
            //    &self, apps: &mut AppBuilder,
            //    _context: &RegisterAppsContext
            // ) {
            //     apps.register_with_views(App1, "/foo");
            //     apps.register_with_views(App2, "/foo");
            // }

            let pattern = tree::router_mount_pattern(&route);
            if let Some(&pos) = positions.get(&pattern) {
                let existing = merged[pos].clone();
                merged[pos] = Self::merge_router_routes(&existing, &route)?;
            } else {
                positions.insert(pattern, merged.len());
                merged.push(route);
            }
        }

        Ok(merged)
    }

    fn merge_router_routes(existing: &Route, new: &Route) -> Result<Route> {
        let existing_router = existing
            .router()
            .expect("existing route should be a nested router");
        let new_router = new.router().expect("new route should be a nested router");

        debug!(
            path = %existing.url(),
            existing_app = ?existing_router.app_name,
            new_app = ?new_router.app_name,
            "merging nested routers mounted at the same path",
        );

        let mut combined = Vec::with_capacity(existing_router.urls.len() + new_router.urls.len());
        combined.extend(
            existing_router
                .urls
                .iter()
                .cloned()
                .map(|r| r.with_app_name_if_unset(existing_router.app_name.clone())),
        );

        combined.extend(
            new_router
                .urls
                .iter()
                .cloned()
                .map(|r| r.with_app_name_if_unset(new_router.app_name.clone())),
        );

        let merged_router = Router::try_with_urls(combined)?;

        // setting the router's url to that of the existing route is done purely
        // for deterministic purposes. This should have no side-effect since we
        // match against the normalized url
        Ok(Route::with_router(&existing.url(), merged_router))
    }

    pub(crate) fn set_app_name(&mut self, app_name: AppName) {
        self.app_name = Some(app_name);
    }

    async fn route(&self, mut request: Request, request_path: &str) -> Result<Response> {
        debug!("Routing request to {}", request_path);

        if let Some(result) = self.get_handler(request_path) {
            let mut path_params = PathParams::new();
            for (key, value) in &result.params {
                path_params.insert(key.clone(), value.clone());
            }
            request.extensions_mut().insert(path_params);
            if let Some(app_name) = result.app_name {
                request.extensions_mut().insert(app_name);
            }
            if let Some(name) = result.name {
                request.extensions_mut().insert(name);
            }
            result.handler.handle(request).await
        } else {
            debug!("Not found: {}", request_path);
            Err(Error::from(NotFound::router()))
        }
    }

    fn get_handler(&self, request_path: &str) -> Option<HandlerFound<'_>> {
        let m = self.route_tree.at(request_path)?;

        let (route_index, remaining_path) = match m.value {
            Entry::Handler(idx) => (*idx, String::new()),
            Entry::Router(idx) => {
                let remaining = match m.params.get(tree::NESTED_ROUTER_PARAM) {
                    Some(rest) => AbsolutePath::new(rest),
                    None => AbsolutePath::root(),
                };
                (*idx, remaining.into())
            }
        };

        let params: Vec<(String, String)> = m
            .params
            .iter()
            .filter(|(key, _)| *key != tree::NESTED_ROUTER_PARAM)
            .map(|(k, v)| (k.to_owned(), v.to_owned()))
            .collect();

        Self::route_to_handler(self, route_index, &remaining_path, &params)
    }

    fn route_to_handler<'a>(
        router: &'a Router,
        route_index: usize,
        remaining_path: &str,
        params: &[(String, String)],
    ) -> Option<HandlerFound<'a>> {
        let route = &router.urls[route_index];

        match &route.view {
            RouteInner::Handler(handler) => Some(HandlerFound {
                handler: &**handler,
                app_name: route.app_name.clone().or_else(|| router.app_name.clone()),
                name: route.name.clone(),
                params: params.to_vec(),
            }),
            RouteInner::Router(nested_router) => {
                nested_router.get_handler(remaining_path).map(|mut found| {
                    found.app_name = found
                        .app_name
                        .or_else(|| route.app_name.clone())
                        .or_else(|| router.app_name.clone());

                    let mut combined = params.to_vec();
                    combined.extend(found.params);
                    found.params = combined;
                    found
                })
            }
            #[cfg(feature = "openapi")]
            RouteInner::ApiHandler(handler) => {
                let handler: &(dyn BoxRequestHandler + Send + Sync) = &**handler;
                Some(HandlerFound {
                    handler,
                    app_name: route.app_name.clone().or_else(|| router.app_name.clone()),
                    name: route.name.clone(),
                    params: params.to_vec(),
                })
            }
        }
    }

    pub(crate) fn has_route(&self, request_path: &str) -> bool {
        self.get_handler(request_path).is_some()
    }

    /// Handle a request.
    ///
    /// This method is called by the [`CotApp`](crate::App) to handle
    /// a request.
    ///
    /// # Errors
    ///
    /// This method re-throws any errors that occur in the request handler.
    pub async fn handle(&self, request: Request) -> Result<Response> {
        let path = request.uri().path().to_owned();
        self.route(request, &path).await
    }

    /// Generates a URL for a view using its name.
    ///
    /// Instead of using this method directly, consider using the
    /// [`reverse!`](crate::reverse) macro which provides much more ergonomic
    /// way to call this.
    ///
    /// The `app_name` parameter specifies the name of the app that the view
    /// should be found in. If it is `None`, the view is searched for across all
    /// registered apps.
    ///
    /// # Errors
    ///
    /// This method returns an error if the view name is not found.
    ///
    /// This method returns an error if the URL cannot be generated because of
    /// missing parameters.
    pub fn reverse(
        &self,
        app_name: Option<&str>,
        name: &str,
        params: &ReverseParamMap,
    ) -> Result<String> {
        Ok(self
            .reverse_option(app_name, name, params)?
            .ok_or_else(|| NoViewToReverse {
                app_name: app_name.map(ToOwned::to_owned),
                view_name: name.to_owned(),
            })?)
    }

    /// Generates a URL for a view using its name.
    ///
    /// The `app_name` parameter specifies the name of the app that the view
    /// should be found in. If it is `None`, the view is searched for across all
    /// registered apps.
    ///
    /// It returns [`None`] if the view name is not found.
    ///
    /// # Errors
    ///
    /// This method returns an error if the URL cannot be generated because of
    /// missing parameters.
    pub fn reverse_option(
        &self,
        app_name: Option<&str>,
        name: &str,
        params: &ReverseParamMap,
    ) -> Result<Option<String>> {
        if app_name.is_none()
            || self.app_name.is_none()
            || app_name == self.app_name.as_ref().map(|name| name.0.as_str())
        {
            self.reverse_option_impl(app_name, name, params)
        } else {
            Ok(None)
        }
    }

    fn reverse_option_impl(
        &self,
        app_name: Option<&str>,
        name: &str,
        params: &ReverseParamMap,
    ) -> Result<Option<String>> {
        if let Some(candidates) = self.names.get(&RouteName(String::from(name))) {
            let matched = candidates
                .iter()
                .find(|(candidate_app, _)| candidate_app.as_ref().map(|a| a.0.as_str()) == app_name)
                .or_else(|| {
                    candidates
                        .iter()
                        .find(|(candidate_app, _)| candidate_app.is_none())
                });
            if let Some((_, matcher)) = matched {
                // fast path: we found the route with the provided name in this
                // router
                return Ok(Some(matcher.reverse(params)?));
            }
        }

        // slow path: the route may exist in the nested routers. we search
        // through recursively to find it.
        for route in &self.urls {
            if let RouteInner::Router(router) = &route.view
                && Self::app_name_matches(app_name, route.app_name.as_ref())
                && let Some(url) = router.reverse_option(app_name, name, params)?
            {
                let prefix = AbsolutePath::new(route.url.reverse(params)?);
                let suffix = AbsolutePath::new(url);

                // we are in a sub-router, and if its parent does not end in a
                // trailing slash (eg. `foo`) and the found route is the
                // sub-router's root (`/`), then we can safely assume that
                // the trailing-slash version (eg. `foo/`) does not exist.
                // We return its parent and must not join
                let combined = if !prefix.as_str().ends_with('/') && suffix.as_str() == "/" {
                    prefix
                } else {
                    prefix.join(&suffix)
                };
                return Ok(Some(combined.into()));
            }
        }
        Ok(None)
    }

    fn app_name_matches(requested: Option<&str>, candidate: Option<&AppName>) -> bool {
        requested.is_none() || candidate.is_none() || candidate.map(|a| a.0.as_str()) == requested
    }

    /// Get the routes in this router.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::{Route, Router};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     unimplemented!()
    /// }
    ///
    /// let router = Router::with_urls([Route::with_handler_and_name("/", home, "home")]);
    /// assert_eq!(router.routes().len(), 1);
    /// ```
    #[must_use]
    pub fn routes(&self) -> &[Route] {
        &self.urls
    }

    /// Check if this router is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::{Route, Router};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     unimplemented!()
    /// }
    ///
    /// let router = Router::empty();
    /// assert!(router.is_empty());
    ///
    /// let router = Router::with_urls([Route::with_handler_and_name("/", home, "home")]);
    /// assert!(!router.is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.urls.is_empty()
    }

    /// Returns the OpenAPI paths for the router.
    ///
    /// This might be useful if you want to manually serve the generated OpenAPI
    /// specs.
    ///
    /// # Panics
    ///
    /// Panics if invalid schemas are generated. This should not happen in
    /// normal operation, but if it does, it indicates a bug in the
    /// [`schemars`](https://docs.rs/schemars/latest/schemars/) library
    /// or in the way the OpenAPI specs are generated.
    #[cfg(feature = "openapi")]
    #[must_use]
    pub fn as_api(&self) -> aide::openapi::OpenApi {
        let mut paths = aide::openapi::Paths::default();
        let mut schema_generator =
            schemars::SchemaGenerator::new(schemars::generate::SchemaSettings::openapi3());

        self.as_openapi_impl(
            &AbsolutePath::root(),
            &[],
            &mut paths,
            &mut schema_generator,
        );

        let component_schemas = schema_generator
            .take_definitions(true)
            .into_iter()
            .map(|(name, json_schema)| {
                (
                    name,
                    aide::openapi::SchemaObject {
                        json_schema: schemars::Schema::try_from(json_schema).expect(
                            "SchemaGenerator::take_definitions should return valid schemas",
                        ),
                        example: None,
                        external_docs: None,
                    },
                )
            })
            .collect();
        aide::openapi::OpenApi {
            paths: Some(paths),
            components: Some(aide::openapi::Components {
                schemas: component_schemas,
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    #[cfg(feature = "openapi")]
    fn as_openapi_impl(
        &self,
        url: &AbsolutePath,
        param_names: &[&str],
        paths: &mut aide::openapi::Paths,
        schema_generator: &mut schemars::SchemaGenerator,
    ) {
        for route in &self.urls {
            Self::route_as_openapi(route, param_names, paths, schema_generator, url);
        }
    }

    #[cfg(feature = "openapi")]
    fn route_as_openapi(
        route: &Route,
        param_names: &[&str],
        paths: &mut aide::openapi::Paths,
        schema_generator: &mut schemars::SchemaGenerator,
        url: &AbsolutePath,
    ) {
        match &route.view {
            RouteInner::Router(router) => {
                let mut params = Vec::from(param_names);
                params.extend(route.url.param_names());

                let url = url.join(&AbsolutePath::new(route.url()));

                router.as_openapi_impl(&url, &params, paths, schema_generator);
            }
            RouteInner::ApiHandler(handler) => {
                let mut params = Vec::from(param_names);
                params.extend(route.url.param_names());

                let url = url.join(&AbsolutePath::new(route.url()));

                let mut route_context = crate::openapi::RouteContext::new();
                route_context.param_names = &params;

                paths.paths.insert(
                    url.into(),
                    aide::openapi::ReferenceOr::Item(
                        handler.as_api_route(&route_context, schema_generator),
                    ),
                );
            }
            RouteInner::Handler(_) => {}
        }
    }
}

impl Default for Router {
    fn default() -> Self {
        Self::empty()
    }
}

#[derive(Debug, thiserror::Error)]
#[error("failed to reverse route `{view_name}` due to view not existing")]
struct NoViewToReverse {
    app_name: Option<String>,
    view_name: String,
}
impl_into_cot_error!(NoViewToReverse);

const ERROR_PREFIX: &str = "route conflict error:";
#[derive(Debug, thiserror::Error)]
enum RouteConflictError {
    #[error(
        "{ERROR_PREFIX} duplicate route: `{new}` conflicts with an already registered handler route `{existing}` \
         (both fully match the same path)"
    )]
    DuplicateHandler { existing: String, new: String },

    #[error(
        "{ERROR_PREFIX} duplicate nested router: `{new}` conflicts with an already registered \
         nested router mounted at `{existing}`"
    )]
    DuplicateRouter { existing: String, new: String },

    #[error(
        "{ERROR_PREFIX} duplicate route name: `{name}` is registered at both `{existing}` and `{new}`; route names \
     must be unique within the same app"
    )]
    DuplicateRouteName {
        name: String,
        existing: String,
        new: String,
    },

    #[error(
        "{ERROR_PREFIX} conflicting route parameters: `{existing}` uses `{{{existing_name}}}` but `{new}` uses \
         `{{{new_name}}}` at the same position in the path; both routes must bind the same \
         parameter name there, since only one value can be captured at that position"
    )]
    ConflictingParamName {
        existing: String,
        existing_name: String,
        new: String,
        new_name: String,
    },

    #[error(
        "{ERROR_PREFIX} conflicting wildcard parameters: `{existing}` uses `{{*{existing_name}}}` but `{new}` \
         uses `{{*{new_name}}}` at the same position in the path"
    )]
    ConflictingWildcardName {
        existing: String,
        existing_name: String,
        new: String,
        new_name: String,
    },

    #[error(
        "{ERROR_PREFIX} duplicate wildcard route: `{new}` conflicts with an already-registered \
         wildcard route `{existing}`"
    )]
    DuplicateWildcard { existing: String, new: String },
    #[error("{ERROR_PREFIX} error while inserting route")]
    RouteInsert(#[from] matchit::InsertError),
}
impl_into_cot_error!(RouteConflictError);

#[derive(Debug)]
struct HandlerFound<'a> {
    #[debug("handler(...)")]
    handler: &'a (dyn BoxRequestHandler + Send + Sync),
    app_name: Option<AppName>,
    name: Option<RouteName>,
    params: Vec<(String, String)>,
}

/// A service that routes requests to their respective views.
///
/// This is mostly an internal service used by the [`CotApp`](crate::App) to
/// route requests to their respective views with an interface that is
/// compatible with the [`tower::Service`] trait.
#[derive(Debug, Clone)]
pub struct RouterService {
    router: Arc<Router>,
}

impl RouterService {
    /// Create a new router service.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::{Route, Router, RouterService};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     unimplemented!()
    /// }
    ///
    /// let router = Router::with_urls([Route::with_handler_and_name("/", home, "home")]);
    /// let service = RouterService::new(Arc::new(router));
    /// ```
    #[must_use]
    pub fn new(router: Arc<Router>) -> Self {
        Self { router }
    }
}

impl tower::Service<Request> for RouterService {
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response>> + Send>>;
    type Response = Response;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: Request) -> Self::Future {
        let router = self.router.clone();
        Box::pin(async move { router.handle(req).await })
    }
}

// used in the reverse! macro; not part of public API
#[doc(hidden)]
#[must_use]
pub fn split_view_name(view_name: &str) -> (Option<&str>, &str) {
    let colon_pos = view_name.find(':');
    if let Some(colon_pos) = colon_pos {
        let app_name = &view_name[..colon_pos];
        let view_name = &view_name[colon_pos + 1..];
        (Some(app_name), view_name)
    } else {
        (None, view_name)
    }
}

// used in the reverse! macro; not part of public API
#[doc(hidden)]
#[must_use]
pub fn reverse_with_query(url: String, query_params: &[(&str, String)]) -> String {
    if query_params.is_empty() {
        return url;
    }

    let mut serializer = form_urlencoded::Serializer::new(String::new());
    for (key, value) in query_params {
        serializer.append_pair(key, value);
    }

    format!("{url}?{}", serializer.finish())
}

/// A route that can be used to route requests to their respective views.
///
/// Non-empty route paths may omit the leading slash. Cot normalizes them by
/// prepending `/`, so `"home"` and `"/home"` define the same route.
///
/// # Examples
///
/// ```
/// use cot::request::Request;
/// use cot::response::Response;
/// use cot::router::{Route, Router};
///
/// async fn home(request: Request) -> cot::Result<Response> {
///     unimplemented!()
/// }
///
/// let router = Router::with_urls([Route::with_handler_and_name("/", home, "home")]);
/// ```
#[derive(Debug, Clone)]
pub struct Route {
    url: Arc<PathMatcher>,
    view: RouteInner,
    name: Option<RouteName>,
    app_name: Option<AppName>,
}

impl Route {
    /// Create a new route with the given handler.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::{Route, Router};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     // ...
    /// #     unimplemented!()
    /// }
    ///
    /// let route = Route::with_handler("home", home);
    /// assert_eq!(route.url(), "/home");
    /// ```
    #[must_use]
    pub fn with_handler<HandlerParams, H>(url: &str, handler: H) -> Self
    where
        HandlerParams: 'static,
        H: RequestHandler<HandlerParams> + Send + Sync + 'static,
    {
        Self {
            url: Arc::new(PathMatcher::new(url)),
            view: RouteInner::Handler(Arc::new(into_box_request_handler(handler))),
            name: None,
            app_name: None,
        }
    }

    /// Create a new route with the given handler for inclusion in the OpenAPI
    /// specifications.
    ///
    /// See [`crate::openapi`] module documentation for more details on how to
    /// generate OpenAPI specifications automatically.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::method::openapi::api_get;
    /// use cot::router::{Route, Router};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     // ...
    /// #     unimplemented!()
    /// }
    ///
    /// let route = Route::with_api_handler("/", api_get(home));
    /// ```
    #[must_use]
    #[cfg(feature = "openapi")]
    pub fn with_api_handler<HandlerParams, H>(url: &str, handler: H) -> Self
    where
        HandlerParams: 'static,
        H: RequestHandler<HandlerParams> + crate::openapi::AsApiRoute + Send + Sync + 'static,
    {
        Self {
            url: Arc::new(PathMatcher::new(url)),
            view: RouteInner::ApiHandler(Arc::new(
                crate::openapi::into_box_api_endpoint_request_handler(handler),
            )),
            name: None,
            app_name: None,
        }
    }

    /// Create a new route with the given handler and name.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::method::openapi::api_get;
    /// use cot::router::{Route, Router};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     // ...
    /// #     unimplemented!()
    /// }
    ///
    /// let route = Route::with_handler_and_name("/", api_get(home), "home");
    /// ```
    #[must_use]
    pub fn with_handler_and_name<N, HandlerParams, H>(url: &str, handler: H, name: N) -> Self
    where
        N: Into<String>,
        HandlerParams: 'static,
        H: RequestHandler<HandlerParams> + Send + Sync + 'static,
    {
        Self {
            url: Arc::new(PathMatcher::new(url)),
            view: RouteInner::Handler(Arc::new(into_box_request_handler(handler))),
            name: Some(RouteName(name.into())),
            app_name: None,
        }
    }

    /// Create a new route with the given handler and name for inclusion in the
    /// OpenAPI specs.
    ///
    /// See [`crate::openapi`] module documentation for more details on how to
    /// generate OpenAPI specs automatically.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::method::openapi::api_post;
    /// use cot::router::{Route, Router};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     // ...
    /// #     unimplemented!()
    /// }
    ///
    /// let route = Route::with_api_handler_and_name("/", api_post(home), "home");
    /// ```
    #[must_use]
    #[cfg(feature = "openapi")]
    pub fn with_api_handler_and_name<N, HandlerParams, H>(url: &str, handler: H, name: N) -> Self
    where
        N: Into<String>,
        HandlerParams: 'static,
        H: RequestHandler<HandlerParams> + crate::openapi::AsApiRoute + Send + Sync + 'static,
    {
        Self {
            url: Arc::new(PathMatcher::new(url)),
            view: RouteInner::ApiHandler(Arc::new(
                crate::openapi::into_box_api_endpoint_request_handler(handler),
            )),
            name: Some(RouteName(name.into())),
            app_name: None,
        }
    }

    /// Create a new route with the given router.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::{Route, Router};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     unimplemented!()
    /// }
    ///
    /// let router = Router::with_urls([Route::with_handler_and_name("/", home, "home")]);
    /// let route = Route::with_router("/", router);
    /// ```
    #[must_use]
    pub fn with_router(url: &str, router: Router) -> Self {
        Self {
            url: Arc::new(PathMatcher::new(url)),
            view: RouteInner::Router(Arc::new(router)),
            name: None,
            app_name: None,
        }
    }

    #[must_use]
    fn with_app_name_if_unset(mut self, app_name: Option<AppName>) -> Self {
        if self.app_name.is_none() {
            self.app_name = app_name;
        }
        self
    }

    /// Get the URL for this route.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::{Route, Router};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     unimplemented!()
    /// }
    ///
    /// let route = Route::with_handler("/test", home);
    /// assert_eq!(route.url(), "/test");
    /// ```
    #[must_use]
    pub fn url(&self) -> String {
        self.url.to_string()
    }

    /// Get the name of this route, if it was created with the
    /// [`Self::with_handler_and_name`] function.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::Request;
    /// use cot::response::Response;
    /// use cot::router::{Route, Router};
    ///
    /// async fn home(request: Request) -> cot::Result<Response> {
    ///     unimplemented!()
    /// }
    ///
    /// let route = Route::with_handler_and_name("/", home, "home");
    /// assert_eq!(route.name(), Some("home"));
    /// ```
    #[must_use]
    pub fn name(&self) -> Option<&str> {
        self.name.as_ref().map(|name| name.0.as_str())
    }

    #[must_use]
    pub(crate) fn app_name(&self) -> Option<&AppName> {
        self.app_name.as_ref()
    }

    #[must_use]
    pub(crate) fn kind(&self) -> RouteKind {
        match &self.view {
            RouteInner::Handler(_) => RouteKind::Handler,
            RouteInner::Router(_) => RouteKind::Router,
            #[cfg(feature = "openapi")]
            RouteInner::ApiHandler(_) => RouteKind::Handler,
        }
    }

    #[must_use]
    pub(crate) fn router(&self) -> Option<Arc<Router>> {
        match &self.view {
            RouteInner::Router(router) => Some(router.clone()),
            RouteInner::Handler(_) => None,
            #[cfg(feature = "openapi")]
            RouteInner::ApiHandler(_) => None,
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum RouteKind {
    Handler,
    Router,
}

#[derive(Clone)]
enum RouteInner {
    Handler(Arc<dyn BoxRequestHandler + Send + Sync>),
    Router(Arc<Router>),
    #[cfg(feature = "openapi")]
    ApiHandler(Arc<dyn crate::openapi::BoxApiEndpointRequestHandler + Send + Sync>),
}

/// Get a URL for a view by its registered name and given params.
///
/// If the view name has two parts separated by a colon, the first part is
/// considered the app name. If the app name is not provided, the app name of
/// the request is used. This means that if you don't specify the `app_name`,
/// this macro will only return URLs for views in the same app as the current
/// request handler.
///
/// # Return value
///
/// Returns a [`cot::Result<String>`] that contains the URL for the view. You
/// will typically want to append `?` to the macro call to get the URL.
///
/// # Query parameters
///
/// Path parameters are passed as `key = value` pairs right after the view name.
/// Query parameters are passed in a `query: { ... }` block and are appended to
/// the generated URL as a percent-encoded query string. The values only need to
/// implement [`ToString`], just like path parameters do.
///
/// The query block must come after any path parameters. For example,
/// `reverse!(request, "article", id = 5, query: { page = 2, sort = "new" })`
/// generates `/articles/5?page=2&sort=new` for a route at `/articles/{id}`.
/// An empty query block leaves the URL unchanged.
///
/// # Examples
///
/// ```
/// use cot::html::Html;
/// use cot::project::RegisterAppsContext;
/// use cot::request::Request;
/// use cot::router::{Route, Router};
/// use cot::{App, AppBuilder, Project, StatusCode, reverse};
///
/// async fn home(request: Request) -> cot::Result<Html> {
///     // any of below two lines returns the same:
///     let url = reverse!(request, "home")?;
///     let url = reverse!(request, "my_custom_app:home")?;
///
///     // with query parameters, this returns `/?page=2&search=cot`:
///     let url = reverse!(request, "home", query: { page = 2, search = "cot" })?;
///
///     Ok(Html::new(format!(
///         "Hello! The URL for this view is: {}",
///         url
///     )))
/// }
///
/// let router = Router::with_urls([Route::with_handler_and_name("/", home, "home")]);
///
/// struct MyApp;
///
/// impl App for MyApp {
///     fn name(&self) -> &'static str {
///         "my_custom_app"
///     }
///
///     fn router(&self) -> Router {
///         Router::with_urls([Route::with_handler_and_name("/", home, "home")])
///     }
/// }
///
/// struct MyProject;
///
/// impl Project for MyProject {
///     fn register_apps(&self, apps: &mut AppBuilder, context: &RegisterAppsContext) {
///         apps.register_with_views(MyApp, "");
///     }
/// }
/// ```
#[macro_export]
macro_rules! reverse {
    // Once all path parameters have been collected, only a query block or the
    // end of the invocation is allowed.
    (@parse $request:expr, $view_name:literal, [$($key:ident = $value:expr,)*],
        $(query: { $($query_key:ident = $query_value:expr),* $(,)? } $(,)?)?
    ) => {{
        #[allow(
            clippy::allow_attributes,
            unused_imports,
            reason = "allow using either `Request` or `Urls` objects"
        )]
        use $crate::request::RequestExt;
        let (app_name, view_name) = $crate::router::split_view_name($view_name);
        let app_name = app_name.or_else(|| $request.app_name());
        $request
            .router()
            .reverse(app_name, view_name, &$crate::reverse_param_map!($($key = $value),*))
            .map(|url| $crate::router::reverse_with_query(
                url,
                &[$( $( (stringify!($query_key), ::std::string::ToString::to_string(&$query_value)) ),* )?],
            ))
    }};
    // Consume one path parameter per expansion so `query = value` and
    // `query: { ... }` can be distinguished without an ambiguous repetition.
    (@parse $request:expr, $view_name:literal, [$($params:tt)*],
        $key:ident = $value:expr $(, $($rest:tt)*)?
    ) => {
        $crate::reverse!(@parse $request, $view_name,
            [$($params)* $key = $value,], $($($rest)*)?)
    };
    ($request:expr, $view_name:literal $(, $($params:tt)*)?) => {
        $crate::reverse!(@parse $request, $view_name, [], $($($params)*)?)
    };
}

/// A helper structure to allow reversing URLs from a request handler.
///
/// This is mainly useful as an extractor to allow reversing URLs without
/// access to a full [`Request`] object.
///
/// # Examples
///
/// ```
/// use cot::html::Html;
/// use cot::router::{Route, Router, Urls};
/// use cot::test::TestRequestBuilder;
/// use cot::{RequestHandler, reverse};
///
/// async fn my_handler(urls: Urls) -> cot::Result<Html> {
///     let url = reverse!(urls, "home")?;
///     Ok(Html::new(format!("{url}")))
/// }
///
/// # #[tokio::main]
/// # async fn main() -> cot::Result<()> {
/// let router = Router::with_urls([Route::with_handler_and_name("/", my_handler, "home")]);
/// let request = TestRequestBuilder::get("/").router(router).build();
///
/// assert_eq!(
///     my_handler
///         .handle(request)
///         .await?
///         .into_body()
///         .into_bytes()
///         .await?,
///     "/"
/// );
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Urls {
    app_name: Option<String>,
    router: Arc<Router>,
}

impl Urls {
    /// Create a new `Urls` object from a [`Request`] object.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::html::Html;
    /// use cot::request::Request;
    /// use cot::response::{Response, ResponseExt};
    /// use cot::router::Urls;
    /// use cot::{Body, StatusCode, reverse};
    ///
    /// async fn my_handler(request: Request) -> cot::Result<Html> {
    ///     let urls = Urls::from_request(&request);
    ///     let url = reverse!(urls, "home")?;
    ///     Ok(Html::new(format!(
    ///         "Hello! The URL for this view is: {}",
    ///         url
    ///     )))
    /// }
    /// ```
    pub fn from_request(request: &Request) -> Self {
        Self {
            app_name: request.app_name().map(ToOwned::to_owned),
            router: Arc::clone(request.router()),
        }
    }

    pub(crate) fn from_parts(request_head: &RequestHead) -> Self {
        Self {
            app_name: request_head.app_name().map(ToOwned::to_owned),
            router: Arc::clone(request_head.router()),
        }
    }

    /// Get the app name the current route belongs to, or [`None`] if the
    /// request is not routed.
    ///
    /// This is mainly useful for providing context to reverse redirects, where
    /// you want to redirect to a route in the same app.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::{Request, RequestExt};
    /// use cot::response::Response;
    /// use cot::router::Urls;
    ///
    /// async fn my_handler(urls: Urls) -> cot::Result<Response> {
    ///     let app_name = urls.app_name();
    ///     // ... do something with the app name
    ///     # unimplemented!()
    /// }
    /// ```
    #[must_use]
    pub fn app_name(&self) -> Option<&str> {
        self.app_name.as_deref()
    }

    /// Get the router.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::request::{Request, RequestExt};
    /// use cot::response::Response;
    /// use cot::router::Urls;
    ///
    /// async fn my_handler(urls: Urls) -> cot::Result<Response> {
    ///     let router = urls.router();
    ///     // ... do something with the router
    ///     # unimplemented!()
    /// }
    /// ```
    #[must_use]
    pub fn router(&self) -> &Router {
        &self.router
    }
}

impl Debug for RouteInner {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match &self {
            RouteInner::Handler(_) => f.debug_tuple("Handler").field(&"handler(...)").finish(),
            RouteInner::Router(router) => f.debug_tuple("Router").field(router).finish(),
            #[cfg(feature = "openapi")]
            RouteInner::ApiHandler(_) => {
                f.debug_tuple("ApiHandler").field(&"handler(...)").finish()
            }
        }
    }
}

impl From<&ProjectContext> for Urls {
    fn from(ctx: &ProjectContext) -> Self {
        Self {
            app_name: None,
            router: Arc::clone(ctx.router()),
        }
    }
}

impl From<&mut ProjectContext> for Urls {
    fn from(ctx: &mut ProjectContext) -> Self {
        Self::from(&*ctx)
    }
}

/// Get a URL for a view by its registered name and given params and return a
/// response with a redirect.
///
/// This macro is a shorthand for creating a response with a redirect to a URL
/// generated by the [`reverse!`] macro. It accepts the same path parameters and
/// optional `query: { ... }` block.
///
/// # Return value
///
/// Returns a [`cot::Result<Response>`] that contains the URL for
/// the view. You will typically want to append `?` to the macro call to get the
/// [`Response`] object.
///
/// # Examples
///
/// ```
/// use cot::request::Request;
/// use cot::response::Response;
/// use cot::reverse_redirect;
/// use cot::router::{Route, Router};
///
/// async fn infinite_loop(request: Request) -> cot::Result<Response> {
///     Ok(reverse_redirect!(request, "home", query: { page = 2 })?)
/// }
///
/// let router = Router::with_urls([Route::with_handler_and_name("/", infinite_loop, "home")]);
/// ```
#[macro_export]
macro_rules! reverse_redirect {
    ($($args:tt)*) => {
        $crate::reverse!($($args)*).map(|url|
            $crate::response::IntoResponse::into_response($crate::response::Redirect::new(url))
                .expect("Failed to build response")
        )
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::StatusCode;
    use crate::html::Html;
    use crate::request::Request;
    use crate::response::{IntoResponse, Response};
    use crate::test::TestRequestBuilder;

    struct MockHandler;

    impl RequestHandler for MockHandler {
        #[expect(clippy::unused_async_trait_impl)]
        async fn handle(&self, _request: Request) -> Result<Response> {
            Html::new("OK").into_response()
        }
    }

    #[cfg(feature = "openapi")]
    impl crate::openapi::AsApiRoute for MockHandler {
        fn as_api_route(
            &self,
            _route_context: &cot::openapi::RouteContext<'_>,
            _schema_generator: &mut schemars::SchemaGenerator,
        ) -> aide::openapi::PathItem {
            aide::openapi::PathItem::default()
        }
    }

    fn assert_params(mut actual: Vec<(String, String)>, expected: &[(&str, &str)]) {
        let mut expected = expected
            .iter()
            .map(|(key, value)| ((*key).to_string(), (*value).to_string()))
            .collect::<Vec<_>>();
        actual.sort();
        expected.sort();
        assert_eq!(actual, expected);
    }

    #[test]
    fn route_inner_debug() {
        let route = Route::with_handler("/test", MockHandler);
        assert!(format!("{route:?}").contains("Handler(\"handler(...)\")"));

        let route = Route::with_router("/test", Router::empty());
        assert!(format!("{route:?}").contains("Router(Router {"));

        #[cfg(feature = "openapi")]
        {
            let route = Route::with_api_handler("/test", MockHandler);
            assert!(format!("{route:?}").contains("ApiHandler(\"handler(...)\")"));
        }
    }

    #[test]
    fn route_kind() {
        let handler_route = Route::with_handler("/test", MockHandler);
        assert_eq!(handler_route.kind(), RouteKind::Handler);

        let router_route = Route::with_router("/test", Router::empty());
        assert_eq!(router_route.kind(), RouteKind::Router);

        #[cfg(feature = "openapi")]
        {
            let api_route = Route::with_api_handler("/test", MockHandler);
            assert_eq!(api_route.kind(), RouteKind::Handler);
        }
    }

    #[test]
    fn route_router() {
        let router = Router::empty();
        let route = Route::with_router("/test", router.clone());
        assert!(route.router().is_some());

        let route = Route::with_handler("/test", MockHandler);
        assert!(route.router().is_none());

        #[cfg(feature = "openapi")]
        {
            let route = Route::with_api_handler("/test", MockHandler);
            assert!(route.router().is_none());
        }
    }

    #[test]
    fn route_with_handler() {
        let route = Route::with_handler("/test", MockHandler);
        assert_eq!(route.url.to_string(), "/test");
    }

    #[test]
    fn route_with_handler_and_params() {
        let route = Route::with_handler("/test/{id}", MockHandler);
        assert_eq!(route.url.to_string(), "/test/{id}");
    }

    #[test]
    fn route_with_handler_and_name() {
        let route = Route::with_handler_and_name("/test", MockHandler, "test");
        assert_eq!(route.url.to_string(), "/test");
        assert_eq!(route.name, Some(RouteName("test".to_string())));
    }

    #[test]
    fn route_with_router() {
        let sub_route = Route::with_handler("/sub", MockHandler);
        let sub_router = Router::with_urls(vec![sub_route]);
        let route = Route::with_router("/test", sub_router);
        assert_eq!(route.url.to_string(), "/test");
    }

    #[test]
    fn router_is_empty() {
        let router = Router::with_urls(vec![]);
        assert!(router.is_empty());
    }

    #[test]
    fn router_routes() {
        let route = Route::with_handler("/test", MockHandler);
        let router = Router::with_urls(vec![route.clone()]);
        assert_eq!(router.routes().len(), 1);
    }

    #[test]
    fn router_empty_returns_no_handler() {
        let router = Router::empty();
        assert!(router.get_handler("/").is_none());
    }

    #[cot::test]
    async fn router_route() {
        let route = Route::with_handler("/test", MockHandler);
        let router = Router::with_urls(vec![route.clone()]);
        let response = router.route(test_request(), "/test").await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[cot::test]
    async fn router_route_without_leading_slash() {
        let route = Route::with_handler_and_name("test", MockHandler, "test");
        assert_eq!(route.url(), "/test");

        let router = Router::with_urls(vec![route]);
        let response = router.route(test_request(), "/test").await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        let url = router
            .reverse(None, "test", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/test");
    }

    #[cot::test]
    async fn router_handle() {
        let route = Route::with_handler("/test", MockHandler);
        let router = Router::with_urls(vec![route.clone()]);
        let response = router.handle(test_request()).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[cot::test]
    async fn sub_router_handle() {
        let route_1 = Route::with_handler("/test", MockHandler);
        let sub_router_1 = Router::with_urls(vec![route_1.clone()]);
        let route_2 = Route::with_handler("/test", MockHandler);
        let sub_router_2 = Router::with_urls(vec![route_2.clone()]);

        let router = Router::with_urls(vec![
            Route::with_router("/", sub_router_1),
            Route::with_router("/sub", sub_router_2),
        ]);
        let response = router
            .handle(TestRequestBuilder::get("/sub/test").build())
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[test]
    fn router_no_param_route_matches_exact_path() {
        let router = Router::with_urls(vec![Route::with_handler_and_name(
            "/users",
            MockHandler,
            "users",
        )]);

        let found = router.get_handler("/users").unwrap();

        assert_eq!(found.name, Some(RouteName("users".to_string())));
        let expected: [(String, String); 0] = [];
        assert_eq!(found.params, expected);
    }

    #[test]
    fn router_no_param_route_rejects_different_path() {
        let router = Router::with_urls(vec![Route::with_handler_and_name(
            "/users",
            MockHandler,
            "users",
        )]);

        assert!(router.get_handler("/test").is_none());
    }

    #[test]
    fn router_routes_with_common_static_prefixes_match_independently() {
        let router = Router::with_urls(vec![
            Route::with_handler_and_name("/car", MockHandler, "car"),
            Route::with_handler_and_name("/cart", MockHandler, "cart"),
            Route::with_handler_and_name("/catalog", MockHandler, "catalog"),
        ]);

        assert_eq!(
            router.get_handler("/car").unwrap().name,
            Some(RouteName("car".to_string()))
        );
        assert_eq!(
            router.get_handler("/cart").unwrap().name,
            Some(RouteName("cart".to_string()))
        );
        assert_eq!(
            router.get_handler("/catalog").unwrap().name,
            Some(RouteName("catalog".to_string()))
        );
        assert!(router.get_handler("/cartographer").is_none());
    }

    #[test]
    fn router_param_route_captures_single_segment() {
        let router = Router::with_urls(vec![Route::with_handler_and_name(
            "/users/{id}",
            MockHandler,
            "user_detail",
        )]);

        let found = router.get_handler("/users/123").unwrap();

        assert_eq!(found.name, Some(RouteName("user_detail".to_string())));
        assert_params(found.params, &[("id", "123")]);
    }

    #[test]
    fn router_param_route_rejects_empty_segment() {
        let router = Router::with_urls(vec![Route::with_handler_and_name(
            "/users/{id}",
            MockHandler,
            "user_detail",
        )]);

        assert!(router.get_handler("/users/").is_none());
    }

    #[test]
    fn router_param_route_rejects_extra_path_for_handler() {
        let router = Router::with_urls(vec![Route::with_handler_and_name(
            "/users/{id}",
            MockHandler,
            "user_detail",
        )]);

        assert!(router.get_handler("/users/123/abc").is_none());
    }

    #[test]
    fn router_multiple_param_route_captures_all_params() {
        let router = Router::with_urls(vec![Route::with_handler_and_name(
            "/users/{id}/posts/{post_id}",
            MockHandler,
            "post_detail",
        )]);

        let found = router.get_handler("/users/123/posts/456").unwrap();

        assert_eq!(found.name, Some(RouteName("post_detail".to_string())));
        assert_params(found.params, &[("id", "123"), ("post_id", "456")]);
    }

    #[test]
    fn router_static_route_takes_priority_over_dynamic_route() {
        let router = Router::with_urls(vec![
            Route::with_handler_and_name("/users/{id}", MockHandler, "dynamic"),
            Route::with_handler_and_name("/users/new", MockHandler, "static"),
        ]);

        let found = router.get_handler("/users/new").unwrap();

        assert_eq!(found.name, Some(RouteName("static".to_string())));
    }

    #[test]
    fn router_single_pattern_multi_param_order_preserved() {
        let router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{model_name}/{pk}/edit/",
            MockHandler,
            "edit",
        )]);

        let found = router.get_handler("/database_user/1/edit/").unwrap();

        assert_eq!(
            found.params,
            vec![
                ("model_name".to_string(), "database_user".to_string()),
                ("pk".to_string(), "1".to_string()),
            ]
        );
    }

    #[test]
    fn router_wildcard_root() {
        let router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{*path}",
            MockHandler,
            "users",
        )]);

        let found = router.get_handler("/foo/bar").unwrap();

        assert_eq!(found.name, Some(RouteName("users".to_string())));
        assert_eq!(
            found.params,
            vec![("path".to_string(), "foo/bar".to_string())]
        );
    }

    #[test]
    fn router_wildcard_single_segment() {
        let router = Router::with_urls(vec![Route::with_handler_and_name(
            "/users/rand/{*path}",
            MockHandler,
            "users",
        )]);

        let found = router.get_handler("/users/rand/foo").unwrap();

        assert_eq!(found.name, Some(RouteName("users".to_string())));
        assert_eq!(found.params, vec![("path".to_string(), "foo".to_string())]);
    }

    #[test]
    fn router_wildcard_multi_segment() {
        let router = Router::with_urls(vec![Route::with_handler_and_name(
            "/users/rand/{*path}",
            MockHandler,
            "users",
        )]);

        let found = router.get_handler("/users/rand/foo/bar").unwrap();

        assert_eq!(found.name, Some(RouteName("users".to_string())));
        assert_eq!(
            found.params,
            vec![("path".to_string(), "foo/bar".to_string())]
        );
    }

    #[test]
    fn router_wildcard_empty_not_allowed() {
        let router = Router::with_urls(vec![Route::with_handler_and_name(
            "/users/rand/{*path}",
            MockHandler,
            "users",
        )]);

        assert!(router.get_handler("/users/rand").is_none());
    }

    #[test]
    fn router_wildcard_route_is_lower_priority_than_static_route() {
        let router = Router::with_urls(vec![
            Route::with_handler_and_name("/static/{*path}", MockHandler, "wildcard"),
            Route::with_handler_and_name("/static/index.html", MockHandler, "static"),
        ]);

        let found = router.get_handler("/static/index.html").unwrap();

        assert_eq!(found.name, Some(RouteName("static".to_string())));
    }

    #[test]
    fn router_root_mount_matches_root_path() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/",
            MockHandler,
            "index",
        )]);
        let router = Router::with_urls(vec![Route::with_router("", sub_router)]);

        let found = router.get_handler("/").unwrap();

        assert_eq!(found.name, Some(RouteName("index".to_string())));
    }

    #[test]
    fn router_exact_mount_match_routes_to_nested_root_not_empty_path() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/",
            MockHandler,
            "sub_index",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/api", sub_router)]);

        let found = router.get_handler("/api").unwrap();

        assert_eq!(found.name, Some(RouteName("sub_index".to_string())));
    }

    #[test]
    fn router_root_mounted_nested_router() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/inner",
            MockHandler,
            "inner",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/", sub_router)]);

        let found = router.get_handler("/inner").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));
    }

    #[test]
    fn router_root_mounted_nested_router_empty() {
        let sub_router =
            Router::with_urls(vec![Route::with_handler_and_name("", MockHandler, "inner")]);
        let router = Router::with_urls(vec![Route::with_router("/outer", sub_router)]);

        let found = router.get_handler("/outer").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));

        assert!(router.get_handler("/outer/").is_none());
        assert!(router.get_handler("outer/").is_none());
        assert!(router.get_handler("outer").is_none());

        let url = router
            .reverse(None, "inner", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/outer");
        assert!(router.has_route(&url));
    }

    #[test]
    fn router_root_mounted_nested_router_empty_and_root_without_slash() {
        let sub_router =
            Router::with_urls(vec![Route::with_handler_and_name("", MockHandler, "inner")]);
        // this should normalize to `/outer`
        let router = Router::with_urls(vec![Route::with_router("outer", sub_router)]);

        let found = router.get_handler("/outer").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));

        assert!(router.get_handler("/outer/").is_none());
        assert!(router.get_handler("outer/").is_none());
        assert!(router.get_handler("outer").is_none());

        let url = router
            .reverse(None, "inner", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/outer");
        assert!(router.has_route(&url));
    }

    #[test]
    fn router_root_mounted_nested_router_empty_root() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "inner",
            MockHandler,
            "inner",
        )]);
        let router = Router::with_urls(vec![Route::with_router("", sub_router)]);

        let found = router.get_handler("/inner").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));
        // remaining path becomes "/inner/", sub-router only registered "/inner"
        assert!(router.get_handler("/inner/").is_none());
        assert!(router.get_handler("inner").is_none());
        assert!(router.get_handler("inner/").is_none());

        let url = router
            .reverse(None, "inner", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/inner");
        assert!(router.has_route(&url));
    }

    #[test]
    fn router_root_mounted_nested_router_empty_root_empty_nested() {
        let sub_router =
            Router::with_urls(vec![Route::with_handler_and_name("", MockHandler, "inner")]);
        let router = Router::with_urls(vec![Route::with_router("", sub_router)]);

        // exact match at the mount point, remaining defaults to root "/"
        let found = router.get_handler("/").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));

        // wildcard sentinel capturing a literal "/", so this is legal
        let found = router.get_handler("//").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));

        let url = router
            .reverse(None, "inner", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/");
        assert!(router.has_route(&url));
    }

    #[test]
    fn router_root_mounted_nested_router_slash_root_slash_nested() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/",
            MockHandler,
            "inner",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/", sub_router)]);

        let found = router.get_handler("/").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));

        let found = router.get_handler("//").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));

        let url = router
            .reverse(None, "inner", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/");
        assert!(router.has_route(&url));
    }

    #[test]
    fn router_root_mounted_nested_router_slash_root_empty_nested() {
        let sub_router =
            Router::with_urls(vec![Route::with_handler_and_name("", MockHandler, "inner")]);
        let router = Router::with_urls(vec![Route::with_router("/", sub_router)]);

        let found = router.get_handler("/").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));

        let found = router.get_handler("//").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));

        let url = router
            .reverse(None, "inner", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/");
        assert!(router.has_route(&url));
    }

    #[test]
    fn router_root_mounted_nested_router_empty_root_slash_nested() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/",
            MockHandler,
            "inner",
        )]);
        let router = Router::with_urls(vec![Route::with_router("", sub_router)]);

        let found = router.get_handler("/").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));

        let found = router.get_handler("//").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));

        let url = router
            .reverse(None, "inner", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/");
        assert!(router.has_route(&url));
    }

    #[test]
    fn router_nested_router_trailing_slash_prefix() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/inner",
            MockHandler,
            "inner",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/api/", sub_router)]);

        let found = router.get_handler("/api/inner").unwrap();
        assert_eq!(found.name, Some(RouteName("inner".to_string())));
    }

    #[test]
    fn router_nested_router_consumes_remaining_path() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/posts/{post_id}",
            MockHandler,
            "post_detail",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/users/{id}", sub_router)]);

        let found = router.get_handler("/users/123/posts/456").unwrap();

        assert_eq!(found.name, Some(RouteName("post_detail".to_string())));
        assert_params(found.params, &[("id", "123"), ("post_id", "456")]);
    }

    #[test]
    fn router_param_mount_param_nested_captures_both_in_order() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{sub_id}",
            MockHandler,
            "leaf",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/{id}", sub_router)]);

        let found = router.get_handler("/123/456").unwrap();
        assert_eq!(found.name, Some(RouteName("leaf".to_string())));
        assert_eq!(
            found.params,
            vec![
                ("id".to_string(), "123".to_string()),
                ("sub_id".to_string(), "456".to_string()),
            ]
        );
    }

    #[test]
    fn router_param_mount_wildcard_nested_exact_match_fails_deep_match_works() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{*rest}",
            MockHandler,
            "leaf",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/{id}", sub_router)]);

        assert!(router.get_handler("/123").is_none());

        let found = router.get_handler("/123/a/b").unwrap();
        assert_eq!(found.name, Some(RouteName("leaf".to_string())));
        assert_params(found.params, &[("id", "123"), ("rest", "a/b")]);
    }

    #[test]
    fn router_param_mount_trailing_slash_empty_nested_captures_param() {
        let sub_router =
            Router::with_urls(vec![Route::with_handler_and_name("", MockHandler, "leaf")]);
        let router = Router::with_urls(vec![Route::with_router("/{id}/", sub_router)]);

        let found = router.get_handler("/123/").unwrap();
        assert_eq!(found.name, Some(RouteName("leaf".to_string())));
        assert_eq!(found.params, vec![("id".to_string(), "123".to_string())]);
    }

    #[test]
    fn router_param_mount_trailing_slash_bare_path_fails() {
        let sub_router =
            Router::with_urls(vec![Route::with_handler_and_name("", MockHandler, "leaf")]);
        let router = Router::with_urls(vec![Route::with_router("/{id}/", sub_router)]);
        assert!(router.get_handler("/123").is_none());
    }

    #[test]
    fn router_duplicate_param_name_across_nesting_levels_allowed() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{id}",
            MockHandler,
            "leaf",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/{id}", sub_router)]);

        let found = router.get_handler("/1/2").unwrap();
        assert_eq!(found.name, Some(RouteName("leaf".to_string())));
        assert_eq!(
            found.params,
            vec![
                ("id".to_string(), "1".to_string()),
                ("id".to_string(), "2".to_string()),
            ]
        );
    }

    #[test]
    fn router_bare_mount_match_fails_when_nested_is_wildcard_only() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{*rest}",
            MockHandler,
            "leaf",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/api", sub_router)]);

        assert!(router.get_handler("/api").is_none());

        let found = router.get_handler("/api/x/y").unwrap();
        assert_eq!(found.name, Some(RouteName("leaf".to_string())));
        assert_params(found.params, &[("rest", "x/y")]);
    }

    #[test]
    fn router_multi_segment_mount_with_wildcard_nested() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{*rest}",
            MockHandler,
            "leaf",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/a/b", sub_router)]);

        assert!(router.get_handler("/a/b").is_none());
        let found = router.get_handler("/a/b/c/d").unwrap();
        assert_eq!(found.name, Some(RouteName("leaf".to_string())));
        assert_params(found.params, &[("rest", "c/d")]);
    }

    #[test]
    fn router_slash_mount_wildcard_nested_bare_slash_fails() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{*path}",
            MockHandler,
            "leaf",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/files/", sub_router)]);

        assert!(router.get_handler("/files/").is_none());
        assert!(router.get_handler("/files").is_none());

        let found = router.get_handler("/files/x").unwrap();
        assert_eq!(found.name, Some(RouteName("leaf".to_string())));
        assert_params(found.params, &[("path", "x")]);
    }

    #[test]
    fn router_multi_segment_slash_mount_param_nested() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{id}",
            MockHandler,
            "leaf",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/a/b/", sub_router)]);

        assert!(router.get_handler("/a/b").is_none());
        assert!(router.get_handler("/a/b/").is_none());

        let found = router.get_handler("/a/b/42").unwrap();
        assert_eq!(found.name, Some(RouteName("leaf".to_string())));
        assert_params(found.params, &[("id", "42")]);
    }

    #[test]
    fn router_handler_takes_priority_over_nested_router_at_same_path() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/",
            MockHandler,
            "nested",
        )]);
        let router = Router::with_urls(vec![
            Route::with_router("/users", sub_router),
            Route::with_handler_and_name("/users", MockHandler, "handler"),
        ]);

        let found = router.get_handler("/users").unwrap();

        assert_eq!(found.name, Some(RouteName("handler".to_string())));
    }

    #[test]
    fn router_static_nested_mount_priority_over_sibling_wildcard_mount() {
        let generic_sub = Router::with_urls(vec![Route::with_handler_and_name(
            "/{*rest}",
            MockHandler,
            "generic",
        )]);
        let specific_sub = Router::with_urls(vec![Route::with_handler_and_name(
            "/{*rest}",
            MockHandler,
            "specific",
        )]);
        let router = Router::with_urls(vec![
            Route::with_router("/admin", generic_sub),
            Route::with_router("/admin/extra", specific_sub),
        ]);

        let found = router.get_handler("/admin/extra/more").unwrap();
        assert_eq!(found.name, Some(RouteName("specific".to_string())));
        assert_params(found.params, &[("rest", "more")]);

        let found = router.get_handler("/admin/other/thing").unwrap();
        assert_eq!(found.name, Some(RouteName("generic".to_string())));
        assert_params(found.params, &[("rest", "other/thing")]);
    }

    #[test]
    fn router_handler_priority_swallows_routers_own_trailing_slash_exact_entry() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{*rest}",
            MockHandler,
            "sub_catch_all",
        )]);
        let router = Router::with_urls(vec![
            Route::with_handler_and_name("/users", MockHandler, "handler"),
            Route::with_router("/users/", sub_router),
        ]);

        let found = router.get_handler("/users").unwrap();
        assert_eq!(found.name, Some(RouteName("handler".to_string())));
        assert!(router.get_handler("/users/").is_none());

        let found = router.get_handler("/users/anything").unwrap();
        assert_eq!(found.name, Some(RouteName("sub_catch_all".to_string())));
        assert_params(found.params, &[("rest", "anything")]);
    }

    #[test]
    fn router_triple_nested_all_empty_mounts_reachable_via_single_slash() {
        let leaf = Router::with_urls(vec![Route::with_handler_and_name("", MockHandler, "leaf")]);
        let mid = Router::with_urls(vec![Route::with_router("", leaf)]);
        let router = Router::with_urls(vec![Route::with_router("", mid)]);

        let found = router.get_handler("/").unwrap();
        assert_eq!(found.name, Some(RouteName("leaf".to_string())));
    }

    #[test]
    fn router_triple_nested_param_then_empty_then_param() {
        let leaf = Router::with_urls(vec![Route::with_handler_and_name(
            "/{b}",
            MockHandler,
            "leaf",
        )]);
        let mid = Router::with_urls(vec![Route::with_router("", leaf)]);
        let router = Router::with_urls(vec![Route::with_router("/{a}", mid)]);

        let found = router.get_handler("/1/2").unwrap();
        assert_eq!(found.name, Some(RouteName("leaf".to_string())));
        assert_eq!(
            found.params,
            vec![
                ("a".to_string(), "1".to_string()),
                ("b".to_string(), "2".to_string()),
            ]
        );
    }

    #[test]
    #[should_panic(
        expected = "route conflict error: duplicate route: `/users` conflicts with an already registered handler route `/users` (both fully match the same path)"
    )]
    fn router_duplicate_handler_routes_panic() {
        let _ = Router::with_urls(vec![
            Route::with_handler("/users", MockHandler),
            Route::with_handler("/users", MockHandler),
        ]);
    }

    #[test]
    #[should_panic(
        expected = "route conflict error: duplicate route: `/users/` conflicts with an already registered handler route `/users/` (both fully match the same path)"
    )]
    fn router_duplicate_handler_routes_with_trailing_slash_panic() {
        let _ = Router::with_urls(vec![
            Route::with_handler("/users/", MockHandler),
            Route::with_handler("/users/", MockHandler),
        ]);
    }

    #[test]
    #[should_panic(
        expected = "route conflict error: duplicate route name: `home` is registered at both `/a` and `/b`; route names must be unique within the same app"
    )]
    fn router_duplicate_route_name_same_app_panics() {
        let _ = Router::with_urls(vec![
            Route::with_handler_and_name("/a", MockHandler, "home"),
            Route::with_handler_and_name("/b", MockHandler, "home"),
        ]);
    }

    #[test]
    fn router_duplicate_nested_router_routes_merge() {
        let router1 = Router::with_urls(vec![Route::with_handler_and_name("/a", MockHandler, "a")]);
        let router2 = Router::with_urls(vec![Route::with_handler_and_name("/b", MockHandler, "b")]);

        let router = Router::with_urls(vec![
            Route::with_router("/users", router1),
            Route::with_router("/users", router2),
        ]);

        assert_eq!(
            router.get_handler("/users/a").unwrap().name,
            Some(RouteName("a".to_string()))
        );
        assert_eq!(
            router.get_handler("/users/b").unwrap().name,
            Some(RouteName("b".to_string()))
        );
    }

    #[test]
    fn router_duplicate_nested_router_routes_merge_with_slash() {
        let router1 = Router::with_urls(vec![Route::with_handler_and_name("/a", MockHandler, "a")]);
        let router2 = Router::with_urls(vec![Route::with_handler_and_name("/b", MockHandler, "b")]);

        let router = Router::with_urls(vec![
            Route::with_router("/users/", router1),
            Route::with_router("/users/", router2),
        ]);

        assert_eq!(
            router.get_handler("/users/a").unwrap().name,
            Some(RouteName("a".to_string()))
        );
        assert_eq!(
            router.get_handler("/users/b").unwrap().name,
            Some(RouteName("b".to_string()))
        );
    }

    #[test]
    fn router_duplicate_nested_router_routes_merge_slash_diff() {
        let router1 = Router::with_urls(vec![Route::with_handler_and_name("/a", MockHandler, "a")]);
        let router2 = Router::with_urls(vec![Route::with_handler_and_name("/b", MockHandler, "b")]);

        let router = Router::with_urls(vec![
            Route::with_router("/users/", router1),
            Route::with_router("/users", router2),
        ]);

        assert_eq!(
            router.get_handler("/users/a").unwrap().name,
            Some(RouteName("a".to_string()))
        );
        assert_eq!(
            router.get_handler("/users/b").unwrap().name,
            Some(RouteName("b".to_string()))
        );
    }

    #[test]
    #[should_panic(expected = "route conflict error: duplicate route")]
    fn router_merged_routers_reject_leaf_conflicts() {
        let router1 = Router::with_urls(vec![Route::with_handler("/health", MockHandler)]);
        let router2 = Router::with_urls(vec![Route::with_handler("/health", MockHandler)]);

        let _ = Router::with_urls(vec![
            Route::with_router("/api", router1),
            Route::with_router("/api", router2),
        ]);
    }

    #[test]
    #[should_panic(expected = "route conflict error: duplicate route name")]
    fn router_merged_routers_both_unscoped_same_name_panics() {
        let router1 = Router::with_urls(vec![Route::with_handler_and_name(
            "/a",
            MockHandler,
            "home",
        )]);
        let router2 = Router::with_urls(vec![Route::with_handler_and_name(
            "/b",
            MockHandler,
            "home",
        )]);

        let _ = Router::with_urls(vec![
            Route::with_router("/shared", router1),
            Route::with_router("/shared", router2),
        ]);
    }

    #[test]
    fn router_merged_routers_reverse_scoped_by_app_name() {
        let mut router1 = Router::with_urls(vec![Route::with_handler_and_name(
            "/one",
            MockHandler,
            "index",
        )]);
        router1.set_app_name(AppName("app1".to_string()));

        let mut router2 = Router::with_urls(vec![Route::with_handler_and_name(
            "/two",
            MockHandler,
            "index",
        )]);
        router2.set_app_name(AppName("app2".to_string()));

        let router = Router::with_urls(vec![
            Route::with_router("/shared", router1),
            Route::with_router("/shared", router2),
        ]);

        assert_eq!(
            router
                .reverse(Some("app1"), "index", &ReverseParamMap::new())
                .unwrap(),
            "/shared/one"
        );
        assert_eq!(
            router
                .reverse(Some("app2"), "index", &ReverseParamMap::new())
                .unwrap(),
            "/shared/two"
        );
    }

    #[test]
    fn router_reverse_prefers_exact_app_scope_over_unscoped_candidate() {
        // router with no name set
        let unscoped_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/unscoped",
            MockHandler,
            "dup",
        )]);

        // router with name set
        let mut scoped_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/scoped",
            MockHandler,
            "dup",
        )]);
        scoped_router.set_app_name(AppName("app1".to_string()));

        let router = Router::with_urls(vec![
            Route::with_router("/a", unscoped_router),
            Route::with_router("/a", scoped_router),
        ]);

        let url = router
            .reverse(Some("app1"), "dup", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/a/scoped");
    }

    #[test]
    fn router_reverse_no_app_name_returns_none() {
        let mut router1 = Router::with_urls(vec![Route::with_handler_and_name(
            "/one",
            MockHandler,
            "home",
        )]);
        router1.set_app_name(AppName("app1".to_string()));
        let mut router2 = Router::with_urls(vec![Route::with_handler_and_name(
            "/two",
            MockHandler,
            "home",
        )]);
        router2.set_app_name(AppName("app2".to_string()));

        let router = Router::with_urls(vec![
            Route::with_router("/shared", router1),
            Route::with_router("/shared", router2),
        ]);

        let result = router
            .reverse_option(None, "home", &ReverseParamMap::new())
            .unwrap();
        assert!(result.is_none());
    }

    #[test]
    #[should_panic(
        expected = "route conflict error: conflicting route parameters: `/foo/{bar}` uses `{bar}` but `/foo/{baz}` uses `{baz}` at the same position in the path; both routes must bind the same parameter name there, since only one value can be captured at that position"
    )]
    fn router_conflicting_param_names_panic() {
        let _ = Router::with_urls(vec![
            Route::with_handler("/foo/{bar}", MockHandler),
            Route::with_handler("/foo/{baz}", MockHandler),
        ]);
    }

    #[test]
    fn router_same_path_with_trailing_lash_diff() {
        // this should not fail
        let _ = Router::with_urls(vec![
            Route::with_handler("/foo/{bar}/", MockHandler),
            Route::with_handler("/foo/{baz}", MockHandler),
        ]);
    }

    #[test]
    #[should_panic(
        expected = "route conflict error: duplicate route: `/static/{*path}` conflicts with an already registered handler route `/static/{*path}` (both fully match the same path)"
    )]
    fn router_duplicate_wildcard_routes_panic() {
        let _ = Router::with_urls(vec![
            Route::with_handler("/static/{*path}", MockHandler),
            Route::with_handler("/static/{*path}", MockHandler),
        ]);
    }

    #[test]
    #[should_panic(
        expected = "route conflict error: conflicting wildcard parameters: `/static/{*path}` uses `{*path}` but `/static/{*file_path}` uses `{*file_path}` at the same position in the path"
    )]
    fn router_conflicting_wildcard_names_panic() {
        let _ = Router::with_urls(vec![
            Route::with_handler("/static/{*path}", MockHandler),
            Route::with_handler("/static/{*file_path}", MockHandler),
        ]);
    }

    #[test]
    #[should_panic(
        expected = "route conflict error: duplicate route: `/static/{*file_path}` conflicts with an already registered handler route `/static/{path}` (both fully match the same path)"
    )]
    fn router_wildcard_and_param_at_same_segment_conflict() {
        let _ = Router::with_urls(vec![
            Route::with_handler("/static/{path}", MockHandler),
            Route::with_handler("/static/{*file_path}", MockHandler),
        ]);
    }

    #[test]
    #[should_panic(expected = "route conflict error")]
    fn router_wildcard_mount_with_static_nested_errors() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/leaf",
            MockHandler,
            "leaf",
        )]);
        let _ = Router::with_urls(vec![Route::with_router("/{*rest}", sub_router)]);
    }

    #[test]
    #[should_panic(expected = "route conflict error")]
    fn router_wildcard_mount_with_param_nested_errors() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{id}",
            MockHandler,
            "leaf",
        )]);
        let _ = Router::with_urls(vec![Route::with_router("/{*rest}", sub_router)]);
    }

    #[test]
    #[should_panic(expected = "route conflict error")]
    fn router_wildcard_mount_with_empty_nested_errors() {
        let sub_router =
            Router::with_urls(vec![Route::with_handler_and_name("", MockHandler, "leaf")]);
        let _ = Router::with_urls(vec![Route::with_router("/{*rest}", sub_router)]);
    }

    #[test]
    #[should_panic(expected = "route conflict error")]
    fn router_wildcard_mount_with_wildcard_nested_errors() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{*rest}",
            MockHandler,
            "leaf",
        )]);
        let _ = Router::with_urls(vec![Route::with_router("/{*outer}", sub_router)]);
    }

    #[test]
    #[should_panic(expected = "route conflict error")]
    fn router_prefixed_wildcard_mount_errors() {
        let sub_router =
            Router::with_urls(vec![Route::with_handler_and_name("", MockHandler, "leaf")]);
        let _ = Router::with_urls(vec![Route::with_router("/files/{*path}", sub_router)]);
    }

    #[test]
    fn router_reverse() {
        let route = Route::with_handler_and_name("/test", MockHandler, "test");
        let router = Router::with_urls(vec![route.clone()]);
        let params = ReverseParamMap::new();
        let url = router.reverse(None, "test", &params).unwrap();
        assert_eq!(url, "/test");
    }

    #[test]
    fn router_reverse_with_param() {
        let route = Route::with_handler_and_name("/test/{id}", MockHandler, "test");
        let router = Router::with_urls(vec![route.clone()]);
        let mut params = ReverseParamMap::new();
        params.insert("id", "123");
        let url = router.reverse(None, "test", &params).unwrap();
        assert_eq!(url, "/test/123");
    }

    #[test]
    fn router_reverse_option() {
        let route = Route::with_handler_and_name("/test", MockHandler, "test");
        let router = Router::with_urls(vec![route.clone()]);
        let params = ReverseParamMap::new();
        let url = router
            .reverse_option(None, "test", &params)
            .unwrap()
            .unwrap();
        assert_eq!(url, "/test");
    }

    #[test]
    fn router_reverse_option_wrong_app_name_returns_none() {
        let route = Route::with_handler_and_name("/test", MockHandler, "test");
        let mut router = Router::with_urls(vec![route]);
        router.set_app_name(AppName("app_1".to_string()));

        let result = router
            .reverse_option(Some("app_2"), "test", &ReverseParamMap::new())
            .unwrap();

        assert!(result.is_none());
    }

    #[test]
    fn router_reverse_missing_view_returns_error() {
        let router = Router::empty();

        let result = router.reverse(None, "missing", &ReverseParamMap::new());
        assert!(result.is_err());
    }

    #[test]
    fn router_reverse_of_nested_index_uses_bare_mount_path() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/",
            MockHandler,
            "index",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/admin", sub_router)]);

        let url = router
            .reverse(None, "index", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/admin");
        assert!(router.has_route(&url));
    }

    #[test]
    fn router_reverse_root_mount_no_double_slash() {
        let route = Route::with_handler_and_name("/", MockHandler, "index");
        let sub_router = Router::with_urls(vec![route]);
        let router = Router::with_urls(vec![Route::with_router("/", sub_router)]);

        let url = router
            .reverse(None, "index", &ReverseParamMap::new())
            .unwrap();

        assert_eq!(url, "/");
    }

    #[test]
    fn router_reverse_nested_under_root_mount_no_double_slash() {
        let route = Route::with_handler_and_name("/inner", MockHandler, "inner");
        let sub_router = Router::with_urls(vec![route]);
        let router = Router::with_urls(vec![Route::with_router("/", sub_router)]);

        let url = router
            .reverse(None, "inner", &ReverseParamMap::new())
            .unwrap();

        assert_eq!(url, "/inner");
    }

    #[test]
    fn router_reverse_deeply_nested_root_mounts_no_double_slash() {
        let route = Route::with_handler_and_name("/leaf", MockHandler, "leaf");
        let inner_router = Router::with_urls(vec![route]);
        let mid_router = Router::with_urls(vec![Route::with_router("/", inner_router)]);
        let router = Router::with_urls(vec![Route::with_router("/", mid_router)]);

        let url = router
            .reverse(None, "leaf", &ReverseParamMap::new())
            .unwrap();

        assert_eq!(url, "/leaf");
    }

    #[test]
    fn router_reverse_slash_mounted_root_route_keeps_slash() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/",
            MockHandler,
            "index",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/admin/", sub_router)]);

        let url = router
            .reverse(None, "index", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/admin/");
        assert!(router.has_route(&url));
    }

    #[test]
    fn router_reverse_slash_mounted_non_root_route_unaffected() {
        let nested_sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/bar/{buz}",
            MockHandler,
            "biz",
        )]);
        let sub_router = Router::with_urls(vec![
            Route::with_handler_and_name("/foo", MockHandler, "foo"),
            Route::with_router("/fab", nested_sub_router),
            Route::with_handler_and_name("/bar/", MockHandler, "bar"),
        ]);
        let router = Router::with_urls(vec![Route::with_router("/admin/", sub_router)]);

        let url = router
            .reverse(None, "foo", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/admin/foo");
        assert!(router.has_route(&url));

        let mut params = ReverseParamMap::new();
        params.insert("buz", "random");
        let url = router.reverse(None, "biz", &params).unwrap();
        assert_eq!(url, "/admin/fab/bar/random");

        let url = router
            .reverse(None, "bar", &ReverseParamMap::new())
            .unwrap();
        assert_eq!(url, "/admin/bar/");
        assert!(router.has_route(&url));
    }

    #[test]
    fn router_reverse_app_name() {
        let route = Route::with_handler_and_name("/test", MockHandler, "test");
        let mut router_1 = Router::with_urls(vec![route.clone()]);
        router_1.set_app_name(AppName("app_1".to_string()));
        let mut router_2 = Router::with_urls(vec![route.clone()]);
        router_2.set_app_name(AppName("app_2".to_string()));
        let root_router = Router::with_urls(vec![
            Route::with_router("/", router_1),
            Route::with_router("/sub", router_2),
        ]);

        let params = ReverseParamMap::new();
        let url = root_router.reverse(Some("app_2"), "test", &params).unwrap();

        assert_eq!(url, "/sub/test");
    }

    #[test]
    fn router_reverse_app_name_nested() {
        let route = Route::with_handler_and_name("/test", MockHandler, "test");
        let router = Router::with_urls(vec![route.clone()]);
        let sub_router = Router::with_urls(vec![Route::with_router("/sub", router)]);
        let mut root_router = Router::with_urls(vec![Route::with_router("/subsub", sub_router)]);
        root_router.set_app_name(AppName("app_root".to_string()));

        let params = ReverseParamMap::new();
        let url = root_router
            .reverse(Some("app_root"), "test", &params)
            .unwrap();

        assert_eq!(url, "/subsub/sub/test");
    }

    #[test]
    fn router_nested_mount_and_leaf_param_order_preserved() {
        let sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/{model_name}/{pk}/edit/",
            MockHandler,
            "edit",
        )]);
        let router = Router::with_urls(vec![Route::with_router("/admin", sub_router)]);

        let found = router.get_handler("/admin/database_user/1/edit/").unwrap();

        assert_eq!(
            found.params,
            vec![
                ("model_name".to_string(), "database_user".to_string()),
                ("pk".to_string(), "1".to_string()),
            ]
        );
    }

    #[test]
    fn router_very_nested_mount_and_leaf_param_order_preserved() {
        let nested_sub_router = Router::with_urls(vec![Route::with_handler_and_name(
            "/foo/{bar}/{*baz}",
            MockHandler,
            "edit",
        )]);

        let sub_router = Router::with_urls(vec![Route::with_router(
            "/{model_name}/{pk}/edit/",
            nested_sub_router,
        )]);
        let router = Router::with_urls(vec![Route::with_router("/admin", sub_router)]);

        let found = router
            .get_handler("/admin/database_user/1/edit/foo/jon/2/doe")
            .unwrap();

        assert_eq!(
            found.params,
            vec![
                ("model_name".to_string(), "database_user".to_string()),
                ("pk".to_string(), "1".to_string()),
                ("bar".to_string(), "jon".to_string()),
                ("baz".to_string(), "2/doe".to_string())
            ]
        );
    }

    #[test]
    fn test_reverse_macro() {
        let route = Route::with_handler_and_name("/test/{id}", MockHandler, "test");
        let router = Router::with_urls(vec![route]);

        let request = TestRequestBuilder::get("/").router(router).build();
        let url = reverse!(request, "test", id = 123).unwrap();

        assert_eq!(url, "/test/123");
    }

    #[test]
    fn reverse_macro_query_params() {
        let route = Route::with_handler_and_name("/", MockHandler, "home");
        let router = Router::with_urls(vec![route]);

        let request = TestRequestBuilder::get("/").router(router).build();
        let url = reverse!(request, "home", query: { page = 2, search = "cot" }).unwrap();

        assert_eq!(url, "/?page=2&search=cot");
    }

    #[test]
    fn reverse_macro_path_and_query_params() {
        let route = Route::with_handler_and_name("/test/{id}", MockHandler, "test");
        let router = Router::with_urls(vec![route]);

        let request = TestRequestBuilder::get("/").router(router).build();
        let url = reverse!(request, "test", id = 123, query: { page = 2 }).unwrap();

        assert_eq!(url, "/test/123?page=2");
    }

    #[test]
    fn reverse_macro_query_params_are_encoded() {
        let route = Route::with_handler_and_name("/", MockHandler, "home");
        let router = Router::with_urls(vec![route]);

        let request = TestRequestBuilder::get("/").router(router).build();
        let url = reverse!(request, "home", query: { search = "hello world & cot" }).unwrap();

        assert_eq!(url, "/?search=hello+world+%26+cot");
    }

    #[test]
    fn reverse_macros_distinguish_query_path_parameter() {
        let route = Route::with_handler_and_name("/search/{query}/{id}", MockHandler, "search");
        let request = TestRequestBuilder::get("/")
            .router(Router::with_urls([route]))
            .build();

        let url = reverse!(request, "search", query = "cot", id = 5,
            query: { query = "new", page = 1 + 1, },
        )
        .unwrap();
        let response = cot::reverse_redirect!(request, "search", query = "cot", id = 5,
            query: { query = "new", page = 1 + 1, },
        )
        .unwrap();

        assert_eq!(url, "/search/cot/5?query=new&page=2");
        assert_eq!(response.headers().get("location").unwrap(), url.as_str());
    }

    #[test]
    fn reverse_macros_without_query_params() {
        let request = TestRequestBuilder::get("/")
            .router(Router::with_urls([
                Route::with_handler_and_name("/", MockHandler, "home"),
                Route::with_handler_and_name("/test/{id}", MockHandler, "test"),
            ]))
            .build();

        assert_eq!(reverse!(request, "home").unwrap(), "/");
        assert_eq!(reverse!(request, "home",).unwrap(), "/");
        assert_eq!(reverse!(request, "home", query: {}).unwrap(), "/");
        assert_eq!(reverse!(request, "test", id = 5,).unwrap(), "/test/5");
        assert_eq!(
            reverse!(request, "test", id = 5, query: {}).unwrap(),
            "/test/5"
        );
        assert_eq!(
            cot::reverse_redirect!(request, "home").unwrap().headers()["location"],
            "/"
        );
        assert_eq!(
            cot::reverse_redirect!(request, "home", query: {})
                .unwrap()
                .headers()["location"],
            "/"
        );
        assert_eq!(
            cot::reverse_redirect!(request, "test", id = 5, query: {})
                .unwrap()
                .headers()["location"],
            "/test/5"
        );
    }

    #[test]
    fn reverse_macros_query_params_with_urls() {
        let route = Route::with_handler_and_name("/", MockHandler, "home");
        let request = TestRequestBuilder::get("/")
            .router(Router::with_urls([route]))
            .build();
        let urls = Urls::from_request(&request);

        let url =
            reverse!(urls, "home", query: { search = "hello world & cot", page = 2 }).unwrap();
        let response = cot::reverse_redirect!(urls, "home",
            query: { search = "hello world & cot", page = 2 }
        )
        .unwrap();

        assert_eq!(url, "/?search=hello+world+%26+cot&page=2");
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        assert_eq!(response.headers().get("location").unwrap(), url.as_str());
    }

    #[test]
    fn reverse_macros_query_params_preserve_errors() {
        let route = Route::with_handler_and_name("/test/{id}", MockHandler, "test");
        let request = TestRequestBuilder::get("/")
            .router(Router::with_urls([route]))
            .build();

        assert!(reverse!(request, "missing", query: { page = 2 }).is_err());
        assert!(cot::reverse_redirect!(request, "missing", query: { page = 2 }).is_err());
        assert!(reverse!(request, "test", query: { page = 2 }).is_err());
        assert!(cot::reverse_redirect!(request, "test", query: { page = 2 }).is_err());
    }

    #[test]
    fn reverse_with_query_leaves_url_unchanged_when_empty() {
        assert_eq!(reverse_with_query("/test".to_string(), &[]), "/test");
    }

    #[test]
    fn test_reverse_redirect_macro() {
        let route = Route::with_handler_and_name("/test/{id}", MockHandler, "test");
        let router = Router::with_urls(vec![route]);

        let request = TestRequestBuilder::get("/").router(router).build();
        let response = cot::reverse_redirect!(request, "test", id = 123).unwrap();

        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        assert_eq!(response.headers().get("location").unwrap(), "/test/123");
    }

    #[test]
    fn reverse_redirect_macro_query_params() {
        let route = Route::with_handler_and_name("/test/{id}", MockHandler, "test");
        let router = Router::with_urls(vec![route]);

        let request = TestRequestBuilder::get("/").router(router).build();
        let response = cot::reverse_redirect!(
            request,
            "test",
            id = 5,
            query: { page = 2, sort = "new", foo = "bar" }
        )
        .unwrap();

        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        assert_eq!(
            response.headers().get("location").unwrap(),
            "/test/5?page=2&sort=new&foo=bar"
        );
    }

    fn test_request() -> Request {
        TestRequestBuilder::get("/test").build()
    }
}