camel-test 0.5.7

Testing utilities for rust-camel
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
//! Integration tests for the rust-camel framework.
//!
//! These tests exercise the full pipeline: CamelContext → Consumer → Processors → Producer,
//! verifying that exchanges flow end-to-end correctly.
//!
//! All assertions use the `MockComponent` shared registry instead of manual
//! capture closures.

use camel_api::Value;
use camel_api::aggregator::AggregatorConfig;
use camel_api::splitter::{AggregationStrategy, SplitterConfig, split_body_lines};
use camel_builder::{RouteBuilder, StepAccumulator};
use camel_component_file::FileComponent;
use camel_component_http::HttpComponent;
use camel_component_log::LogComponent;
use camel_test::CamelTestContext;

// ---------------------------------------------------------------------------
// Test 1: Timer → Mock (verify exchanges received)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn timer_to_mock() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=3")
        .route_id("test-route-1")
        .to("mock:result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("result").unwrap();
    endpoint.assert_exchange_count(3).await;

    let exchanges = endpoint.get_received_exchanges().await;
    let first = &exchanges[0];
    assert_eq!(
        first.input.header("CamelTimerName"),
        Some(&serde_json::Value::String("tick".into()))
    );
    assert_eq!(
        first.input.header("CamelTimerCounter"),
        Some(&serde_json::Value::Number(1.into()))
    );
}

// ---------------------------------------------------------------------------
// Test 2: Timer → Filter → Mock (verify filtering behavior)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn timer_filter_mock() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    // Filter: only allow even-numbered ticks through to mock:result.
    // With the typestate FilterBuilder, the filter scope only executes
    // for matching exchanges. Non-matching exchanges skip the scope entirely.
    // Timer fires 4 times (counters 1, 2, 3, 4), but only even counters
    // (2, 4) pass the filter, so only 2 exchanges reach mock:result.
    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=4")
        .route_id("test-route-2")
        .filter(|ex| {
            ex.input
                .header("CamelTimerCounter")
                .and_then(|v| v.as_u64())
                .map(|n| n % 2 == 0)
                .unwrap_or(false)
        })
        .to("mock:result")
        .end_filter()
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(400)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("result").unwrap();
    endpoint.assert_exchange_count(2).await;

    // Verify that only even-numbered exchanges passed through.
    let exchanges = endpoint.get_received_exchanges().await;
    let counters: Vec<u64> = exchanges
        .iter()
        .map(|ex| {
            ex.input
                .header("CamelTimerCounter")
                .and_then(|v| v.as_u64())
                .expect("CamelTimerCounter header missing")
        })
        .collect();
    assert_eq!(
        counters,
        vec![2, 4],
        "only even counters should pass filter"
    );
}

// ---------------------------------------------------------------------------
// Test N: Filter EIP — matching exchanges reach inner mock
// ---------------------------------------------------------------------------

#[tokio::test]
async fn filter_matching_exchanges_reach_inner_mock() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    // 4 exchanges, alternate active=true/false (n=0,1,2,3 → even=true).
    // Only active=true exchanges should reach mock:matched.
    let counter = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
    let counter_clone = std::sync::Arc::clone(&counter);

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=4")
        .route_id("test-route-3")
        .process(move |mut ex: camel_api::Exchange| {
            let c = std::sync::Arc::clone(&counter_clone);
            async move {
                let n = c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                ex.input
                    .set_header("active", Value::Bool(n.is_multiple_of(2)));
                Ok(ex)
            }
        })
        .filter(|ex| ex.input.header("active") == Some(&Value::Bool(true)))
        .to("mock:matched")
        .end_filter()
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(400)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("matched").unwrap();
    endpoint.assert_exchange_count(2).await;
}

// ---------------------------------------------------------------------------
// Test N+1: Filter EIP — non-matching exchanges skip inner, reach outer mock
// ---------------------------------------------------------------------------

#[tokio::test]
async fn filter_non_matching_continue_outer_pipeline() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let counter = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
    let counter_clone = std::sync::Arc::clone(&counter);

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=4")
        .route_id("test-route-4")
        .process(move |mut ex: camel_api::Exchange| {
            let c = std::sync::Arc::clone(&counter_clone);
            async move {
                let n = c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                ex.input
                    .set_header("active", Value::Bool(n.is_multiple_of(2)));
                Ok(ex)
            }
        })
        .filter(|ex| ex.input.header("active") == Some(&Value::Bool(true)))
        .to("mock:inner")
        .end_filter()
        .to("mock:outer") // always reached by all 4 exchanges
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(400)).await;
    h.stop().await;

    let inner = h.mock().get_endpoint("inner").unwrap();
    let outer = h.mock().get_endpoint("outer").unwrap();

    inner.assert_exchange_count(2).await; // only active=true exchanges
    outer.assert_exchange_count(4).await; // ALL exchanges continue past filter
}

// ---------------------------------------------------------------------------
// Test 3: Timer → SetHeader → Mock (verify headers set)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn timer_set_header_mock() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=3")
        .route_id("test-route-5")
        .set_header("environment", Value::String("test".into()))
        .set_header("version", Value::Number(1.into()))
        .to("mock:result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("result").unwrap();
    endpoint.assert_exchange_count(3).await;

    let exchanges = endpoint.get_received_exchanges().await;
    for ex in exchanges.iter() {
        assert_eq!(
            ex.input.header("environment"),
            Some(&Value::String("test".into())),
            "Each exchange should have 'environment' header"
        );
        assert_eq!(
            ex.input.header("version"),
            Some(&Value::Number(1.into())),
            "Each exchange should have 'version' header"
        );
        // Timer's own headers should still be present
        assert!(
            ex.input.header("CamelTimerName").is_some(),
            "Timer headers should still be present"
        );
    }
}

// ---------------------------------------------------------------------------
// Test 4: Timer → SetHeader → Log (verify full pipeline with log producer)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn timer_to_log() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_component(LogComponent::new())
        .build()
        .await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=2")
        .route_id("test-route-6")
        .set_header("source", Value::String("integration-test".into()))
        .to("log:test?showHeaders=true")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    // Just verify it doesn't panic — the log producer writes to tracing
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    h.stop().await;
}

// ---------------------------------------------------------------------------
// Test 5: Multiple routes in a single context
// ---------------------------------------------------------------------------

#[tokio::test]
async fn multiple_routes() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route_a = RouteBuilder::from("timer:routeA?period=50&repeatCount=2")
        .route_id("test-route-7")
        .set_header("route", Value::String("A".into()))
        .to("mock:resultA")
        .build()
        .unwrap();

    let route_b = RouteBuilder::from("timer:routeB?period=50&repeatCount=3")
        .route_id("test-route-8")
        .set_header("route", Value::String("B".into()))
        .to("mock:resultB")
        .build()
        .unwrap();

    h.add_route(route_a).await.unwrap();
    h.add_route(route_b).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    h.stop().await;

    let endpoint_a = h.mock().get_endpoint("resultA").unwrap();
    let endpoint_b = h.mock().get_endpoint("resultB").unwrap();

    endpoint_a.assert_exchange_count(2).await;
    endpoint_b.assert_exchange_count(3).await;

    let a_exchanges = endpoint_a.get_received_exchanges().await;
    let b_exchanges = endpoint_b.get_received_exchanges().await;

    assert_eq!(
        a_exchanges[0].input.header("route"),
        Some(&Value::String("A".into()))
    );
    assert_eq!(
        b_exchanges[0].input.header("route"),
        Some(&Value::String("B".into()))
    );
}

// ---------------------------------------------------------------------------
// Error-handling integration tests (Tasks 4 + 5)
// ---------------------------------------------------------------------------

use camel_api::{BoxProcessor, BoxProcessorExt, CamelError, CircuitBreakerConfig};
use std::sync::{
    Arc,
    atomic::{AtomicU32, Ordering},
};
use std::time::Duration;

/// A processor that always fails with the given message.
fn failing_step(msg: &'static str) -> BoxProcessor {
    BoxProcessor::from_fn(move |_ex| {
        Box::pin(async move { Err(CamelError::ProcessorError(msg.into())) })
    })
}

// ---------------------------------------------------------------------------
// Test 6: DLC receives the failed exchange
// ---------------------------------------------------------------------------

#[tokio::test]
async fn dlc_receives_failed_exchange() {
    use camel_api::error_handler::ErrorHandlerConfig;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-9")
        .process_fn(failing_step("intentional"))
        .error_handler(ErrorHandlerConfig::dead_letter_channel("mock:dlc"))
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(300)).await;
    h.stop().await;

    let dlc = h.mock().get_endpoint("dlc").unwrap();
    let exchanges = dlc.get_received_exchanges().await;
    assert!(!exchanges.is_empty());
    assert!(exchanges[0].has_error());
}

// ---------------------------------------------------------------------------
// Test 7: Retry recovers before DLC
// ---------------------------------------------------------------------------

#[tokio::test]
async fn retry_recovers_before_dlc() {
    use camel_api::error_handler::ErrorHandlerConfig;

    let attempt = Arc::new(AtomicU32::new(0));
    let attempt_clone = Arc::clone(&attempt);
    let processor = BoxProcessor::from_fn(move |ex| {
        let a = Arc::clone(&attempt_clone);
        Box::pin(async move {
            let n = a.fetch_add(1, Ordering::SeqCst);
            if n < 2 {
                Err(CamelError::ProcessorError("not yet".into()))
            } else {
                Ok(ex)
            }
        })
    });

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let eh = ErrorHandlerConfig::dead_letter_channel("mock:dlc")
        .on_exception(|_| true)
        .retry(3)
        .with_backoff(Duration::from_millis(1), 1.0, Duration::from_millis(10))
        .build();

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-10")
        .process_fn(processor)
        .error_handler(eh)
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(400)).await;
    h.stop().await;

    // DLC should be empty — retry succeeded.
    if let Some(ep) = h.mock().get_endpoint("dlc") {
        assert_eq!(ep.get_received_exchanges().await.len(), 0);
    }
}

// ---------------------------------------------------------------------------
// Test 8: onException with specific handled_by endpoint
// ---------------------------------------------------------------------------

#[tokio::test]
async fn on_exception_handled_by_specific_endpoint() {
    use camel_api::error_handler::ErrorHandlerConfig;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let eh = ErrorHandlerConfig::dead_letter_channel("mock:default-dlc")
        .on_exception(|e| matches!(e, CamelError::ProcessorError(_)))
        .handled_by("mock:processor-errors")
        .build();

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-11")
        .process_fn(failing_step("processor error"))
        .error_handler(eh)
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(300)).await;
    h.stop().await;

    // Specific handler received it.
    let specific = h.mock().get_endpoint("processor-errors").unwrap();
    assert!(!specific.get_received_exchanges().await.is_empty());

    // Default DLC did NOT receive it.
    if let Some(ep) = h.mock().get_endpoint("default-dlc") {
        assert_eq!(ep.get_received_exchanges().await.len(), 0);
    }
}

// ---------------------------------------------------------------------------
// Test 9: Global error handler fallback
// ---------------------------------------------------------------------------

#[tokio::test]
async fn global_error_handler_fallback() {
    use camel_api::error_handler::ErrorHandlerConfig;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    h.ctx()
        .lock()
        .await
        .set_error_handler(ErrorHandlerConfig::dead_letter_channel("mock:global-dlc"));

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-12")
        .process_fn(failing_step("global test"))
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(300)).await;
    h.stop().await;

    let dlc = h.mock().get_endpoint("global-dlc").unwrap();
    assert!(!dlc.get_received_exchanges().await.is_empty());
}

// ---------------------------------------------------------------------------
// Test 10: Per-route handler overrides global
// ---------------------------------------------------------------------------

#[tokio::test]
async fn per_route_overrides_global() {
    use camel_api::error_handler::ErrorHandlerConfig;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    h.ctx()
        .lock()
        .await
        .set_error_handler(ErrorHandlerConfig::dead_letter_channel("mock:global-dlc"));

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-13")
        .process_fn(failing_step("per-route test"))
        .error_handler(ErrorHandlerConfig::dead_letter_channel("mock:route-dlc"))
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(300)).await;
    h.stop().await;

    // Per-route DLC got it.
    let route_dlc = h.mock().get_endpoint("route-dlc").unwrap();
    assert!(!route_dlc.get_received_exchanges().await.is_empty());

    // Global DLC got nothing.
    if let Some(ep) = h.mock().get_endpoint("global-dlc") {
        assert_eq!(ep.get_received_exchanges().await.len(), 0);
    }
}

// ---------------------------------------------------------------------------
// Test 11: direct: error bubbles to calling route's DLC
// ---------------------------------------------------------------------------

#[tokio::test]
async fn direct_error_bubbles_to_caller() {
    use camel_api::error_handler::ErrorHandlerConfig;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_direct()
        .with_mock()
        .build()
        .await;

    // Subroute: direct:sub → failing processor (no error handler).
    let sub_route = RouteBuilder::from("direct:sub")
        .route_id("test-route-14")
        .process_fn(failing_step("subroute failure"))
        .build()
        .unwrap();
    h.add_route(sub_route).await.unwrap();

    // Calling route: timer → direct:sub → DLC catches the bubble.
    let main_route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-15")
        .to("direct:sub")
        .error_handler(ErrorHandlerConfig::dead_letter_channel("mock:caller-dlc"))
        .build()
        .unwrap();
    h.ctx()
        .lock()
        .await
        .add_route_definition(main_route)
        .await
        .unwrap();

    h.start().await;
    tokio::time::sleep(Duration::from_millis(400)).await;
    h.stop().await;

    let dlc = h.mock().get_endpoint("caller-dlc").unwrap();
    let exchanges = dlc.get_received_exchanges().await;
    assert!(!exchanges.is_empty());
    assert!(exchanges[0].has_error());
}

// ---------------------------------------------------------------------------
// Test 12: direct: error contained in subroute (does not reach caller)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn direct_error_contained_in_subroute() {
    use camel_api::error_handler::ErrorHandlerConfig;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_direct()
        .with_mock()
        .build()
        .await;

    // Subroute has its own DLC → absorbs the error.
    let sub_route = RouteBuilder::from("direct:sub2")
        .route_id("test-route-16")
        .process_fn(failing_step("contained failure"))
        .error_handler(ErrorHandlerConfig::dead_letter_channel("mock:sub-dlc"))
        .build()
        .unwrap();
    h.add_route(sub_route).await.unwrap();

    // Calling route continues after subroute (error was absorbed).
    let main_route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-17")
        .to("direct:sub2")
        .to("mock:caller-received")
        .build()
        .unwrap();
    h.ctx()
        .lock()
        .await
        .add_route_definition(main_route)
        .await
        .unwrap();

    h.start().await;
    tokio::time::sleep(Duration::from_millis(400)).await;
    h.stop().await;

    // Sub DLC got the error.
    let sub_dlc = h.mock().get_endpoint("sub-dlc").unwrap();
    assert!(!sub_dlc.get_received_exchanges().await.is_empty());

    // Caller continued — mock:caller-received got the exchange (with error marked).
    let caller = h.mock().get_endpoint("caller-received").unwrap();
    assert!(!caller.get_received_exchanges().await.is_empty());
}

// ---------------------------------------------------------------------------
// Test 13: No error handler — route continues without crashing
// ---------------------------------------------------------------------------

#[tokio::test]
async fn no_error_handler_logs_and_continues() {
    let h = CamelTestContext::builder().with_timer().build().await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=3")
        .route_id("test-route-18")
        .process_fn(failing_step("no handler"))
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(500)).await;
    h.stop().await;
    // No panic — test passes if we get here.
}

// ---------------------------------------------------------------------------
// Test 14: Circuit breaker with error handler (end-to-end)
// ---------------------------------------------------------------------------

/// Verifies circuit breaker + error handler interaction:
///
/// - The pipeline is composed as `ErrorHandler(CircuitBreaker(Steps))`.
/// - The first `failure_threshold` errors pass through the circuit breaker
///   (Closed state), hit the error handler, and are routed to the DLC.
/// - After the threshold, the circuit opens. `poll_ready()` returns
///   `CamelError::CircuitOpen`, and the pipeline task backs off (1s sleep)
///   then retries. Since `open_duration` is 60s (much longer than the test),
///   the circuit stays open for the rest of the test.
/// - Meanwhile, the timer consumer keeps producing exchanges into the channel,
///   but the pipeline is stuck in the backoff loop and never processes them.
/// - Result: DLC receives exactly `failure_threshold` exchanges; `mock:sink`
///   receives zero.
#[tokio::test]
async fn circuit_breaker_with_error_handler() {
    use camel_api::error_handler::ErrorHandlerConfig;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=5")
        .route_id("test-route-19")
        .process_fn(failing_step("cb test failure"))
        .circuit_breaker(
            CircuitBreakerConfig::new()
                .failure_threshold(2)
                .open_duration(Duration::from_secs(60)),
        )
        .error_handler(ErrorHandlerConfig::dead_letter_channel("mock:dlc"))
        .to("mock:sink")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    // Give enough time for all 5 timer ticks to fire (5 × 50ms = 250ms).
    // The circuit opens after 2 failures. The pipeline backs off in a
    // retry loop (1s sleep) rather than breaking, but since open_duration
    // is 60s, no further exchanges are processed during this window.
    tokio::time::sleep(Duration::from_millis(500)).await;
    h.stop().await;

    // DLC received exactly the 2 exchanges that passed through the CB
    // before it opened — each marked with an error.
    let dlc = h.mock().get_endpoint("dlc").unwrap();
    let dlc_exchanges = dlc.get_received_exchanges().await;
    assert_eq!(
        dlc_exchanges.len(),
        2,
        "DLC should receive exactly failure_threshold (2) exchanges"
    );
    for ex in &dlc_exchanges {
        assert!(ex.has_error(), "Each DLC exchange should carry an error");
    }

    // mock:sink received nothing — every exchange failed before reaching it.
    if let Some(sink) = h.mock().get_endpoint("sink") {
        assert_eq!(
            sink.get_received_exchanges().await.len(),
            0,
            "mock:sink should receive zero exchanges"
        );
    }
}

// ---------------------------------------------------------------------------
// Splitter EIP integration tests
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Test 15: Split with timer and mock (end-to-end)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn split_with_timer_and_mock() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    // Timer fires once, body = "line1\nline2\nline3"
    // Split by lines, each fragment goes to mock:per-line
    // After split, aggregated result goes to mock:final
    let route = RouteBuilder::from("timer:split-test?period=100&repeatCount=1")
        .route_id("test-route-20")
        .process(|mut ex: camel_api::Exchange| async move {
            ex.input.body = camel_api::body::Body::Text("line1\nline2\nline3".to_string());
            Ok(ex)
        })
        .split(SplitterConfig::new(split_body_lines()).aggregation(AggregationStrategy::CollectAll))
        .to("mock:per-line")
        .end_split()
        .to("mock:final")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    h.stop().await;

    // Each line should have been sent to mock:per-line
    let per_line = h.mock().get_endpoint("per-line").unwrap();
    let per_line_count = per_line.get_received_exchanges().await.len();
    assert_eq!(
        per_line_count, 3,
        "Expected 3 per-line exchanges, got {per_line_count}"
    );

    // The aggregated result should have been sent to mock:final
    let final_ep = h.mock().get_endpoint("final").unwrap();
    let final_exchanges = final_ep.get_received_exchanges().await;
    assert_eq!(
        final_exchanges.len(),
        1,
        "Expected 1 final exchange, got {}",
        final_exchanges.len()
    );

    // CollectAll produces a JSON array of the fragment bodies
    let expected = serde_json::json!(["line1", "line2", "line3"]);
    match &final_exchanges[0].input.body {
        camel_api::body::Body::Json(v) => assert_eq!(
            *v, expected,
            "CollectAll should produce JSON array of fragment bodies"
        ),
        other => panic!("Expected JSON body from CollectAll, got {other:?}"),
    }
}

// ---------------------------------------------------------------------------
// Test 16: Split with error handler (stop_on_exception + DLC)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn split_with_error_handler() {
    use camel_api::error_handler::ErrorHandlerConfig;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:split-err?period=100&repeatCount=1")
        .route_id("test-route-21")
        .process(|mut ex: camel_api::Exchange| async move {
            ex.input.body = camel_api::body::Body::Text("a\nb".to_string());
            Ok(ex)
        })
        .error_handler(ErrorHandlerConfig::dead_letter_channel("mock:dlc"))
        .split(SplitterConfig::new(split_body_lines()).stop_on_exception(true))
        .process_fn(failing_step("fragment boom"))
        .end_split()
        .to("mock:sink")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    h.stop().await;

    // The split error should propagate up to the route's error handler (DLC)
    let dlc = h.mock().get_endpoint("dlc").unwrap();
    let dlc_count = dlc.get_received_exchanges().await.len();
    assert_eq!(
        dlc_count, 1,
        "Expected exactly 1 DLC exchange (stop_on_exception), got {dlc_count}"
    );

    // The sink should NOT have received anything (error stops pipeline)
    let sink = h.mock().get_endpoint("sink").unwrap();
    let sink_count = sink.get_received_exchanges().await.len();
    assert_eq!(sink_count, 0, "Expected 0 sink exchanges, got {sink_count}");
}

// ---------------------------------------------------------------------------
// File component integration tests
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Test 17: File consumer → Mock (read files from directory)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn file_consumer_to_mock() {
    let dir = tempfile::tempdir().unwrap();
    let dir_path = dir.path().to_str().unwrap();

    std::fs::write(dir.path().join("a.txt"), "alpha").unwrap();
    std::fs::write(dir.path().join("b.txt"), "beta").unwrap();

    let h = CamelTestContext::builder()
        .with_component(FileComponent::new())
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from(&format!(
        "file:{dir_path}?noop=true&initialDelay=0&delay=100"
    ))
    .route_id("test-file-consumer")
    .to("mock:result")
    .build()
    .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("result").unwrap();
    let exchanges = endpoint.get_received_exchanges().await;
    assert!(
        exchanges.len() >= 2,
        "Should have read at least 2 files, got {}",
        exchanges.len()
    );

    for ex in &exchanges {
        assert!(ex.input.header("CamelFileName").is_some());
        assert!(ex.input.header("CamelFileNameOnly").is_some());
    }
}

// ---------------------------------------------------------------------------
// Test 18: Timer → File producer (write files)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn timer_to_file_producer() {
    let dir = tempfile::tempdir().unwrap();
    let dir_path = dir.path().to_str().unwrap();

    let h = CamelTestContext::builder()
        .with_timer()
        .with_component(FileComponent::new())
        .build()
        .await;

    let route = RouteBuilder::from("timer:write-test?period=50&repeatCount=2")
        .route_id("test-route-22")
        .set_header("CamelFileName", Value::String("output.txt".into()))
        .to(format!("file:{dir_path}?fileExist=Append"))
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    h.stop().await;

    assert!(
        dir.path().join("output.txt").exists(),
        "File should have been written"
    );
}

// ---------------------------------------------------------------------------
// Test 19: File consumer → Transform → File producer (file-to-file pipeline)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn file_to_file_pipeline() {
    let input_dir = tempfile::tempdir().unwrap();
    let output_dir = tempfile::tempdir().unwrap();
    let input_path = input_dir.path().to_str().unwrap();
    let output_path = output_dir.path().to_str().unwrap();

    std::fs::write(input_dir.path().join("source.txt"), "hello world").unwrap();

    let h = CamelTestContext::builder()
        .with_component(FileComponent::new())
        .build()
        .await;

    let route = RouteBuilder::from(&format!(
        "file:{input_path}?noop=true&initialDelay=0&delay=100"
    ))
    .route_id("test-file-pipeline")
    .to(format!("file:{output_path}"))
    .build()
    .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    h.stop().await;

    assert!(
        output_dir.path().join("source.txt").exists(),
        "File should have been copied to output directory"
    );
    let content = std::fs::read_to_string(output_dir.path().join("source.txt")).unwrap();
    assert_eq!(content, "hello world");
}

// ---------------------------------------------------------------------------
// HTTP component integration tests
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Test 20: HTTP component registration and endpoint creation
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_component_registration_and_endpoint_creation() {
    use camel_component::Component;

    let component = HttpComponent::new();

    // Verify component scheme
    assert_eq!(component.scheme(), "http");

    // Verify endpoint can be created with config
    let endpoint = component
        .create_endpoint("http://example.com/api?httpMethod=POST&connectTimeout=5000")
        .unwrap();
    assert!(endpoint.uri().contains("httpMethod=POST"));
}

// ---------------------------------------------------------------------------
// Test 21: HTTP query params are forwarded (Bug #3 verification)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_query_params_forwarding_config() {
    use camel_component_http::HttpEndpointConfig;
    use camel_endpoint::UriConfig;

    // Verify config parsing forwards non-Camel query params
    let config = HttpEndpointConfig::from_uri(
        "http://api.example.com/v1/users?apiKey=secret123&httpMethod=GET&token=abc456",
    )
    .unwrap();

    // apiKey and token should be preserved for forwarding
    assert!(
        config.query_params.contains_key("apiKey"),
        "apiKey should be preserved"
    );
    assert!(
        config.query_params.contains_key("token"),
        "token should be preserved"
    );
    assert_eq!(config.query_params.get("apiKey").unwrap(), "secret123");
    assert_eq!(config.query_params.get("token").unwrap(), "abc456");

    // httpMethod should NOT be in query_params (it's a Camel option)
    assert!(
        !config.query_params.contains_key("httpMethod"),
        "httpMethod should not be forwarded"
    );
}

// ===========================================================================
// HTTP end-to-end integration tests (wiremock)
//
// These tests exercise the full pipeline path:
//   Timer/Direct → HttpProducer → real HTTP request → wiremock → Mock
//
// Unlike tests 20-21 which only verify config parsing, these prove that
// the HTTP component actually sends requests and maps responses correctly
// when wired into a CamelContext pipeline.
// ===========================================================================

// ---------------------------------------------------------------------------
// Test 22: HTTP GET end-to-end — timer fires, HTTP producer GETs wiremock,
//          response body lands in mock endpoint
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_get_e2e() {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/greeting"))
        .respond_with(ResponseTemplate::new(200).set_body_string("hello from wiremock"))
        .expect(1)
        .mount(&server)
        .await;

    // Timer produces a non-empty body so resolve_method would pick POST.
    // Force GET via httpMethod param (same as Apache Camel usage).
    let http_uri = format!(
        "http://127.0.0.1:{}/api/greeting?httpMethod=GET&allowPrivateIps=true",
        server.address().port()
    );

    let h = CamelTestContext::builder()
        .with_timer()
        .with_component(HttpComponent::new())
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-23")
        .to(&http_uri)
        .to("mock:result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(500)).await;
    h.stop().await;

    // Verify mock captured the exchange with response body
    let endpoint = h.mock().get_endpoint("result").unwrap();
    endpoint.assert_exchange_count(1).await;

    let exchanges = endpoint.get_received_exchanges().await;
    let ex = &exchanges[0];

    // Response body should be the wiremock response (arrives as Body::Bytes)
    match &ex.input.body {
        camel_api::body::Body::Bytes(b) => {
            assert_eq!(std::str::from_utf8(b).unwrap(), "hello from wiremock");
        }
        other => panic!("expected Body::Bytes, got {:?}", other),
    }

    // CamelHttpResponseCode header should be 200
    assert_eq!(
        ex.input.header("CamelHttpResponseCode"),
        Some(&serde_json::Value::Number(200.into()))
    );
}

// ---------------------------------------------------------------------------
// Test 23: HTTP POST with body — set_header sets method, body is forwarded
//          to wiremock, response captured by mock
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_post_with_body_e2e() {
    use wiremock::matchers::{body_string, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/api/data"))
        .and(body_string("payload-from-camel"))
        .respond_with(ResponseTemplate::new(201).set_body_string("created"))
        .expect(1)
        .mount(&server)
        .await;

    let http_uri = format!(
        "http://127.0.0.1:{}/api/data?httpMethod=POST&allowPrivateIps=true",
        server.address().port()
    );

    let h = CamelTestContext::builder()
        .with_timer()
        .with_component(HttpComponent::new())
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-24")
        .map_body(|_body| camel_api::body::Body::Text("payload-from-camel".into()))
        .to(&http_uri)
        .to("mock:result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(500)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("result").unwrap();
    endpoint.assert_exchange_count(1).await;

    let exchanges = endpoint.get_received_exchanges().await;
    let ex = &exchanges[0];

    // Status 201
    assert_eq!(
        ex.input.header("CamelHttpResponseCode"),
        Some(&serde_json::Value::Number(201.into()))
    );

    // Response body
    match &ex.input.body {
        camel_api::body::Body::Bytes(b) => {
            assert_eq!(std::str::from_utf8(b).unwrap(), "created");
        }
        other => panic!("expected Body::Bytes, got {:?}", other),
    }
}

// ---------------------------------------------------------------------------
// Test 24: HTTP response headers are mapped into exchange headers
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_response_headers_mapped_e2e() {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/headers"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("x-custom-header", "custom-value")
                .insert_header("x-request-id", "req-42")
                .set_body_string("ok"),
        )
        .expect(1)
        .mount(&server)
        .await;

    let http_uri = format!(
        "http://127.0.0.1:{}/api/headers?httpMethod=GET&allowPrivateIps=true",
        server.address().port()
    );

    let h = CamelTestContext::builder()
        .with_timer()
        .with_component(HttpComponent::new())
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-25")
        .to(&http_uri)
        .to("mock:result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(500)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("result").unwrap();
    endpoint.assert_exchange_count(1).await;

    let exchanges = endpoint.get_received_exchanges().await;
    let ex = &exchanges[0];

    // Custom response headers should be mapped into exchange headers
    assert_eq!(
        ex.input.header("x-custom-header"),
        Some(&serde_json::Value::String("custom-value".into()))
    );
    assert_eq!(
        ex.input.header("x-request-id"),
        Some(&serde_json::Value::String("req-42".into()))
    );
}

// ---------------------------------------------------------------------------
// Test 25: HTTP 500 with throwExceptionOnFailure=true triggers error
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_error_handling_e2e() {
    use camel_api::error_handler::ErrorHandlerConfig;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/fail"))
        .respond_with(ResponseTemplate::new(500).set_body_string("internal server error"))
        .expect(1)
        .mount(&server)
        .await;

    // throwExceptionOnFailure=true is the default; force GET since timer has body
    let http_uri = format!(
        "http://127.0.0.1:{}/api/fail?httpMethod=GET&allowPrivateIps=true",
        server.address().port()
    );

    let h = CamelTestContext::builder()
        .with_timer()
        .with_component(HttpComponent::new())
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-26")
        .to(&http_uri)
        .error_handler(ErrorHandlerConfig::dead_letter_channel("mock:dlc"))
        .to("mock:result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(500)).await;
    h.stop().await;

    // The exchange should have been routed to the DLC, not mock:result
    let dlc = h.mock().get_endpoint("dlc").unwrap();
    let dlc_exchanges = dlc.get_received_exchanges().await;
    assert_eq!(
        dlc_exchanges.len(),
        1,
        "DLC should receive the failed exchange"
    );
    assert!(
        dlc_exchanges[0].has_error(),
        "Exchange should carry an error"
    );

    // mock:result should NOT have received anything
    if let Some(result) = h.mock().get_endpoint("result") {
        assert_eq!(
            result.get_received_exchanges().await.len(),
            0,
            "mock:result should not receive the failed exchange"
        );
    }
}

// ---------------------------------------------------------------------------
// Aggregator EIP integration tests
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Test 26 (Aggregator): collect_all — 9 timer fires, orderId cycles A/B/C,
//          completionSize=3, expect 3 batches each with Body::Json([...])
// ---------------------------------------------------------------------------

#[tokio::test]
async fn aggregator_collect_all() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let counter = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
    let counter_clone = std::sync::Arc::clone(&counter);

    let route = RouteBuilder::from("timer:agg-test?period=1&repeatCount=9")
        .route_id("test-route-27")
        .process(move |mut ex: camel_api::Exchange| {
            let c = std::sync::Arc::clone(&counter_clone);
            async move {
                let n = c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                let key = ["A", "B", "C"][(n % 3) as usize];
                ex.input
                    .headers
                    .insert("orderId".to_string(), serde_json::json!(key));
                ex.input.body = camel_api::body::Body::Text(format!("item-{n}"));
                Ok(ex)
            }
        })
        .aggregate(
            AggregatorConfig::correlate_by("orderId")
                .complete_when_size(3)
                .build(),
        )
        .to("mock:aggregated")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    h.stop().await;

    // 9 exchanges total: 6 pending (Body::Empty) + 3 completed (Body::Json).
    // The aggregator emits all exchanges; pending ones have Body::Empty.
    let endpoint = h.mock().get_endpoint("aggregated").unwrap();
    let exchanges = endpoint.get_received_exchanges().await;

    let completed: Vec<_> = exchanges
        .iter()
        .filter(|e| e.property("CamelAggregatorPending").is_none())
        .collect();
    assert_eq!(
        completed.len(),
        3,
        "expected 3 completed batches, got {}",
        completed.len()
    );

    for ex in &completed {
        let camel_api::body::Body::Json(v) = &ex.input.body else {
            panic!("expected Body::Json, got {:?}", ex.input.body);
        };
        let arr = v.as_array().expect("expected JSON array");
        assert_eq!(arr.len(), 3, "each batch should have 3 items");
    }
}

// ---------------------------------------------------------------------------
// Test 27 (Aggregator): custom_strategy — 4 timer fires with key "X",
//          custom fold concatenates bodies with "+", completionSize=4,
//          expect 1 exchange with body "0+1+2+3"
// ---------------------------------------------------------------------------

#[tokio::test]
async fn aggregator_custom_strategy() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let counter = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
    let counter_clone = std::sync::Arc::clone(&counter);

    let fold_fn: camel_api::aggregator::AggregationFn =
        std::sync::Arc::new(|mut acc: camel_api::Exchange, next: camel_api::Exchange| {
            let a = acc.input.body.as_text().unwrap_or("").to_string();
            let b = next.input.body.as_text().unwrap_or("").to_string();
            acc.input.body = camel_api::body::Body::Text(format!("{a}+{b}"));
            acc
        });

    let route = RouteBuilder::from("timer:agg-custom?period=1&repeatCount=4")
        .route_id("test-route-28")
        .process(move |mut ex: camel_api::Exchange| {
            let c = std::sync::Arc::clone(&counter_clone);
            async move {
                let n = c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                ex.input
                    .headers
                    .insert("key".to_string(), serde_json::json!("X"));
                ex.input.body = camel_api::body::Body::Text(n.to_string());
                Ok(ex)
            }
        })
        .aggregate(
            AggregatorConfig::correlate_by("key")
                .complete_when_size(4)
                .strategy(camel_api::aggregator::AggregationStrategy::Custom(fold_fn))
                .build(),
        )
        .to("mock:custom-agg")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("custom-agg").unwrap();
    let exchanges = endpoint.get_received_exchanges().await;

    // 4 exchanges total: 3 pending (Body::Empty) + 1 completed (Body::Text "0+1+2+3").
    let completed: Vec<_> = exchanges
        .iter()
        .filter(|e| e.property("CamelAggregatorPending").is_none())
        .collect();
    assert_eq!(
        completed.len(),
        1,
        "expected 1 completed aggregate, got {}",
        completed.len()
    );
    assert_eq!(completed[0].input.body.as_text(), Some("0+1+2+3"));
}

// ---------------------------------------------------------------------------
// Test 28 (Aggregator): scatter-gather — timer fires 3 times, each fire
//          is aggregated by timer name, completionSize=3,
//          expect 1 exchange at mock:scatter-gather
// ---------------------------------------------------------------------------

#[tokio::test]
async fn aggregator_scatter_gather() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    // Timer fires 3 times with the same timer name "scatter".
    // The aggregator groups by CamelTimerName (all 3 share key "scatter")
    // and emits when completionSize=3 is reached.
    let route = RouteBuilder::from("timer:scatter?period=10&repeatCount=3")
        .route_id("test-route-29")
        .aggregate(
            AggregatorConfig::correlate_by("CamelTimerName")
                .complete_when_size(3)
                .build(),
        )
        .to("mock:scatter-gather")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    h.stop().await;

    // 3 exchanges: 2 pending + 1 completed (Body::Json array of 3).
    let endpoint = h.mock().get_endpoint("scatter-gather").unwrap();
    let exchanges = endpoint.get_received_exchanges().await;

    let completed: Vec<_> = exchanges
        .iter()
        .filter(|e| e.property("CamelAggregatorPending").is_none())
        .collect();
    assert_eq!(
        completed.len(),
        1,
        "expected 1 completed aggregate, got {}",
        completed.len()
    );
}

// ---------------------------------------------------------------------------
// Test 29 (Aggregator): complete on inactivity timeout
// ---------------------------------------------------------------------------

#[tokio::test]
async fn aggregator_agg_timeout_emits_after_inactivity() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:agg-timeout?period=50&repeatCount=1")
        .route_id("agg-timeout-route")
        .process(|mut ex: camel_api::Exchange| async move {
            ex.input.set_header("key", Value::String("A".into()));
            Ok(ex)
        })
        .aggregate(
            AggregatorConfig::correlate_by("key")
                .complete_on_timeout(std::time::Duration::from_millis(200))
                .build(),
        )
        .to("mock:agg-timeout-result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    // Wait for timeout to fire (200ms + margin)
    tokio::time::sleep(std::time::Duration::from_millis(450)).await;

    h.stop().await;

    let endpoint = h.mock().get_endpoint("agg-timeout-result").unwrap();
    endpoint.assert_exchange_count(1).await;
}

// ---------------------------------------------------------------------------
// Test 30 (Aggregator): force completion on stop flushes pending group
// ---------------------------------------------------------------------------

#[tokio::test]
async fn aggregator_agg_force_completion_on_stop() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:agg-force?period=50&repeatCount=1")
        .route_id("agg-force-route")
        .process(|mut ex: camel_api::Exchange| async move {
            ex.input.set_header("key", Value::String("A".into()));
            Ok(ex)
        })
        .aggregate(
            AggregatorConfig::correlate_by("key")
                .complete_when_size(100)
                .force_completion_on_stop(true)
                .build(),
        )
        .to("mock:agg-force-result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    // Ensure one timer exchange is produced and remains pending.
    tokio::time::sleep(std::time::Duration::from_millis(80)).await;

    h.stop().await;

    let endpoint = h.mock().get_endpoint("agg-force-result").unwrap();
    endpoint.assert_exchange_count(1).await;
}

// ---------------------------------------------------------------------------
// set_body / set_body_fn / set_header_fn integration tests
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Test 29: set_body("enriched") replaces body end-to-end
// ---------------------------------------------------------------------------

#[tokio::test]
async fn route_set_body_static() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:set-body-static?period=50&repeatCount=1")
        .route_id("test-route-30")
        .set_body("enriched")
        .to("mock:set-body-static")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(Duration::from_millis(200)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("set-body-static").unwrap();
    endpoint.assert_exchange_count(1).await;

    let exchanges = endpoint.get_received_exchanges().await;
    assert_eq!(
        exchanges[0].input.body.as_text(),
        Some("enriched"),
        "set_body should replace body with static string"
    );
}

// ---------------------------------------------------------------------------
// Test 30: set_body_fn reads exchange and transforms body
// ---------------------------------------------------------------------------

#[tokio::test]
async fn route_set_body_fn() {
    use camel_api::body::Body;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:set-body-fn?period=50&repeatCount=1")
        .route_id("test-route-31")
        // First set a known body so set_body_fn has something to read.
        .set_body("hello")
        .set_body_fn(|ex: &camel_api::Exchange| {
            let text = ex.input.body.as_text().unwrap_or("");
            Body::Text(text.to_uppercase())
        })
        .to("mock:set-body-fn")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(Duration::from_millis(200)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("set-body-fn").unwrap();
    endpoint.assert_exchange_count(1).await;

    let exchanges = endpoint.get_received_exchanges().await;
    assert_eq!(
        exchanges[0].input.body.as_text(),
        Some("HELLO"),
        "set_body_fn should uppercase the body read from the exchange"
    );
}

// ---------------------------------------------------------------------------
// Test 31: set_header_fn reads body and writes it into a header
// ---------------------------------------------------------------------------

#[tokio::test]
async fn route_set_header_fn() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:set-header-fn?period=50&repeatCount=1")
        .route_id("test-route-32")
        // Set a known body first so set_header_fn can echo it.
        .set_body("ping")
        .set_header_fn("echo", |ex: &camel_api::Exchange| {
            Value::String(ex.input.body.as_text().unwrap_or("").into())
        })
        .to("mock:set-header-fn")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(Duration::from_millis(200)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("set-header-fn").unwrap();
    endpoint.assert_exchange_count(1).await;

    let exchanges = endpoint.get_received_exchanges().await;
    assert_eq!(
        exchanges[0].input.header("echo"),
        Some(&Value::String("ping".into())),
        "set_header_fn should copy body text into the 'echo' header"
    );
}

// ---------------------------------------------------------------------------
// Test 26: HTTP query params forwarded in actual request to wiremock
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_query_params_forwarded_e2e() {
    use wiremock::matchers::{method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/search"))
        .and(query_param("apiKey", "secret123"))
        .and(query_param("lang", "rust"))
        .respond_with(ResponseTemplate::new(200).set_body_string("found"))
        .expect(1)
        .mount(&server)
        .await;

    // Non-Camel params (apiKey, lang) are forwarded; httpMethod is consumed by Camel
    let http_uri = format!(
        "http://127.0.0.1:{}/api/search?httpMethod=GET&allowPrivateIps=true&apiKey=secret123&lang=rust",
        server.address().port()
    );

    let h = CamelTestContext::builder()
        .with_timer()
        .with_component(HttpComponent::new())
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
        .route_id("test-route-33")
        .to(&http_uri)
        .to("mock:result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(500)).await;
    h.stop().await;

    let endpoint = h.mock().get_endpoint("result").unwrap();
    endpoint.assert_exchange_count(1).await;

    let exchanges = endpoint.get_received_exchanges().await;
    match &exchanges[0].input.body {
        camel_api::body::Body::Bytes(b) => {
            assert_eq!(std::str::from_utf8(b).unwrap(), "found");
        }
        other => panic!("expected Body::Bytes, got {:?}", other),
    }
}

// ---------------------------------------------------------------------------
// Stop EIP: .stop() inside filter halts outer pipeline for matching exchanges
// ---------------------------------------------------------------------------

/// Apache Camel semantics: exchanges matching the filter predicate hit .stop()
/// and do NOT continue to the outer pipeline. Non-matching exchanges skip the
/// filter block entirely and DO continue to the outer pipeline.
///
/// Route:
///   timer (4 exchanges, n=0..3, even=active=true)
///     .filter(active=true)
///       .to("mock:inner")   ← only active=true exchanges
///       .stop()             ← active=true exchanges stop here
///     .end_filter()
///     .to("mock:outer")     ← only active=false exchanges reach here
#[tokio::test]
async fn stop_inside_filter_prevents_outer_pipeline() {
    use std::time::Duration;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let counter = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
    let counter_clone = std::sync::Arc::clone(&counter);

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=4")
        .route_id("test-route-34")
        .process(move |mut ex: camel_api::Exchange| {
            let c = std::sync::Arc::clone(&counter_clone);
            async move {
                let n = c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                ex.input
                    .set_header("active", Value::Bool(n.is_multiple_of(2)));
                Ok(ex)
            }
        })
        .filter(|ex| ex.input.header("active") == Some(&Value::Bool(true)))
        .to("mock:inner")
        .stop() // active=true exchanges stop here
        .end_filter()
        .to("mock:outer") // only active=false exchanges should reach here
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(Duration::from_millis(400)).await;
    h.stop().await;

    let inner = h.mock().get_endpoint("inner").unwrap();
    let outer = h.mock().get_endpoint("outer").unwrap();

    inner.assert_exchange_count(2).await; // active=true: exchanges 0 and 2
    outer.assert_exchange_count(2).await; // active=false: exchanges 1 and 3 (stopped exchanges never reach outer)
}

// ---------------------------------------------------------------------------
// Multicast EIP integration tests
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Test: Multicast sends exchange to multiple endpoints
// ---------------------------------------------------------------------------
// This test verifies that a route with Multicast correctly sends copies
// of the exchange to each endpoint defined in the multicast scope.

#[tokio::test]
async fn multicast_sends_to_multiple_endpoints() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    // Multicast: timer → [mock:a, mock:b, mock:c] → mock:final
    // Each endpoint in the multicast should receive the exchange.
    let route = RouteBuilder::from("timer:multicast-test?period=50&repeatCount=1")
        .route_id("test-route-35")
        .multicast()
        .to("mock:a")
        .to("mock:b")
        .to("mock:c")
        .end_multicast()
        .to("mock:final")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    h.stop().await;

    // Each multicast endpoint should have received 1 exchange
    let endpoint_a = h.mock().get_endpoint("a").unwrap();
    let endpoint_b = h.mock().get_endpoint("b").unwrap();
    let endpoint_c = h.mock().get_endpoint("c").unwrap();
    let endpoint_final = h.mock().get_endpoint("final").unwrap();

    endpoint_a.assert_exchange_count(1).await;
    endpoint_b.assert_exchange_count(1).await;
    endpoint_c.assert_exchange_count(1).await;
    endpoint_final.assert_exchange_count(1).await;
}

// ---------------------------------------------------------------------------
// Test: Multicast sets metadata properties (index, complete)
// ---------------------------------------------------------------------------
// This test verifies that MulticastService correctly sets the CAMEL_MULTICAST_INDEX
// and CAMEL_MULTICAST_COMPLETE properties on each cloned exchange.

#[tokio::test]
async fn multicast_metadata_properties() {
    use camel_processor::CAMEL_MULTICAST_INDEX;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    // Multicast with 3 endpoints - each should receive exchange with correct index
    let route = RouteBuilder::from("timer:multicast-meta?period=50&repeatCount=1")
        .route_id("test-route-36")
        .multicast()
        .to("mock:meta-a")
        .to("mock:meta-b")
        .to("mock:meta-c")
        .end_multicast()
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    h.stop().await;

    // Verify that each endpoint received an exchange with the correct index property
    let exchanges_a = h
        .mock()
        .get_endpoint("meta-a")
        .unwrap()
        .get_received_exchanges()
        .await;
    let exchanges_b = h
        .mock()
        .get_endpoint("meta-b")
        .unwrap()
        .get_received_exchanges()
        .await;
    let exchanges_c = h
        .mock()
        .get_endpoint("meta-c")
        .unwrap()
        .get_received_exchanges()
        .await;

    assert_eq!(exchanges_a.len(), 1);
    assert_eq!(exchanges_b.len(), 1);
    assert_eq!(exchanges_c.len(), 1);

    // The MulticastService should set CAMEL_MULTICAST_INDEX on each exchange
    // This will FAIL with the current placeholder implementation because it
    // doesn't use MulticastService at all
    let idx_a = exchanges_a[0].property(CAMEL_MULTICAST_INDEX);
    let idx_b = exchanges_b[0].property(CAMEL_MULTICAST_INDEX);
    let idx_c = exchanges_c[0].property(CAMEL_MULTICAST_INDEX);

    assert!(idx_a.is_some(), "meta-a should have CAMEL_MULTICAST_INDEX");
    assert!(idx_b.is_some(), "meta-b should have CAMEL_MULTICAST_INDEX");
    assert!(idx_c.is_some(), "meta-c should have CAMEL_MULTICAST_INDEX");

    // Verify correct index values
    assert_eq!(idx_a, Some(&Value::from(0i64)));
    assert_eq!(idx_b, Some(&Value::from(1i64)));
    assert_eq!(idx_c, Some(&Value::from(2i64)));
}

// ---------------------------------------------------------------------------
// Test: Multicast parallel CollectAll aggregation
// ---------------------------------------------------------------------------
// This test verifies that parallel multicast with CollectAll strategy produces
// a JSON array body containing the results from all endpoints.

#[tokio::test]
async fn multicast_parallel_collect_all() {
    use camel_api::body::Body;
    use camel_api::multicast::MulticastStrategy;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:multicast-parallel?period=50&repeatCount=1")
        .route_id("test-route-37")
        .multicast()
        .parallel(true)
        .aggregation(MulticastStrategy::CollectAll)
        .to("mock:p-a")
        .to("mock:p-b")
        .end_multicast()
        .to("mock:p-result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    h.stop().await;

    // Each parallel endpoint received one exchange
    let endpoint_a = h.mock().get_endpoint("p-a").unwrap();
    let endpoint_b = h.mock().get_endpoint("p-b").unwrap();
    let endpoint_result = h.mock().get_endpoint("p-result").unwrap();

    endpoint_a.assert_exchange_count(1).await;
    endpoint_b.assert_exchange_count(1).await;
    endpoint_result.assert_exchange_count(1).await;

    // The result endpoint should have received a JSON array body (CollectAll)
    let result_exchanges = endpoint_result.get_received_exchanges().await;
    assert_eq!(result_exchanges.len(), 1);
    assert!(
        matches!(&result_exchanges[0].input.body, Body::Json(v) if v.is_array()),
        "expected JSON array body from CollectAll aggregation, got {:?}",
        result_exchanges[0].input.body
    );
}

// ---------------------------------------------------------------------------
// Test: HTTP concurrent pipeline processes multiple requests simultaneously
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_concurrent_pipeline() {
    let h = CamelTestContext::builder()
        .with_component(HttpComponent::new())
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("http://0.0.0.0:18080/concurrent-test")
        .route_id("test-route-38")
        .process(|ex| async move {
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            Ok(ex)
        })
        .to("mock:concurrent-result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    // Give server time to start
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // Fire 5 requests concurrently
    let client = reqwest::Client::new();
    let mut handles = Vec::new();
    let start = std::time::Instant::now();
    for i in 0..5 {
        let client = client.clone();
        handles.push(tokio::spawn(async move {
            client
                .get(format!("http://127.0.0.1:18080/concurrent-test?i={i}"))
                .send()
                .await
                .unwrap()
        }));
    }

    for handle in handles {
        let resp = handle.await.unwrap();
        assert_eq!(resp.status(), 200);
    }
    let elapsed = start.elapsed();

    h.stop().await;

    // With concurrent pipeline: ~100ms (all 5 run in parallel).
    // With sequential pipeline: ~500ms (one at a time).
    // Use 350ms as threshold — generous margin but catches sequential.
    assert!(
        elapsed < std::time::Duration::from_millis(350),
        "Expected concurrent execution (<350ms), but took {:?}. \
         Pipeline may be running sequentially.",
        elapsed
    );

    let endpoint = h.mock().get_endpoint("concurrent-result").unwrap();
    endpoint.assert_exchange_count(5).await;
}

// ---------------------------------------------------------------------------
// Test: HTTP route with .sequential() override processes one at a time
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_sequential_override() {
    let h = CamelTestContext::builder()
        .with_component(HttpComponent::new())
        .with_mock()
        .build()
        .await;

    // Same slow processor, but forced sequential via .sequential()
    let route = RouteBuilder::from("http://0.0.0.0:18081/sequential-test")
        .route_id("test-route-39")
        .sequential()
        .process(|ex| async move {
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            Ok(ex)
        })
        .to("mock:sequential-result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // Fire 3 requests concurrently
    let client = reqwest::Client::new();
    let mut handles = Vec::new();
    let start = std::time::Instant::now();
    for i in 0..3 {
        let client = client.clone();
        handles.push(tokio::spawn(async move {
            client
                .get(format!("http://127.0.0.1:18081/sequential-test?i={i}"))
                .send()
                .await
                .unwrap()
        }));
    }

    for handle in handles {
        let resp = handle.await.unwrap();
        assert_eq!(resp.status(), 200);
    }
    let elapsed = start.elapsed();

    h.stop().await;

    // Sequential: ~300ms (3 * 100ms). Must be clearly above concurrent threshold.
    assert!(
        elapsed >= std::time::Duration::from_millis(250),
        "Expected sequential execution (>=250ms), but took {:?}. \
         Pipeline may be running concurrently despite .sequential() override.",
        elapsed
    );

    let endpoint = h.mock().get_endpoint("sequential-result").unwrap();
    endpoint.assert_exchange_count(3).await;
}

// ---------------------------------------------------------------------------
// Test: HTTP route with .concurrent(2) limits parallelism to 2
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_concurrent_with_semaphore_limit() {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    let h = CamelTestContext::builder()
        .with_component(HttpComponent::new())
        .with_mock()
        .build()
        .await;

    let peak = Arc::new(AtomicUsize::new(0));
    let current = Arc::new(AtomicUsize::new(0));
    let peak_clone = peak.clone();
    let current_clone = current.clone();

    // Limit to 2 concurrent pipeline executions
    let route = RouteBuilder::from("http://0.0.0.0:18082/semaphore-test")
        .route_id("test-route-40")
        .concurrent(2)
        .process(move |ex| {
            let peak = peak_clone.clone();
            let current = current_clone.clone();
            async move {
                let val = current.fetch_add(1, Ordering::SeqCst) + 1;
                // Update peak
                peak.fetch_max(val, Ordering::SeqCst);
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                current.fetch_sub(1, Ordering::SeqCst);
                Ok(ex)
            }
        })
        .to("mock:semaphore-result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // Fire 6 requests concurrently
    let client = reqwest::Client::new();
    let mut handles = Vec::new();
    for i in 0..6 {
        let client = client.clone();
        handles.push(tokio::spawn(async move {
            client
                .get(format!("http://127.0.0.1:18082/semaphore-test?i={i}"))
                .send()
                .await
                .unwrap()
        }));
    }

    for handle in handles {
        let resp = handle.await.unwrap();
        assert_eq!(resp.status(), 200);
    }

    h.stop().await;

    // Peak concurrency should be exactly 2 (semaphore limit)
    let peak_val = peak.load(Ordering::SeqCst);
    assert!(
        peak_val <= 2,
        "Expected peak concurrency <= 2, but got {}. Semaphore not working.",
        peak_val
    );

    let endpoint = h.mock().get_endpoint("semaphore-result").unwrap();
    endpoint.assert_exchange_count(6).await;
}

// ---------------------------------------------------------------------------
// Test: HTTP concurrent pipeline with circuit breaker (short duration)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_concurrent_with_circuit_breaker() {
    use camel_api::error_handler::ErrorHandlerConfig;

    let h = CamelTestContext::builder()
        .with_component(HttpComponent::new())
        .with_mock()
        .build()
        .await;

    // Use short open_duration (1s) so circuit closes quickly and requests can complete
    let route = RouteBuilder::from("http://0.0.0.0:18083/cb-test")
        .route_id("test-route-41")
        .process_fn(failing_step("concurrent cb failure"))
        .circuit_breaker(
            CircuitBreakerConfig::new()
                .failure_threshold(2)
                .open_duration(Duration::from_secs(1)),
        )
        .error_handler(ErrorHandlerConfig::dead_letter_channel("mock:dlc"))
        .to("mock:sink")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    // Give server time to start
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Send 5 requests concurrently
    let client = reqwest::Client::new();
    let mut handles = Vec::new();
    for i in 0..5 {
        let client = client.clone();
        handles.push(tokio::spawn(async move {
            client
                .get(format!("http://127.0.0.1:18083/cb-test?i={i}"))
                .send()
                .await
                .unwrap()
        }));
    }

    // All requests should complete (may take time due to circuit open backoff)
    for handle in handles {
        let resp = handle.await.unwrap();
        // Status could be 200 (DLC handled) or 500 (pipeline error)
        // We just assert it returns
        assert!(
            resp.status() == 200 || resp.status() == 500,
            "Expected 200 or 500, got {}",
            resp.status()
        );
    }

    h.stop().await;

    // Due to race conditions in concurrent mode, the circuit breaker
    // may see 2-5 failures before opening (multiple requests may be
    // in-flight simultaneously when threshold is reached)
    let dlc = h.mock().get_endpoint("dlc").unwrap();
    let dlc_exchanges = dlc.get_received_exchanges().await;
    assert!(
        dlc_exchanges.len() >= 2,
        "DLC should receive at least 2 exchanges (failure_threshold), got {}",
        dlc_exchanges.len()
    );
    assert!(
        dlc_exchanges.len() <= 5,
        "DLC should receive at most 5 exchanges (total requests), got {}",
        dlc_exchanges.len()
    );

    // All DLC exchanges should have errors
    for ex in &dlc_exchanges {
        assert!(ex.has_error(), "Each DLC exchange should carry an error");
    }

    // Mock sink receives 0 exchanges (all fail before reaching it)
    if let Some(sink) = h.mock().get_endpoint("sink") {
        assert_eq!(
            sink.get_received_exchanges().await.len(),
            0,
            "mock:sink should receive zero exchanges"
        );
    }
}

// ---------------------------------------------------------------------------
// Test: HTTP concurrent shutdown drains in-flight exchanges
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_concurrent_shutdown_drains_inflight() {
    let h = CamelTestContext::builder()
        .with_component(HttpComponent::new())
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("http://0.0.0.0:18084/shutdown-test")
        .route_id("test-route-42")
        .process(|ex| async move {
            tokio::time::sleep(Duration::from_millis(200)).await;
            Ok(ex)
        })
        .to("mock:shutdown-result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    // Give server time to start
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Send 3 requests concurrently
    let client = reqwest::Client::new();
    let mut handles = Vec::new();
    for i in 0..3 {
        let client = client.clone();
        handles.push(tokio::spawn(async move {
            client
                .get(format!("http://127.0.0.1:18084/shutdown-test?i={i}"))
                .send()
                .await
                .unwrap()
        }));
    }

    // Wait 50ms (some requests started but not completed)
    tokio::time::sleep(Duration::from_millis(50)).await;

    // Stop should wait for in-flight exchanges to drain (default 30s timeout)
    h.stop().await;

    // All 3 requests should complete
    for handle in handles {
        let resp = handle.await.unwrap();
        assert_eq!(resp.status(), 200);
    }

    // Mock should have received all 3 exchanges (drain completed)
    let endpoint = h.mock().get_endpoint("shutdown-result").unwrap();
    endpoint.assert_exchange_count(3).await;
}

// ---------------------------------------------------------------------------
// Test: HTTP concurrent error propagation to HTTP responses
// ---------------------------------------------------------------------------

#[tokio::test]
async fn http_concurrent_error_propagation() {
    let h = CamelTestContext::builder()
        .with_component(HttpComponent::new())
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("http://0.0.0.0:18085/error-test")
        .route_id("test-route-43")
        .process(|ex| async move {
            // Check query param "fail"
            let should_fail = ex
                .input
                .header("CamelHttpQuery")
                .and_then(|v| v.as_str())
                .map(|q| q.contains("fail=true"))
                .unwrap_or(false);

            if should_fail {
                Err(CamelError::ProcessorError("deliberate".into()))
            } else {
                Ok(ex)
            }
        })
        .to("mock:error-result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    // Give server time to start
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Send 4 requests concurrently: 2 with fail=true, 2 with fail=false
    let client = reqwest::Client::new();
    let mut handles = Vec::new();
    let mut fail_indices = Vec::new();

    for i in 0..4 {
        let should_fail = i % 2 == 0; // 0, 2 fail; 1, 3 succeed
        if should_fail {
            fail_indices.push(i);
        }
        let client = client.clone();
        handles.push(tokio::spawn(async move {
            let url = if should_fail {
                format!("http://127.0.0.1:18085/error-test?i={i}&fail=true")
            } else {
                format!("http://127.0.0.1:18085/error-test?i={i}&fail=false")
            };
            let resp = client.get(&url).send().await.unwrap();
            (i, should_fail, resp)
        }));
    }

    // Assert response statuses
    for handle in handles {
        let (i, should_fail, resp) = handle.await.unwrap();
        if should_fail {
            assert_eq!(
                resp.status(),
                500,
                "Request {i} with fail=true should return 500"
            );
        } else {
            assert_eq!(
                resp.status(),
                200,
                "Request {i} with fail=false should return 200"
            );
        }
    }

    h.stop().await;

    // Mock sink receives exactly 2 exchanges (the successful ones)
    let endpoint = h.mock().get_endpoint("error-result").unwrap();
    endpoint.assert_exchange_count(2).await;
}

// ---------------------------------------------------------------------------
// Choice EIP tests
// ---------------------------------------------------------------------------

// Test A: when clause routes matching exchange
#[tokio::test]
async fn choice_when_routes_matching_exchange() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    // 4 ticks: counters 1,2,3,4. Even → mock:even, odd → mock:odd.
    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=4")
        .route_id("test-route-44")
        .choice()
        .when(|ex| {
            ex.input
                .header("CamelTimerCounter")
                .and_then(|v| v.as_u64())
                .map(|n| n % 2 == 0)
                .unwrap_or(false)
        })
        .to("mock:even")
        .end_when()
        .when(|ex| {
            ex.input
                .header("CamelTimerCounter")
                .and_then(|v| v.as_u64())
                .map(|n| n % 2 != 0)
                .unwrap_or(false)
        })
        .to("mock:odd")
        .end_when()
        .end_choice()
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(std::time::Duration::from_millis(400)).await;
    h.stop().await;

    let even = h.mock().get_endpoint("even").unwrap();
    let odd = h.mock().get_endpoint("odd").unwrap();
    even.assert_exchange_count(2).await; // counters 2, 4
    odd.assert_exchange_count(2).await; // counters 1, 3
}

// Test B: otherwise fires when no when matches
#[tokio::test]
async fn choice_otherwise_fires_when_no_when_matches() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    // Counter is always set — when predicate never true (impossible header).
    // All 3 ticks go to mock:fallback via otherwise.
    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=3")
        .route_id("test-route-45")
        .choice()
        .when(|ex| ex.input.header("nonexistent").is_some())
        .to("mock:never")
        .end_when()
        .otherwise()
        .to("mock:fallback")
        .end_otherwise()
        .end_choice()
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    h.stop().await;

    let fallback = h.mock().get_endpoint("fallback").unwrap();
    fallback.assert_exchange_count(3).await;

    // The "never" endpoint must not have received anything.
    // Note: MockComponent registers endpoints during route resolution, so
    // get_endpoint("never") returns Some, but with 0 exchanges.
    if let Some(never) = h.mock().get_endpoint("never") {
        never.assert_exchange_count(0).await;
    }
}

// Test C: no match and no otherwise → exchange continues past choice
#[tokio::test]
async fn choice_no_match_no_otherwise_continues() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    // when predicate never true. No otherwise. Exchange continues to mock:after.
    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=3")
        .route_id("test-route-46")
        .choice()
        .when(|ex| ex.input.header("nonexistent").is_some())
        .to("mock:never")
        .end_when()
        .end_choice()
        .to("mock:after") // all 3 exchanges reach here
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    h.stop().await;

    let after = h.mock().get_endpoint("after").unwrap();
    after.assert_exchange_count(3).await;

    // Verify the "never" endpoint (registered during route resolution) received nothing.
    if let Some(never) = h.mock().get_endpoint("never") {
        never.assert_exchange_count(0).await;
    }
}

// Test D: short-circuit — only first matching when fires
#[tokio::test]
async fn choice_short_circuits_first_match() {
    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    // Both whens always match (|_| true). First should always win.
    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=4")
        .route_id("test-route-47")
        .choice()
        .when(|_ex| true)
        .to("mock:first")
        .end_when()
        .when(|_ex| true)
        .to("mock:second")
        .end_when()
        .end_choice()
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;
    tokio::time::sleep(std::time::Duration::from_millis(400)).await;
    h.stop().await;

    let first = h.mock().get_endpoint("first").unwrap();
    first.assert_exchange_count(4).await; // all 4 go to first

    // "second" must not have received anything.
    // Note: MockComponent registers endpoints during route resolution, so
    // get_endpoint("second") returns Some, but with 0 exchanges.
    if let Some(second) = h.mock().get_endpoint("second") {
        second.assert_exchange_count(0).await;
    }
}

// ---------------------------------------------------------------------------
// Test: XML body pipeline — direct:xml-in → convert_body_to(Text) → mock:xml-out
// ---------------------------------------------------------------------------

#[tokio::test]
async fn xml_body_pipeline() {
    use camel_api::body::Body;
    use camel_api::{Exchange, Message};
    use camel_component_direct::DirectComponent;
    use tower::util::ServiceExt;

    let direct = DirectComponent::new();
    let h = CamelTestContext::builder()
        .with_component(direct)
        .with_mock()
        .build()
        .await;

    // Route: direct:xml-in → convert_body_to(Text) → mock:xml-out
    let route = RouteBuilder::from("direct:xml-in")
        .route_id("test-xml-body-pipeline")
        .convert_body_to(camel_api::BodyType::Text)
        .to("mock:xml-out")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    // Give the route a moment to start
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    // Create a producer to send an exchange with XML body
    let producer = {
        let ctx = h.ctx().lock().await;
        let producer_ctx = ctx.producer_context();
        let registry = ctx.registry();
        let component = registry.get("direct").unwrap();
        let endpoint = component.create_endpoint("direct:xml-in").unwrap();
        endpoint.create_producer(&producer_ctx).unwrap()
    };

    // Send exchange with Body::Xml
    let xml_content = "<root><msg>hello</msg></root>";
    let exchange = Exchange::new(Message::new(Body::Xml(xml_content.to_string())));
    let _ = producer.oneshot(exchange).await.unwrap();

    // Wait for the exchange to be processed
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    h.stop().await;

    // Assert mock received 1 exchange
    let endpoint = h.mock().get_endpoint("xml-out").unwrap();
    endpoint.assert_exchange_count(1).await;

    // Assert the received body is Body::Text (since we converted Xml→Text)
    let exchanges = endpoint.get_received_exchanges().await;
    assert_eq!(
        exchanges[0].input.body.as_text(),
        Some(xml_content),
        "Body should be converted from Xml to Text"
    );
}

// ---------------------------------------------------------------------------
// Test: New mock assertion API — reference migration example
// ---------------------------------------------------------------------------

/// Demonstrates the new `await_exchanges` + `ExchangeAssert` API.
///
/// This is the reference example for migrating away from the old pattern:
///
/// ```
/// // OLD (fragile — fixed sleep):
/// tokio::time::sleep(Duration::from_millis(200)).await;
/// let received = mock.get_received_exchanges().await;
/// assert_eq!(received.len(), 3);
/// assert_eq!(received[0].input.body.as_text(), Some("timer://tick tick #1"));
///
/// // NEW (reliable — Notify-based):
/// ep.await_exchanges(3, Duration::from_millis(2000)).await;
/// ep.exchange(0).assert_body_text("timer://tick tick #1");
/// ```
///
/// Timer body format: `"timer://<name> tick #<n>"` (e.g. `"timer://tick tick #1"`).
#[tokio::test(flavor = "multi_thread")]
async fn mock_new_assertion_api() {
    use std::time::Duration;

    let h = CamelTestContext::builder()
        .with_timer()
        .with_mock()
        .build()
        .await;

    let route = RouteBuilder::from("timer:tick?period=50&repeatCount=3")
        .route_id("test-mock-new-assertion-api")
        .to("mock:assert-api-result")
        .build()
        .unwrap();

    h.add_route(route).await.unwrap();
    h.start().await;

    let ep = h.mock().get_endpoint("assert-api-result").unwrap();

    // Wait for exactly 3 exchanges — no sleep needed.
    ep.await_exchanges(3, Duration::from_millis(2000)).await;

    // Timer body format: "timer://<name> tick #<n>"
    ep.exchange(0).assert_body_text("timer://tick tick #1");
    ep.exchange(1).assert_body_text("timer://tick tick #2");
    ep.exchange(2).assert_body_text("timer://tick tick #3");

    h.stop().await;
}