elif-http 0.8.8

HTTP server core for the elif.rs LLM-friendly web framework
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
//! # Middleware V2
//!
//! New middleware system with handle(request, next) pattern for Laravel-style simplicity.
//! This is the new middleware API that will replace the current one.

use crate::request::{ElifMethod, ElifRequest};
use crate::response::ElifResponse;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::Duration;
// use axum::extract::Request;
// use super::Middleware as OldMiddleware; // Import the old middleware trait

/// Type alias for boxed future in Next
pub type NextFuture<'a> = Pin<Box<dyn Future<Output = ElifResponse> + Send + 'a>>;

/// Next represents the rest of the middleware chain
pub struct Next {
    handler: Box<dyn FnOnce(ElifRequest) -> NextFuture<'static> + Send>,
}

impl Next {
    /// Create a new Next with a handler function
    pub fn new<F>(handler: F) -> Self
    where
        F: FnOnce(ElifRequest) -> NextFuture<'static> + Send + 'static,
    {
        Self {
            handler: Box::new(handler),
        }
    }

    /// Run the rest of the middleware chain with the given request
    pub async fn run(self, request: ElifRequest) -> ElifResponse {
        (self.handler)(request).await
    }

    /// Run the rest of the middleware chain and return a boxed future
    /// This is a convenience method for middleware implementations
    pub fn call(self, request: ElifRequest) -> NextFuture<'static> {
        Box::pin(async move { self.run(request).await })
    }
}

/// New middleware trait with Laravel-style handle(request, next) pattern
/// Uses boxed futures to be dyn-compatible
pub trait Middleware: Send + Sync + std::fmt::Debug {
    /// Handle the request and call the next middleware in the chain
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static>;

    /// Optional middleware name for debugging
    fn name(&self) -> &'static str {
        "Middleware"
    }
}

/// Middleware pipeline for the new system
#[derive(Debug)]
pub struct MiddlewarePipelineV2 {
    middleware: Vec<Arc<dyn Middleware>>,
}

impl Default for MiddlewarePipelineV2 {
    fn default() -> Self {
        Self::new()
    }
}

impl MiddlewarePipelineV2 {
    /// Create a new empty middleware pipeline
    pub fn new() -> Self {
        Self {
            middleware: Vec::new(),
        }
    }

    /// Add middleware to the pipeline
    pub fn add<M: Middleware + 'static>(mut self, middleware: M) -> Self {
        self.middleware.push(Arc::new(middleware));
        self
    }

    /// Add middleware to the pipeline (mutable version)
    pub fn add_mut<M: Middleware + 'static>(&mut self, middleware: M) {
        self.middleware.push(Arc::new(middleware));
    }

    /// Create a pipeline from a vector of Arc<dyn Middleware>
    pub fn from_middleware_vec(middleware: Vec<Arc<dyn Middleware>>) -> Self {
        Self { middleware }
    }

    /// Add an already-boxed middleware to the pipeline
    pub fn add_boxed(mut self, middleware: Arc<dyn Middleware>) -> Self {
        self.middleware.push(middleware);
        self
    }

    /// Extend this pipeline with middleware from another pipeline
    /// The middleware from this pipeline will execute before the middleware from the other pipeline
    pub fn extend(mut self, other: Self) -> Self {
        self.middleware.extend(other.middleware);
        self
    }

    /// Execute the middleware pipeline with a handler
    pub async fn execute<F, Fut>(&self, request: ElifRequest, handler: F) -> ElifResponse
    where
        F: FnOnce(ElifRequest) -> Fut + Send + 'static,
        Fut: Future<Output = ElifResponse> + Send + 'static,
    {
        let mut chain =
            Box::new(move |req: ElifRequest| Box::pin(handler(req)) as NextFuture<'static>)
                as Box<dyn FnOnce(ElifRequest) -> NextFuture<'static> + Send>;

        for middleware in self.middleware.iter().rev() {
            let middleware = middleware.clone();
            let next_handler = chain;
            chain = Box::new(move |req: ElifRequest| {
                let next = Next::new(next_handler);
                middleware.handle(req, next)
            });
        }

        chain(request).await
    }

    /// Get number of middleware in pipeline
    pub fn len(&self) -> usize {
        self.middleware.len()
    }

    /// Check if pipeline is empty
    pub fn is_empty(&self) -> bool {
        self.middleware.is_empty()
    }

    /// Get middleware names for debugging
    pub fn names(&self) -> Vec<&'static str> {
        self.middleware.iter().map(|m| m.name()).collect()
    }
}

impl Clone for MiddlewarePipelineV2 {
    fn clone(&self) -> Self {
        Self {
            middleware: self.middleware.clone(),
        }
    }
}

impl From<Vec<Arc<dyn Middleware>>> for MiddlewarePipelineV2 {
    fn from(middleware: Vec<Arc<dyn Middleware>>) -> Self {
        Self { middleware }
    }
}

// Legacy middleware adapter removed - all middleware should use V2 system directly

/// Conditional middleware wrapper that can skip execution based on path patterns and HTTP methods
pub struct ConditionalMiddleware<M> {
    middleware: M,
    skip_paths: Vec<String>,
    only_methods: Option<Vec<ElifMethod>>,
    condition: Option<Arc<dyn Fn(&ElifRequest) -> bool + Send + Sync>>,
}

impl<M: std::fmt::Debug> std::fmt::Debug for ConditionalMiddleware<M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConditionalMiddleware")
            .field("middleware", &self.middleware)
            .field("skip_paths", &self.skip_paths)
            .field("only_methods", &self.only_methods)
            .field("condition", &self.condition.as_ref().map(|_| "Some(Fn)"))
            .finish()
    }
}

impl<M> ConditionalMiddleware<M> {
    pub fn new(middleware: M) -> Self {
        Self {
            middleware,
            skip_paths: Vec::new(),
            only_methods: None,
            condition: None,
        }
    }

    /// Skip middleware execution for paths matching these patterns
    /// Supports basic wildcards: "/api/*" matches "/api/users", "/api/posts", etc.
    pub fn skip_paths(mut self, paths: Vec<&str>) -> Self {
        self.skip_paths = paths.into_iter().map(|s| s.to_string()).collect();
        self
    }

    /// Only execute middleware for these HTTP methods
    pub fn only_methods(mut self, methods: Vec<ElifMethod>) -> Self {
        self.only_methods = Some(methods);
        self
    }

    /// Add a custom condition function that determines whether to run the middleware
    pub fn condition<F>(mut self, condition: F) -> Self
    where
        F: Fn(&ElifRequest) -> bool + Send + Sync + 'static,
    {
        self.condition = Some(Arc::new(condition));
        self
    }

    /// Check if a path matches any of the skip patterns
    fn should_skip_path(&self, path: &str) -> bool {
        for pattern in &self.skip_paths {
            if Self::path_matches(path, pattern) {
                return true;
            }
        }
        false
    }

    /// Simple glob-style path matching (supports single * wildcard)
    fn path_matches(path: &str, pattern: &str) -> bool {
        if let Some((prefix, suffix)) = pattern.split_once('*') {
            path.starts_with(prefix) && path.ends_with(suffix)
        } else {
            path == pattern
        }
    }

    /// Check if the request should be processed by this middleware
    fn should_execute(&self, request: &ElifRequest) -> bool {
        // Check skip paths
        if self.should_skip_path(request.path()) {
            return false;
        }

        // Check method restrictions
        if let Some(ref allowed_methods) = self.only_methods {
            if !allowed_methods.contains(&request.method) {
                return false;
            }
        }

        // Check custom condition
        if let Some(ref condition) = self.condition {
            if !condition(request) {
                return false;
            }
        }

        true
    }
}

impl<M: Middleware> Middleware for ConditionalMiddleware<M> {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        if self.should_execute(&request) {
            // Execute the wrapped middleware
            self.middleware.handle(request, next)
        } else {
            // Skip the middleware and go directly to next
            Box::pin(async move { next.run(request).await })
        }
    }

    fn name(&self) -> &'static str {
        "ConditionalMiddleware"
    }
}

/// Middleware factories for common patterns
pub mod factories {
    use super::*;
    use std::time::Duration;

    /// Rate limiting middleware factory
    pub fn rate_limit(requests_per_minute: u32) -> RateLimitMiddleware {
        RateLimitMiddleware::new()
            .limit(requests_per_minute)
            .window(Duration::from_secs(60))
    }

    /// Rate limiting middleware with custom window
    pub fn rate_limit_with_window(requests: u32, window: Duration) -> RateLimitMiddleware {
        RateLimitMiddleware::new().limit(requests).window(window)
    }

    /// Authentication middleware factory
    pub fn bearer_auth(token: String) -> SimpleAuthMiddleware {
        SimpleAuthMiddleware::new(token)
    }

    /// CORS middleware factory
    pub fn cors() -> CorsMiddleware {
        CorsMiddleware::new()
    }

    /// CORS middleware with specific origins
    pub fn cors_with_origins(origins: Vec<String>) -> CorsMiddleware {
        CorsMiddleware::new().allow_origins(origins)
    }

    /// Timeout middleware factory
    pub fn timeout(duration: Duration) -> TimeoutMiddleware {
        TimeoutMiddleware::new(duration)
    }

    /// Body size limit middleware factory
    pub fn body_limit(max_bytes: u64) -> BodyLimitMiddleware {
        BodyLimitMiddleware::new(max_bytes)
    }

    /// Profiler middleware factory
    pub fn profiler() -> ProfilerMiddleware {
        ProfilerMiddleware::new()
    }

    /// Disabled profiler middleware factory
    pub fn profiler_disabled() -> ProfilerMiddleware {
        ProfilerMiddleware::disabled()
    }
}

/// Middleware composition utilities
pub mod composition {
    use super::*;

    /// Compose two middleware into a pipeline
    pub fn compose<M1, M2>(first: M1, second: M2) -> MiddlewarePipelineV2
    where
        M1: Middleware + 'static,
        M2: Middleware + 'static,
    {
        MiddlewarePipelineV2::new().add(first).add(second)
    }

    /// Chain multiple middleware together (alias for compose for better readability)
    pub fn chain<M1, M2>(first: M1, second: M2) -> MiddlewarePipelineV2
    where
        M1: Middleware + 'static,
        M2: Middleware + 'static,
    {
        compose(first, second)
    }

    /// Create a middleware group from multiple middleware
    pub fn group(middleware: Vec<Arc<dyn Middleware>>) -> MiddlewarePipelineV2 {
        MiddlewarePipelineV2::from(middleware)
    }

    /// Compose three middleware into a pipeline
    pub fn compose3<M1, M2, M3>(first: M1, second: M2, third: M3) -> MiddlewarePipelineV2
    where
        M1: Middleware + 'static,
        M2: Middleware + 'static,
        M3: Middleware + 'static,
    {
        MiddlewarePipelineV2::new()
            .add(first)
            .add(second)
            .add(third)
    }

    /// Compose four middleware into a pipeline
    pub fn compose4<M1, M2, M3, M4>(
        first: M1,
        second: M2,
        third: M3,
        fourth: M4,
    ) -> MiddlewarePipelineV2
    where
        M1: Middleware + 'static,
        M2: Middleware + 'static,
        M3: Middleware + 'static,
        M4: Middleware + 'static,
    {
        MiddlewarePipelineV2::new()
            .add(first)
            .add(second)
            .add(third)
            .add(fourth)
    }
}

/// A composed middleware that executes two middleware in sequence
pub struct ComposedMiddleware<M1, M2> {
    first: M1,
    second: M2,
}

impl<M1: std::fmt::Debug, M2: std::fmt::Debug> std::fmt::Debug for ComposedMiddleware<M1, M2> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ComposedMiddleware")
            .field("first", &self.first)
            .field("second", &self.second)
            .finish()
    }
}

impl<M1, M2> ComposedMiddleware<M1, M2> {
    pub fn new(first: M1, second: M2) -> Self {
        Self { first, second }
    }
}

// For now, let's implement composition via pipeline extension
// The composed middleware pattern is complex with Rust lifetimes in this context
impl<M1, M2> ComposedMiddleware<M1, M2>
where
    M1: Middleware + 'static,
    M2: Middleware + 'static,
{
    /// Convert to a pipeline for easier execution
    pub fn to_pipeline(self) -> MiddlewarePipelineV2 {
        MiddlewarePipelineV2::new().add(self.first).add(self.second)
    }
}

/// Middleware introspection and debugging utilities
pub mod introspection {
    use super::*;
    use std::time::Instant;

    /// Execution statistics for middleware
    #[derive(Debug, Clone)]
    pub struct MiddlewareStats {
        pub name: String,
        pub executions: u64,
        pub total_time: Duration,
        pub avg_time: Duration,
        pub last_execution: Option<Instant>,
    }

    impl MiddlewareStats {
        pub fn new(name: String) -> Self {
            Self {
                name,
                executions: 0,
                total_time: Duration::ZERO,
                avg_time: Duration::ZERO,
                last_execution: None,
            }
        }

        pub fn record_execution(&mut self, duration: Duration) {
            self.executions += 1;
            self.total_time += duration;
            // Safe division using u128 to avoid overflow and division-by-zero
            self.avg_time =
                Duration::from_nanos((self.total_time.as_nanos() / self.executions as u128) as u64);
            self.last_execution = Some(Instant::now());
        }
    }

    /// Debug information about a middleware pipeline
    #[derive(Debug, Clone)]
    pub struct PipelineInfo {
        pub middleware_count: usize,
        pub middleware_names: Vec<String>,
        pub execution_order: Vec<String>,
    }

    impl MiddlewarePipelineV2 {
        /// Get debug information about the pipeline
        pub fn debug_info(&self) -> PipelineInfo {
            PipelineInfo {
                middleware_count: self.len(),
                middleware_names: self.names().into_iter().map(|s| s.to_string()).collect(),
                execution_order: self.names().into_iter().map(|s| s.to_string()).collect(),
            }
        }

        /// Create a debug pipeline that wraps each middleware with timing
        pub fn with_debug(self) -> DebugPipeline {
            DebugPipeline::new(self)
        }
    }

    /// A wrapper around MiddlewarePipelineV2 that provides debugging capabilities
    #[derive(Debug)]
    pub struct DebugPipeline {
        pipeline: MiddlewarePipelineV2,
        stats: Arc<Mutex<HashMap<String, MiddlewareStats>>>,
    }

    impl DebugPipeline {
        pub fn new(pipeline: MiddlewarePipelineV2) -> Self {
            let mut stats = HashMap::new();
            for name in pipeline.names() {
                stats.insert(name.to_string(), MiddlewareStats::new(name.to_string()));
            }

            Self {
                pipeline,
                stats: Arc::new(Mutex::new(stats)),
            }
        }

        /// Get execution statistics for all middleware
        pub fn stats(&self) -> HashMap<String, MiddlewareStats> {
            self.stats
                .lock()
                .expect("Stats mutex should not be poisoned")
                .clone()
        }

        /// Get statistics for a specific middleware
        pub fn middleware_stats(&self, name: &str) -> Option<MiddlewareStats> {
            self.stats
                .lock()
                .expect("Stats mutex should not be poisoned")
                .get(name)
                .cloned()
        }

        /// Reset all statistics
        pub fn reset_stats(&self) {
            let mut stats = self
                .stats
                .lock()
                .expect("Stats mutex should not be poisoned");
            for (name, stat) in stats.iter_mut() {
                *stat = MiddlewareStats::new(name.clone());
            }
        }

        /// Execute the pipeline with debug tracking
        pub async fn execute_debug<F, Fut>(
            &self,
            request: ElifRequest,
            handler: F,
        ) -> (ElifResponse, Duration)
        where
            F: FnOnce(ElifRequest) -> Fut + Send + 'static,
            Fut: Future<Output = ElifResponse> + Send + 'static,
        {
            let start_time = Instant::now();
            let response = self.pipeline.execute(request, handler).await;
            let total_duration = start_time.elapsed();

            (response, total_duration)
        }
    }

    /// A middleware wrapper that tracks execution statistics
    #[derive(Debug)]
    pub struct InstrumentedMiddleware<M> {
        middleware: M,
        name: String,
        stats: Arc<Mutex<MiddlewareStats>>,
    }

    impl<M> InstrumentedMiddleware<M> {
        pub fn new(middleware: M, name: String) -> Self {
            let stats = Arc::new(Mutex::new(MiddlewareStats::new(name.clone())));
            Self {
                middleware,
                name,
                stats,
            }
        }

        /// Get the current statistics for this middleware
        pub fn stats(&self) -> MiddlewareStats {
            self.stats
                .lock()
                .expect("Middleware stats mutex should not be poisoned")
                .clone()
        }

        /// Reset statistics for this middleware
        pub fn reset_stats(&self) {
            let mut stats = self
                .stats
                .lock()
                .expect("Middleware stats mutex should not be poisoned");
            *stats = MiddlewareStats::new(self.name.clone());
        }
    }

    impl<M: Middleware> Middleware for InstrumentedMiddleware<M> {
        fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
            let stats = self.stats.clone();
            let middleware_result = self.middleware.handle(request, next);

            Box::pin(async move {
                let start = Instant::now();
                let response = middleware_result.await;
                let duration = start.elapsed();

                stats
                    .lock()
                    .expect("Middleware stats mutex should not be poisoned")
                    .record_execution(duration);
                response
            })
        }

        fn name(&self) -> &'static str {
            "InstrumentedMiddleware"
        }
    }

    /// Utility function to wrap middleware with instrumentation
    pub fn instrument<M: Middleware + 'static>(
        middleware: M,
        name: String,
    ) -> InstrumentedMiddleware<M> {
        InstrumentedMiddleware::new(middleware, name)
    }
}

/// Rate limiting middleware
pub struct RateLimitMiddleware {
    requests_per_window: u32,
    window: Duration,
    // Simple in-memory store - in production you'd use Redis or similar
    requests: Arc<Mutex<HashMap<String, (std::time::Instant, u32)>>>,
    // Last cleanup time to avoid O(N) cleanup on every request
    last_cleanup: Arc<Mutex<std::time::Instant>>,
}

impl std::fmt::Debug for RateLimitMiddleware {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RateLimitMiddleware")
            .field("requests_per_window", &self.requests_per_window)
            .field("window", &self.window)
            .field("last_cleanup", &"<Mutex<Instant>>")
            .finish()
    }
}

impl Default for RateLimitMiddleware {
    fn default() -> Self {
        Self::new()
    }
}

impl RateLimitMiddleware {
    pub fn new() -> Self {
        let now = std::time::Instant::now();
        Self {
            requests_per_window: 60, // Default: 60 requests per minute
            window: Duration::from_secs(60),
            requests: Arc::new(Mutex::new(HashMap::new())),
            last_cleanup: Arc::new(Mutex::new(now)),
        }
    }

    pub fn limit(mut self, requests: u32) -> Self {
        self.requests_per_window = requests;
        self
    }

    pub fn window(mut self, window: Duration) -> Self {
        self.window = window;
        self
    }

    fn get_client_id(&self, request: &ElifRequest) -> String {
        // Simple IP-based rate limiting - in production you might use user ID, API key, etc.
        request
            .header("x-forwarded-for")
            .and_then(|h| h.to_str().ok())
            .unwrap_or("unknown")
            .to_string()
    }

    fn is_rate_limited(&self, client_id: &str) -> bool {
        let now = std::time::Instant::now();

        // Periodic cleanup to avoid O(N) operation on every request
        // Only clean up every 30 seconds to balance memory usage vs performance
        const CLEANUP_INTERVAL: Duration = Duration::from_secs(30);

        {
            let mut last_cleanup = self
                .last_cleanup
                .lock()
                .expect("Cleanup time mutex should not be poisoned");
            if now.duration_since(*last_cleanup) > CLEANUP_INTERVAL {
                // Time for cleanup - acquire requests lock and clean
                let mut requests = self
                    .requests
                    .lock()
                    .expect("Rate limiter mutex should not be poisoned");
                requests.retain(|_, (timestamp, _)| now.duration_since(*timestamp) < self.window);
                *last_cleanup = now;
                // Release both locks before continuing
                drop(requests);
            }
        }

        // Now handle the actual rate limiting logic
        let mut requests = self
            .requests
            .lock()
            .expect("Rate limiter mutex should not be poisoned");

        // Check current rate
        if let Some((timestamp, count)) = requests.get_mut(client_id) {
            if now.duration_since(*timestamp) < self.window {
                if *count >= self.requests_per_window {
                    return true; // Rate limited
                }
                *count += 1;
            } else {
                // Reset window
                *timestamp = now;
                *count = 1;
            }
        } else {
            // First request from this client
            requests.insert(client_id.to_string(), (now, 1));
        }

        false
    }
}

impl Middleware for RateLimitMiddleware {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        let client_id = self.get_client_id(&request);
        let is_limited = self.is_rate_limited(&client_id);

        Box::pin(async move {
            if is_limited {
                ElifResponse::with_status(
                    crate::response::status::ElifStatusCode::TOO_MANY_REQUESTS,
                )
                .json_value(serde_json::json!({
                    "error": {
                        "code": "rate_limited",
                        "message": "Too many requests. Please try again later."
                    }
                }))
            } else {
                next.run(request).await
            }
        })
    }

    fn name(&self) -> &'static str {
        "RateLimitMiddleware"
    }
}

/// CORS middleware
#[derive(Debug)]
pub struct CorsMiddleware {
    allowed_origins: Vec<String>,
    allowed_methods: Vec<String>,
    allowed_headers: Vec<String>,
}

impl Default for CorsMiddleware {
    fn default() -> Self {
        Self::new()
    }
}

impl CorsMiddleware {
    pub fn new() -> Self {
        Self {
            allowed_origins: vec!["*".to_string()],
            allowed_methods: vec![
                "GET".to_string(),
                "POST".to_string(),
                "PUT".to_string(),
                "DELETE".to_string(),
                "OPTIONS".to_string(),
            ],
            allowed_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
        }
    }

    pub fn allow_origins(mut self, origins: Vec<String>) -> Self {
        self.allowed_origins = origins;
        self
    }

    pub fn allow_methods(mut self, methods: Vec<String>) -> Self {
        self.allowed_methods = methods;
        self
    }

    pub fn allow_headers(mut self, headers: Vec<String>) -> Self {
        self.allowed_headers = headers;
        self
    }
}

impl Middleware for CorsMiddleware {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        let allowed_origins = self.allowed_origins.clone();
        let allowed_methods = self.allowed_methods.clone();
        let allowed_headers = self.allowed_headers.clone();

        Box::pin(async move {
            // Handle preflight OPTIONS request
            if request.method == ElifMethod::OPTIONS {
                let mut preflight_response = ElifResponse::ok();
                // Add headers safely - ignore failures to avoid replacing response
                let _ = preflight_response
                    .add_header("Access-Control-Allow-Origin", allowed_origins.join(","));
                let _ = preflight_response
                    .add_header("Access-Control-Allow-Methods", allowed_methods.join(","));
                let _ = preflight_response
                    .add_header("Access-Control-Allow-Headers", allowed_headers.join(","));
                return preflight_response;
            }

            let mut response = next.run(request).await;

            // Add CORS headers to response safely - never replace the response on failure
            let _ = response.add_header("Access-Control-Allow-Origin", allowed_origins.join(","));
            let _ = response.add_header("Access-Control-Allow-Methods", allowed_methods.join(","));
            let _ = response.add_header("Access-Control-Allow-Headers", allowed_headers.join(","));

            response
        })
    }

    fn name(&self) -> &'static str {
        "CorsMiddleware"
    }
}

/// Timeout middleware
#[derive(Debug)]
pub struct TimeoutMiddleware {
    timeout: Duration,
}

impl TimeoutMiddleware {
    pub fn new(timeout: Duration) -> Self {
        Self { timeout }
    }
}

impl Middleware for TimeoutMiddleware {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        let timeout = self.timeout;
        Box::pin(async move {
            match tokio::time::timeout(timeout, next.run(request)).await {
                Ok(response) => response,
                Err(_) => ElifResponse::with_status(
                    crate::response::status::ElifStatusCode::REQUEST_TIMEOUT,
                )
                .json_value(serde_json::json!({
                    "error": {
                        "code": "timeout",
                        "message": "Request timed out"
                    }
                })),
            }
        })
    }

    fn name(&self) -> &'static str {
        "TimeoutMiddleware"
    }
}

/// Body size limit middleware
#[derive(Debug)]
pub struct BodyLimitMiddleware {
    max_bytes: u64,
}

impl BodyLimitMiddleware {
    pub fn new(max_bytes: u64) -> Self {
        Self { max_bytes }
    }
}

impl Middleware for BodyLimitMiddleware {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        let max_bytes = self.max_bytes;
        Box::pin(async move {
            // Check if request has body and if it exceeds limit
            if let Some(body) = request.body_bytes() {
                if body.len() as u64 > max_bytes {
                    return ElifResponse::with_status(crate::response::status::ElifStatusCode::PAYLOAD_TOO_LARGE)
                        .json_value(serde_json::json!({
                            "error": {
                                "code": "payload_too_large",
                                "message": format!("Request body too large. Maximum allowed: {} bytes", max_bytes)
                            }
                        }));
                }
            }

            next.run(request).await
        })
    }

    fn name(&self) -> &'static str {
        "BodyLimitMiddleware"
    }
}

/// Example logging middleware using the new pattern
#[derive(Debug)]
pub struct LoggingMiddleware;

impl Middleware for LoggingMiddleware {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        Box::pin(async move {
            // Before request
            let start = std::time::Instant::now();
            let method = request.method.clone();
            let path = request.path().to_string();

            // Pass to next middleware
            let response = next.run(request).await;

            // After response
            let duration = start.elapsed();
            println!(
                "{} {} - {} - {:?}",
                method,
                path,
                response.status_code(),
                duration
            );

            response
        })
    }

    fn name(&self) -> &'static str {
        "LoggingMiddleware"
    }
}

/// Middleware profiler that logs timing for each middleware in the pipeline
#[derive(Debug)]
pub struct ProfilerMiddleware {
    enabled: bool,
}

impl Default for ProfilerMiddleware {
    fn default() -> Self {
        Self::new()
    }
}

impl ProfilerMiddleware {
    pub fn new() -> Self {
        Self { enabled: true }
    }

    pub fn disabled() -> Self {
        Self { enabled: false }
    }
}

impl Middleware for ProfilerMiddleware {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        let enabled = self.enabled;
        Box::pin(async move {
            if !enabled {
                return next.run(request).await;
            }

            let start = std::time::Instant::now();
            let method = request.method.clone();
            let path = request.path().to_string();

            println!("⏱️  [PROFILER] Starting request {} {}", method, path);

            let response = next.run(request).await;

            let duration = start.elapsed();
            println!(
                "⏱️  [PROFILER] Completed {} {} in {:?} - Status: {}",
                method,
                path,
                duration,
                response.status_code()
            );

            response
        })
    }

    fn name(&self) -> &'static str {
        "ProfilerMiddleware"
    }
}

/// Example auth middleware using the new pattern
#[derive(Debug)]
pub struct SimpleAuthMiddleware {
    required_token: String,
}

impl SimpleAuthMiddleware {
    pub fn new(token: String) -> Self {
        Self {
            required_token: token,
        }
    }
}

impl Middleware for SimpleAuthMiddleware {
    fn handle(&self, request: ElifRequest, next: Next) -> NextFuture<'static> {
        let required_token = self.required_token.clone();
        Box::pin(async move {
            // Extract token
            let token = match request.header("Authorization") {
                Some(h) => match h.to_str() {
                    Ok(header_str) if header_str.starts_with("Bearer ") => &header_str[7..],
                    _ => {
                        return ElifResponse::unauthorized().json_value(serde_json::json!({
                            "error": {
                                "code": "unauthorized",
                                "message": "Missing or invalid authorization header"
                            }
                        }));
                    }
                },
                None => {
                    return ElifResponse::unauthorized().json_value(serde_json::json!({
                        "error": {
                            "code": "unauthorized",
                            "message": "Missing authorization header"
                        }
                    }));
                }
            };

            // Validate token
            if token != required_token {
                return ElifResponse::unauthorized().json_value(serde_json::json!({
                    "error": {
                        "code": "unauthorized",
                        "message": "Invalid token"
                    }
                }));
            }

            // Token is valid, proceed to next middleware
            next.run(request).await
        })
    }

    fn name(&self) -> &'static str {
        "SimpleAuthMiddleware"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::request::ElifRequest;
    use crate::response::ElifResponse;

    /// Test middleware that adds a header to requests
    #[derive(Debug)]
    pub struct TestMiddleware {
        name: &'static str,
    }

    impl TestMiddleware {
        pub fn new(name: &'static str) -> Self {
            Self { name }
        }
    }

    impl Middleware for TestMiddleware {
        fn handle(&self, mut request: ElifRequest, next: Next) -> NextFuture<'static> {
            let name = self.name;
            Box::pin(async move {
                // Add a custom header to track middleware execution
                let header_name = crate::response::headers::ElifHeaderName::from_str(&format!(
                    "x-middleware-{}",
                    name.to_lowercase()
                ))
                .unwrap();
                let header_value =
                    crate::response::headers::ElifHeaderValue::from_str("executed").unwrap();
                request.headers.insert(header_name, header_value);

                let response = next.run(request).await;

                // Add response header - simplified for now
                response
            })
        }

        fn name(&self) -> &'static str {
            self.name
        }
    }

    #[tokio::test]
    async fn test_simple_middleware_execution() {
        let pipeline = MiddlewarePipelineV2::new()
            .add(TestMiddleware::new("First"))
            .add(TestMiddleware::new("Second"));

        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/test".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response = pipeline
            .execute(request, |req| {
                Box::pin(async move {
                    // Verify both middleware executed by checking headers they added
                    assert!(
                        req.headers.contains_key(
                            &crate::response::headers::ElifHeaderName::from_str(
                                "x-middleware-first"
                            )
                            .unwrap()
                        ),
                        "First middleware should have added header"
                    );
                    assert!(
                        req.headers.contains_key(
                            &crate::response::headers::ElifHeaderName::from_str(
                                "x-middleware-second"
                            )
                            .unwrap()
                        ),
                        "Second middleware should have added header"
                    );

                    ElifResponse::ok().text("Hello World")
                })
            })
            .await;

        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
    }

    #[tokio::test]
    async fn test_middleware_chain_execution_order() {
        /// Test middleware that tracks execution order
        #[derive(Debug)]
        struct OrderTestMiddleware {
            name: &'static str,
        }

        impl OrderTestMiddleware {
            fn new(name: &'static str) -> Self {
                Self { name }
            }
        }

        impl Middleware for OrderTestMiddleware {
            fn handle(&self, mut request: ElifRequest, next: Next) -> NextFuture<'static> {
                let name = self.name;
                Box::pin(async move {
                    // Add execution order to request headers (before handler)
                    let header_name_str = format!("x-before-{}", name.to_lowercase());
                    let header_name =
                        crate::response::headers::ElifHeaderName::from_str(&header_name_str)
                            .unwrap();
                    let header_value =
                        crate::response::headers::ElifHeaderValue::from_str("executed").unwrap();
                    request.headers.insert(header_name, header_value);

                    // Call next middleware/handler
                    let response = next.run(request).await;

                    // Add execution order to response headers (after handler)
                    let response_header = format!("x-after-{}", name.to_lowercase());
                    response.header(&response_header, "executed").unwrap_or(
                        // If header addition fails, return original response
                        ElifResponse::ok().text("fallback"),
                    )
                })
            }

            fn name(&self) -> &'static str {
                self.name
            }
        }

        // Create pipeline with multiple middleware
        let pipeline = MiddlewarePipelineV2::new()
            .add(OrderTestMiddleware::new("First"))
            .add(OrderTestMiddleware::new("Second"))
            .add(OrderTestMiddleware::new("Third"));

        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/test".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response = pipeline
            .execute(request, |req| {
                Box::pin(async move {
                    // Verify all middleware ran before the handler
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-before-first")
                            .unwrap()
                    ));
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-before-second")
                            .unwrap()
                    ));
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-before-third")
                            .unwrap()
                    ));

                    ElifResponse::ok().text("Handler executed")
                })
            })
            .await;

        // Verify response and that all middleware ran after the handler
        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Convert to axum response to check headers
        let axum_response = response.into_axum_response();
        let (parts, _body) = axum_response.into_parts();
        assert!(parts.headers.contains_key("x-after-first"));
        assert!(parts.headers.contains_key("x-after-second"));
        assert!(parts.headers.contains_key("x-after-third"));

        // Verify pipeline info
        assert_eq!(pipeline.len(), 3);
        assert_eq!(pipeline.names(), vec!["First", "Second", "Third"]);
    }

    #[tokio::test]
    async fn test_auth_middleware() {
        let auth_middleware = SimpleAuthMiddleware::new("secret123".to_string());

        // Test with valid token
        let mut headers = crate::response::headers::ElifHeaderMap::new();
        headers.insert(
            crate::response::headers::ElifHeaderName::from_str("authorization").unwrap(),
            "Bearer secret123".parse().unwrap(),
        );
        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/protected".parse().unwrap(),
            headers,
        );

        let next =
            Next::new(|_req| Box::pin(async { ElifResponse::ok().text("Protected content") }));

        let response = auth_middleware.handle(request, next).await;
        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Test with invalid token
        let mut headers = crate::response::headers::ElifHeaderMap::new();
        headers.insert(
            crate::response::headers::ElifHeaderName::from_str("authorization").unwrap(),
            "Bearer invalid".parse().unwrap(),
        );
        let request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/protected".parse().unwrap(),
            headers,
        );

        let next =
            Next::new(|_req| Box::pin(async { ElifResponse::ok().text("Protected content") }));

        let response = auth_middleware.handle(request, next).await;
        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::UNAUTHORIZED
        );
    }

    #[tokio::test]
    async fn test_pipeline_info() {
        let pipeline = MiddlewarePipelineV2::new()
            .add(TestMiddleware::new("Test1"))
            .add(TestMiddleware::new("Test2"));

        assert_eq!(pipeline.len(), 2);
        assert!(!pipeline.is_empty());
        assert_eq!(pipeline.names(), vec!["Test1", "Test2"]);

        let empty_pipeline = MiddlewarePipelineV2::new();
        assert_eq!(empty_pipeline.len(), 0);
        assert!(empty_pipeline.is_empty());
    }

    // Legacy compatibility test removed - all middleware use V2 system directly

    #[tokio::test]
    async fn test_conditional_middleware_skip_paths() {
        let base_middleware = TestMiddleware::new("Conditional");
        let conditional =
            ConditionalMiddleware::new(base_middleware).skip_paths(vec!["/public/*", "/health"]);

        let pipeline = MiddlewarePipelineV2::new().add(conditional);

        // Test skipped path
        let request1 = ElifRequest::new(
            ElifMethod::GET,
            "/public/assets/style.css".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response1 = pipeline
            .execute(request1, |req| {
                Box::pin(async move {
                    // Middleware should be skipped - no header added
                    assert!(!req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str(
                            "x-middleware-conditional"
                        )
                        .unwrap()
                    ));
                    ElifResponse::ok().text("OK")
                })
            })
            .await;

        assert_eq!(
            response1.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Test non-skipped path
        let request2 = ElifRequest::new(
            ElifMethod::GET,
            "/api/users".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response2 = pipeline
            .execute(request2, |req| {
                Box::pin(async move {
                    // Middleware should execute - header added
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str(
                            "x-middleware-conditional"
                        )
                        .unwrap()
                    ));
                    ElifResponse::ok().text("OK")
                })
            })
            .await;

        assert_eq!(
            response2.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
    }

    #[tokio::test]
    async fn test_conditional_middleware_only_methods() {
        let base_middleware = TestMiddleware::new("MethodConditional");
        let conditional = ConditionalMiddleware::new(base_middleware)
            .only_methods(vec![ElifMethod::POST, ElifMethod::PUT]);

        let pipeline = MiddlewarePipelineV2::new().add(conditional);

        // Test allowed method
        let request1 = ElifRequest::new(
            ElifMethod::POST,
            "/api/users".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response1 = pipeline
            .execute(request1, |req| {
                Box::pin(async move {
                    // Middleware should execute for POST
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str(
                            "x-middleware-methodconditional"
                        )
                        .unwrap()
                    ));
                    ElifResponse::ok().text("OK")
                })
            })
            .await;

        assert_eq!(
            response1.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Test disallowed method
        let request2 = ElifRequest::new(
            ElifMethod::GET,
            "/api/users".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response2 = pipeline
            .execute(request2, |req| {
                Box::pin(async move {
                    // Middleware should be skipped for GET
                    assert!(!req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str(
                            "x-middleware-methodconditional"
                        )
                        .unwrap()
                    ));
                    ElifResponse::ok().text("OK")
                })
            })
            .await;

        assert_eq!(
            response2.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
    }

    #[tokio::test]
    async fn test_conditional_middleware_custom_condition() {
        let base_middleware = TestMiddleware::new("CustomConditional");
        let conditional = ConditionalMiddleware::new(base_middleware)
            .condition(|req| req.header("X-Debug").is_some());

        let pipeline = MiddlewarePipelineV2::new().add(conditional);

        // Test with condition met
        let mut headers1 = crate::response::headers::ElifHeaderMap::new();
        headers1.insert(
            crate::response::headers::ElifHeaderName::from_str("x-debug").unwrap(),
            "true".parse().unwrap(),
        );
        let request1 = ElifRequest::new(ElifMethod::GET, "/api/test".parse().unwrap(), headers1);

        let response1 = pipeline
            .execute(request1, |req| {
                Box::pin(async move {
                    // Middleware should execute when X-Debug header present
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str(
                            "x-middleware-customconditional"
                        )
                        .unwrap()
                    ));
                    ElifResponse::ok().text("OK")
                })
            })
            .await;

        assert_eq!(
            response1.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Test without condition met
        let request2 = ElifRequest::new(
            ElifMethod::GET,
            "/api/test".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response2 = pipeline
            .execute(request2, |req| {
                Box::pin(async move {
                    // Middleware should be skipped when X-Debug header not present
                    assert!(!req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str(
                            "x-middleware-customconditional"
                        )
                        .unwrap()
                    ));
                    ElifResponse::ok().text("OK")
                })
            })
            .await;

        assert_eq!(
            response2.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
    }

    #[tokio::test]
    async fn test_rate_limit_factory() {
        use super::factories;

        let rate_limiter = factories::rate_limit(2); // 2 requests per minute
        let pipeline = MiddlewarePipelineV2::new().add(rate_limiter);

        // First request should pass
        let request1 = ElifRequest::new(
            ElifMethod::GET,
            "/api/test".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response1 = pipeline
            .execute(request1, |_req| {
                Box::pin(async move { ElifResponse::ok().text("OK") })
            })
            .await;

        assert_eq!(
            response1.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Second request should also pass
        let request2 = ElifRequest::new(
            ElifMethod::GET,
            "/api/test".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response2 = pipeline
            .execute(request2, |_req| {
                Box::pin(async move { ElifResponse::ok().text("OK") })
            })
            .await;

        assert_eq!(
            response2.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Third request should be rate limited
        let request3 = ElifRequest::new(
            ElifMethod::GET,
            "/api/test".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response3 = pipeline
            .execute(request3, |_req| {
                Box::pin(async move { ElifResponse::ok().text("OK") })
            })
            .await;

        assert_eq!(
            response3.status_code(),
            crate::response::status::ElifStatusCode::TOO_MANY_REQUESTS
        );
    }

    #[tokio::test]
    async fn test_cors_factory() {
        use super::factories;

        let cors = factories::cors_with_origins(vec!["https://example.com".to_string()]);
        let pipeline = MiddlewarePipelineV2::new().add(cors);

        // Test OPTIONS preflight request
        let request1 = ElifRequest::new(
            ElifMethod::OPTIONS,
            "/api/test".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response1 = pipeline
            .execute(request1, |_req| {
                Box::pin(async move { ElifResponse::ok().text("Should not reach here") })
            })
            .await;

        assert_eq!(
            response1.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Test normal request with CORS headers added
        let request2 = ElifRequest::new(
            ElifMethod::GET,
            "/api/test".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response2 = pipeline
            .execute(request2, |_req| {
                Box::pin(async move { ElifResponse::ok().text("OK") })
            })
            .await;

        assert_eq!(
            response2.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
    }

    #[tokio::test]
    async fn test_timeout_factory() {
        use super::factories;
        use std::time::Duration;

        let timeout_middleware = factories::timeout(Duration::from_millis(100));
        let pipeline = MiddlewarePipelineV2::new().add(timeout_middleware);

        // Test request that completes within timeout
        let request1 = ElifRequest::new(
            ElifMethod::GET,
            "/api/fast".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response1 = pipeline
            .execute(request1, |_req| {
                Box::pin(async move {
                    tokio::time::sleep(Duration::from_millis(10)).await;
                    ElifResponse::ok().text("Fast response")
                })
            })
            .await;

        assert_eq!(
            response1.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Test request that times out
        let request2 = ElifRequest::new(
            ElifMethod::GET,
            "/api/slow".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response2 = pipeline
            .execute(request2, |_req| {
                Box::pin(async move {
                    tokio::time::sleep(Duration::from_millis(200)).await;
                    ElifResponse::ok().text("Slow response")
                })
            })
            .await;

        assert_eq!(
            response2.status_code(),
            crate::response::status::ElifStatusCode::REQUEST_TIMEOUT
        );
    }

    #[tokio::test]
    async fn test_body_limit_factory() {
        use super::factories;
        use axum::body::Bytes;

        let body_limit = factories::body_limit(10); // 10 bytes max
        let pipeline = MiddlewarePipelineV2::new().add(body_limit);

        // Test request with small body
        let small_body = Bytes::from("small");
        let request1 = ElifRequest::new(
            ElifMethod::POST,
            "/api/upload".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        )
        .with_body(small_body);

        let response1 = pipeline
            .execute(request1, |_req| {
                Box::pin(async move { ElifResponse::ok().text("Upload successful") })
            })
            .await;

        assert_eq!(
            response1.status_code(),
            crate::response::status::ElifStatusCode::OK
        );

        // Test request with large body
        let large_body = Bytes::from("this body is way too large for the limit");
        let request2 = ElifRequest::new(
            ElifMethod::POST,
            "/api/upload".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        )
        .with_body(large_body);

        let response2 = pipeline
            .execute(request2, |_req| {
                Box::pin(async move { ElifResponse::ok().text("Should not reach here") })
            })
            .await;

        assert_eq!(
            response2.status_code(),
            crate::response::status::ElifStatusCode::PAYLOAD_TOO_LARGE
        );
    }

    #[tokio::test]
    async fn test_composition_utilities() {
        use super::composition;

        let middleware1 = TestMiddleware::new("First");
        let middleware2 = TestMiddleware::new("Second");

        // Test compose function
        let composed_pipeline = composition::compose(middleware1, middleware2);

        let request = ElifRequest::new(
            ElifMethod::GET,
            "/api/test".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response = composed_pipeline
            .execute(request, |req| {
                Box::pin(async move {
                    // Both middleware should have executed
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-middleware-first")
                            .unwrap()
                    ));
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-middleware-second")
                            .unwrap()
                    ));
                    ElifResponse::ok().text("Composed response")
                })
            })
            .await;

        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
        assert_eq!(composed_pipeline.len(), 2);

        // Test compose3 function
        let middleware1 = TestMiddleware::new("Alpha");
        let middleware2 = TestMiddleware::new("Beta");
        let middleware3 = TestMiddleware::new("Gamma");

        let composed3_pipeline = composition::compose3(middleware1, middleware2, middleware3);

        let request2 = ElifRequest::new(
            ElifMethod::POST,
            "/api/composed".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response2 = composed3_pipeline
            .execute(request2, |req| {
                Box::pin(async move {
                    // All three middleware should have executed
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-middleware-alpha")
                            .unwrap()
                    ));
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-middleware-beta")
                            .unwrap()
                    ));
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-middleware-gamma")
                            .unwrap()
                    ));
                    ElifResponse::ok().text("Triple composed response")
                })
            })
            .await;

        assert_eq!(
            response2.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
        assert_eq!(composed3_pipeline.len(), 3);
    }

    #[tokio::test]
    async fn test_composition_group() {
        use super::composition;

        let middleware_vec: Vec<Arc<dyn Middleware>> = vec![
            Arc::new(TestMiddleware::new("Group1")),
            Arc::new(TestMiddleware::new("Group2")),
            Arc::new(TestMiddleware::new("Group3")),
        ];

        let group_pipeline = composition::group(middleware_vec);

        let request = ElifRequest::new(
            ElifMethod::DELETE,
            "/api/group".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response = group_pipeline
            .execute(request, |req| {
                Box::pin(async move {
                    // All group middleware should have executed
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-middleware-group1")
                            .unwrap()
                    ));
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-middleware-group2")
                            .unwrap()
                    ));
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-middleware-group3")
                            .unwrap()
                    ));
                    ElifResponse::ok().text("Group response")
                })
            })
            .await;

        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
        assert_eq!(group_pipeline.len(), 3);
        assert_eq!(group_pipeline.names(), vec!["Group1", "Group2", "Group3"]);
    }

    #[tokio::test]
    async fn test_composed_middleware_to_pipeline() {
        let middleware1 = TestMiddleware::new("ComposedA");
        let middleware2 = TestMiddleware::new("ComposedB");

        let composed = ComposedMiddleware::new(middleware1, middleware2);
        let pipeline = composed.to_pipeline();

        let request = ElifRequest::new(
            ElifMethod::PUT,
            "/api/composed".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response = pipeline
            .execute(request, |req| {
                Box::pin(async move {
                    // Both composed middleware should have executed
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str(
                            "x-middleware-composeda"
                        )
                        .unwrap()
                    ));
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str(
                            "x-middleware-composedb"
                        )
                        .unwrap()
                    ));
                    ElifResponse::ok().text("Composed pipeline response")
                })
            })
            .await;

        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
        assert_eq!(pipeline.len(), 2);
    }

    #[tokio::test]
    async fn test_introspection_debug_info() {
        let pipeline = MiddlewarePipelineV2::new()
            .add(TestMiddleware::new("Debug1"))
            .add(TestMiddleware::new("Debug2"))
            .add(TestMiddleware::new("Debug3"));

        let debug_info = pipeline.debug_info();

        assert_eq!(debug_info.middleware_count, 3);
        assert_eq!(
            debug_info.middleware_names,
            vec!["Debug1", "Debug2", "Debug3"]
        );
        assert_eq!(
            debug_info.execution_order,
            vec!["Debug1", "Debug2", "Debug3"]
        );
    }

    #[tokio::test]
    async fn test_introspection_debug_pipeline() {
        let pipeline = MiddlewarePipelineV2::new()
            .add(TestMiddleware::new("Timed1"))
            .add(TestMiddleware::new("Timed2"));

        let debug_pipeline = pipeline.with_debug();

        let request = ElifRequest::new(
            ElifMethod::GET,
            "/api/debug".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let (response, duration) = debug_pipeline
            .execute_debug(request, |_req| {
                Box::pin(async move {
                    // Simulate some processing time
                    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                    ElifResponse::ok().text("Debug response")
                })
            })
            .await;

        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
        assert!(duration > std::time::Duration::from_millis(5));

        // Check that we can get stats (even if middleware aren't individually tracked yet)
        let stats = debug_pipeline.stats();
        assert_eq!(stats.len(), 2);
        assert!(stats.contains_key("Timed1"));
        assert!(stats.contains_key("Timed2"));
    }

    #[tokio::test]
    async fn test_introspection_instrumented_middleware() {
        let base_middleware = TestMiddleware::new("Base");
        let instrumented =
            introspection::instrument(base_middleware, "InstrumentedTest".to_string());

        let pipeline = MiddlewarePipelineV2::new().add(instrumented);

        let request = ElifRequest::new(
            ElifMethod::POST,
            "/api/instrumented".parse().unwrap(),
            crate::response::headers::ElifHeaderMap::new(),
        );

        let response = pipeline
            .execute(request, |req| {
                Box::pin(async move {
                    // Verify middleware executed
                    assert!(req.headers.contains_key(
                        &crate::response::headers::ElifHeaderName::from_str("x-middleware-base")
                            .unwrap()
                    ));
                    ElifResponse::ok().text("Instrumented response")
                })
            })
            .await;

        assert_eq!(
            response.status_code(),
            crate::response::status::ElifStatusCode::OK
        );
    }

    #[tokio::test]
    async fn test_introspection_middleware_stats() {
        use super::introspection::{instrument, MiddlewareStats};

        let mut stats = MiddlewareStats::new("TestStats".to_string());

        // Record some executions
        stats.record_execution(std::time::Duration::from_millis(10));
        stats.record_execution(std::time::Duration::from_millis(20));
        stats.record_execution(std::time::Duration::from_millis(30));

        assert_eq!(stats.executions, 3);
        assert_eq!(stats.total_time, std::time::Duration::from_millis(60));
        assert_eq!(stats.avg_time, std::time::Duration::from_millis(20));
        assert!(stats.last_execution.is_some());

        // Test instrumented middleware stats
        let base_middleware = TestMiddleware::new("StatsTest");
        let instrumented = instrument(base_middleware, "StatsInstrumented".to_string());

        let initial_stats = instrumented.stats();
        assert_eq!(initial_stats.executions, 0);
        assert_eq!(initial_stats.total_time, std::time::Duration::ZERO);

        // Test reset functionality
        instrumented.reset_stats();
        let reset_stats = instrumented.stats();
        assert_eq!(reset_stats.executions, 0);
    }
}