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
//! Request/Response pipeline that integrates routing and middleware
//!
//! This module provides the unified request processing pipeline that:
//! - Integrates the new framework-native routing engine
//! - Handles parameter injection from route matches
//! - Executes middleware pipelines with route-specific configurations  
//! - Provides clean error handling throughout the pipeline
//! - Supports route-specific middleware execution

use crate::middleware::v2::{MiddlewarePipelineV2, NextFuture};
use crate::request::ElifRequest;
use crate::response::{ElifResponse, ElifStatusCode};
use crate::routing::{HttpMethod, RouteMatch, RouteMatcher};
use std::collections::HashMap;
use std::sync::Arc;
use thiserror::Error;

/// Errors that can occur during request pipeline processing
#[derive(Error, Debug)]
pub enum PipelineError {
    #[error("Route not found: {method} {path}")]
    RouteNotFound { method: HttpMethod, path: String },

    #[error("Method not allowed: {method}")]
    MethodNotAllowed { method: String },

    #[error("Parameter error: {0}")]
    Parameter(#[from] ParamError),

    #[error("Middleware error: {0}")]
    Middleware(String),

    #[error("Handler error: {0}")]
    Handler(String),

    #[error("Internal pipeline error: {0}")]
    Internal(String),
}

/// Errors that can occur during parameter extraction and parsing
#[derive(Error, Debug)]
pub enum ParamError {
    #[error("Missing parameter: {0}")]
    Missing(String),

    #[error("Failed to parse parameter '{param}' with value '{value}': {error}")]
    ParseError {
        param: String,
        value: String,
        error: String,
    },
}

/// Handler function type for request processing
pub type HandlerFn = dyn Fn(ElifRequest) -> NextFuture<'static> + Send + Sync;

/// Configuration for route-specific middleware groups
#[derive(Debug, Clone)]
pub struct MiddlewareGroup {
    pub name: String,
    pub pipeline: MiddlewarePipelineV2,
}

/// The main request processing pipeline
pub struct RequestPipeline {
    /// Route matcher for resolving incoming requests
    matcher: Arc<RouteMatcher>,
    /// Global middleware that runs for all requests
    global_middleware: MiddlewarePipelineV2,
    /// Named middleware groups for route-specific execution
    middleware_groups: HashMap<String, MiddlewarePipelineV2>,
    /// Route handlers mapped by route ID (wrapped in Arc for efficient sharing)
    handlers: Arc<HashMap<String, Arc<HandlerFn>>>,
}

impl RequestPipeline {
    /// Create a new request pipeline with a route matcher
    pub fn new(matcher: RouteMatcher) -> Self {
        Self {
            matcher: Arc::new(matcher),
            global_middleware: MiddlewarePipelineV2::new(),
            middleware_groups: HashMap::new(),
            handlers: Arc::new(HashMap::new()),
        }
    }

    /// Add global middleware that runs for all requests
    pub fn add_global_middleware<M>(mut self, middleware: M) -> Self
    where
        M: crate::middleware::v2::Middleware + 'static,
    {
        self.global_middleware = self.global_middleware.add(middleware);
        self
    }

    /// Add a named middleware group for route-specific execution
    pub fn add_middleware_group<S: Into<String>>(
        mut self,
        name: S,
        pipeline: MiddlewarePipelineV2,
    ) -> Self {
        self.middleware_groups.insert(name.into(), pipeline);
        self
    }

    /// Register a handler for a specific route ID
    pub fn add_handler<S: Into<String>, F>(mut self, route_id: S, handler: F) -> Self
    where
        F: Fn(ElifRequest) -> NextFuture<'static> + Send + Sync + 'static,
    {
        // We need to get mutable access to the HashMap inside the Arc
        // Since we're in a builder pattern, we can safely unwrap and modify
        let handlers = Arc::get_mut(&mut self.handlers)
            .expect("RequestPipeline handlers should be exclusively owned during building");
        handlers.insert(route_id.into(), Arc::new(handler));
        self
    }

    /// Process an incoming request through the complete pipeline
    pub async fn process(&self, request: ElifRequest) -> ElifResponse {
        match self.process_internal(request).await {
            Ok(response) => response,
            Err(error) => self.handle_pipeline_error(error),
        }
    }

    /// Internal request processing with error handling
    async fn process_internal(&self, request: ElifRequest) -> Result<ElifResponse, PipelineError> {
        // 1. Route resolution
        let route_match = self.resolve_route(&request)?;

        // 2. Parameter injection
        let request_with_params = self.inject_params(request, &route_match);

        // 3. Build complete middleware pipeline for this route
        let complete_pipeline = self.build_route_pipeline(&route_match)?;

        // 4. Execute middleware + handler
        // Use Arc::clone for cheap reference counting instead of cloning the entire HashMap
        let route_id = route_match.route_id.clone();
        let handlers = Arc::clone(&self.handlers);
        let response = complete_pipeline.execute(request_with_params, move |req| {
            let route_id = route_id.clone();
            let handlers = Arc::clone(&handlers);
            Box::pin(async move {
                match handlers.get(&route_id) {
                    Some(handler) => handler(req).await,
                    None => {
                        ElifResponse::internal_server_error()
                            .with_json(&serde_json::json!({
                                "error": {
                                    "code": "handler_not_found",
                                    "message": format!("No handler registered for route: {}", route_id)
                                }
                            }))
                    }
                }
            })
        }).await;

        Ok(response)
    }

    /// Resolve incoming request to a matching route
    fn resolve_route(&self, request: &ElifRequest) -> Result<RouteMatch, PipelineError> {
        let http_method = match request.method.to_axum() {
            &axum::http::Method::GET => HttpMethod::GET,
            &axum::http::Method::POST => HttpMethod::POST,
            &axum::http::Method::PUT => HttpMethod::PUT,
            &axum::http::Method::DELETE => HttpMethod::DELETE,
            &axum::http::Method::PATCH => HttpMethod::PATCH,
            &axum::http::Method::HEAD => HttpMethod::HEAD,
            &axum::http::Method::OPTIONS => HttpMethod::OPTIONS,
            &axum::http::Method::TRACE => HttpMethod::TRACE,
            unsupported => {
                return Err(PipelineError::MethodNotAllowed {
                    method: unsupported.to_string(),
                });
            }
        };

        self.matcher
            .resolve(&http_method, request.path())
            .ok_or_else(|| PipelineError::RouteNotFound {
                method: http_method,
                path: request.path().to_string(),
            })
    }

    /// Inject route parameters into the request
    fn inject_params(&self, mut request: ElifRequest, route_match: &RouteMatch) -> ElifRequest {
        for (key, value) in &route_match.params {
            request.add_path_param(key, value);
        }
        request
    }

    /// Build the complete middleware pipeline for a specific route
    fn build_route_pipeline(
        &self,
        _route_match: &RouteMatch,
    ) -> Result<MiddlewarePipelineV2, PipelineError> {
        let pipeline = self.global_middleware.clone();

        // Add route-specific middleware groups
        // For now, we'll look for middleware group names in route metadata
        // This can be extended to support route definition with middleware specifications

        Ok(pipeline)
    }

    /// Handle pipeline errors by converting them to appropriate HTTP responses
    fn handle_pipeline_error(&self, error: PipelineError) -> ElifResponse {
        match error {
            PipelineError::RouteNotFound { .. } => {
                ElifResponse::not_found().with_json(&serde_json::json!({
                    "error": {
                        "code": "not_found",
                        "message": "The requested resource was not found"
                    }
                }))
            }
            PipelineError::MethodNotAllowed { method } => ElifResponse::with_status(
                ElifStatusCode::METHOD_NOT_ALLOWED,
            )
            .with_json(&serde_json::json!({
                "error": {
                    "code": "method_not_allowed",
                    "message": format!("HTTP method '{}' is not supported", method),
                    "hint": "Supported methods: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, TRACE"
                }
            })),
            PipelineError::Parameter(param_error) => {
                ElifResponse::bad_request().with_json(&serde_json::json!({
                    "error": {
                        "code": "parameter_error",
                        "message": param_error.to_string()
                    }
                }))
            }
            PipelineError::Middleware(msg)
            | PipelineError::Handler(msg)
            | PipelineError::Internal(msg) => {
                ElifResponse::internal_server_error().with_json(&serde_json::json!({
                    "error": {
                        "code": "internal_error",
                        "message": msg
                    }
                }))
            }
        }
    }

    /// Get statistics about the pipeline
    pub fn stats(&self) -> PipelineStats {
        PipelineStats {
            total_routes: self.matcher.all_routes().len(),
            global_middleware_count: self.global_middleware.len(),
            middleware_groups: self.middleware_groups.len(),
            registered_handlers: self.handlers.len(),
        }
    }

    /// Get the route matcher for introspection
    pub fn matcher(&self) -> &RouteMatcher {
        &self.matcher
    }

    /// Get global middleware pipeline for introspection
    pub fn global_middleware(&self) -> &MiddlewarePipelineV2 {
        &self.global_middleware
    }

    /// Get middleware groups for introspection
    pub fn middleware_groups(&self) -> &HashMap<String, MiddlewarePipelineV2> {
        &self.middleware_groups
    }
}

impl std::fmt::Debug for RequestPipeline {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RequestPipeline")
            .field("matcher", &self.matcher)
            .field("global_middleware", &self.global_middleware)
            .field("middleware_groups", &self.middleware_groups)
            .field("handlers", &self.handlers.len())
            .finish()
    }
}

/// Statistics about the request pipeline
#[derive(Debug, Clone)]
pub struct PipelineStats {
    pub total_routes: usize,
    pub global_middleware_count: usize,
    pub middleware_groups: usize,
    pub registered_handlers: usize,
}

/// Builder for creating request pipelines
pub struct RequestPipelineBuilder {
    matcher: Option<RouteMatcher>,
    global_middleware: MiddlewarePipelineV2,
    middleware_groups: HashMap<String, MiddlewarePipelineV2>,
    handlers: HashMap<String, Arc<HandlerFn>>,
}

impl RequestPipelineBuilder {
    /// Create a new pipeline builder
    pub fn new() -> Self {
        Self {
            matcher: None,
            global_middleware: MiddlewarePipelineV2::new(),
            middleware_groups: HashMap::new(),
            handlers: HashMap::new(),
        }
    }

    /// Set the route matcher
    pub fn matcher(mut self, matcher: RouteMatcher) -> Self {
        self.matcher = Some(matcher);
        self
    }

    /// Add global middleware
    pub fn global_middleware<M>(mut self, middleware: M) -> Self
    where
        M: crate::middleware::v2::Middleware + 'static,
    {
        self.global_middleware = self.global_middleware.add(middleware);
        self
    }

    /// Add a middleware group
    pub fn middleware_group<S: Into<String>>(
        mut self,
        name: S,
        pipeline: MiddlewarePipelineV2,
    ) -> Self {
        self.middleware_groups.insert(name.into(), pipeline);
        self
    }

    /// Add a route handler
    pub fn handler<S: Into<String>, F>(mut self, route_id: S, handler: F) -> Self
    where
        F: Fn(ElifRequest) -> NextFuture<'static> + Send + Sync + 'static,
    {
        self.handlers.insert(route_id.into(), Arc::new(handler));
        self
    }

    /// Build the request pipeline
    pub fn build(self) -> Result<RequestPipeline, PipelineError> {
        let matcher = self
            .matcher
            .ok_or_else(|| PipelineError::Internal("Route matcher is required".to_string()))?;

        Ok(RequestPipeline {
            matcher: Arc::new(matcher),
            global_middleware: self.global_middleware,
            middleware_groups: self.middleware_groups,
            handlers: Arc::new(self.handlers),
        })
    }
}

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

/// Helper functions for parameter extraction with better error handling
pub mod parameter_extraction {
    use super::{ElifRequest, ParamError};
    use std::fmt::{Debug, Display};
    use std::str::FromStr;

    /// Extract and parse a path parameter with type conversion
    pub fn extract_path_param<T>(request: &ElifRequest, name: &str) -> Result<T, ParamError>
    where
        T: FromStr,
        T::Err: Debug + Display,
    {
        let param_value = request
            .path_param(name)
            .ok_or_else(|| ParamError::Missing(name.to_string()))?;

        param_value.parse().map_err(|e| ParamError::ParseError {
            param: name.to_string(),
            value: param_value.clone(),
            error: format!("{}", e),
        })
    }

    /// Extract and parse a query parameter with type conversion
    pub fn extract_query_param<T>(
        request: &ElifRequest,
        name: &str,
    ) -> Result<Option<T>, ParamError>
    where
        T: FromStr,
        T::Err: Debug + Display,
    {
        if let Some(param_value) = request.query_param(name) {
            let parsed = param_value.parse().map_err(|e| ParamError::ParseError {
                param: name.to_string(),
                value: param_value.clone(),
                error: format!("{}", e),
            })?;
            Ok(Some(parsed))
        } else {
            Ok(None)
        }
    }

    /// Extract required query parameter with type conversion
    pub fn extract_required_query_param<T>(
        request: &ElifRequest,
        name: &str,
    ) -> Result<T, ParamError>
    where
        T: FromStr,
        T::Err: Debug + Display,
    {
        extract_query_param(request, name)?.ok_or_else(|| ParamError::Missing(name.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::middleware::v2::{LoggingMiddleware, MiddlewarePipelineV2};
    use crate::response::{ElifResponse, ElifStatusCode};
    use crate::routing::RouteMatcherBuilder;

    #[tokio::test]
    async fn test_basic_pipeline_processing() {
        // Create a simple route matcher
        let matcher = RouteMatcherBuilder::new()
            .get("home".to_string(), "/".to_string())
            .get("user_show".to_string(), "/users/{id}".to_string())
            .build()
            .unwrap();

        // Create pipeline with a simple handler
        let pipeline = RequestPipelineBuilder::new()
            .matcher(matcher)
            .handler("home", |_req| {
                Box::pin(async move { ElifResponse::ok().with_text("Welcome home!") })
            })
            .handler("user_show", |req| {
                Box::pin(async move {
                    let user_id: u32 = match parameter_extraction::extract_path_param(&req, "id") {
                        Ok(id) => id,
                        Err(_) => return ElifResponse::bad_request().with_text("Invalid user ID"),
                    };
                    ElifResponse::ok().with_json(&serde_json::json!({
                        "user_id": user_id,
                        "message": "User details"
                    }))
                })
            })
            .build()
            .unwrap();

        // Test home route
        let home_request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/".parse().unwrap(),
            crate::response::ElifHeaderMap::new(),
        );

        let home_response = pipeline.process(home_request).await;
        assert_eq!(home_response.status_code(), ElifStatusCode::OK);

        // Test user route with parameter
        let user_request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/users/123".parse().unwrap(),
            crate::response::ElifHeaderMap::new(),
        );

        let user_response = pipeline.process(user_request).await;
        assert_eq!(user_response.status_code(), ElifStatusCode::OK);
    }

    #[tokio::test]
    async fn test_pipeline_with_middleware() {
        let matcher = RouteMatcherBuilder::new()
            .get("test".to_string(), "/test".to_string())
            .build()
            .unwrap();

        let pipeline = RequestPipelineBuilder::new()
            .matcher(matcher)
            .global_middleware(LoggingMiddleware)
            .handler("test", |_req| {
                Box::pin(async move { ElifResponse::ok().with_text("Test response") })
            })
            .build()
            .unwrap();

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

        let response = pipeline.process(request).await;
        assert_eq!(response.status_code(), ElifStatusCode::OK);
    }

    #[tokio::test]
    async fn test_pipeline_route_not_found() {
        let matcher = RouteMatcherBuilder::new()
            .get("home".to_string(), "/".to_string())
            .build()
            .unwrap();

        let pipeline = RequestPipelineBuilder::new()
            .matcher(matcher)
            .build()
            .unwrap();

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

        let response = pipeline.process(request).await;
        assert_eq!(response.status_code(), ElifStatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_pipeline_handler_not_found() {
        let matcher = RouteMatcherBuilder::new()
            .get("test".to_string(), "/test".to_string())
            .build()
            .unwrap();

        // Create pipeline without registering a handler
        let pipeline = RequestPipelineBuilder::new()
            .matcher(matcher)
            .build()
            .unwrap();

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

        let response = pipeline.process(request).await;
        assert_eq!(
            response.status_code(),
            ElifStatusCode::INTERNAL_SERVER_ERROR
        );
    }

    #[tokio::test]
    async fn test_parameter_extraction_helpers() {
        let mut request = ElifRequest::new(
            crate::request::ElifMethod::GET,
            "/users/123?page=2&limit=10".parse().unwrap(),
            crate::response::ElifHeaderMap::new(),
        );

        // Simulate parameter injection
        request.add_path_param("id", "123");
        request.add_query_param("page", "2");
        request.add_query_param("limit", "10");

        // Test path parameter extraction
        let user_id: u32 = parameter_extraction::extract_path_param(&request, "id").unwrap();
        assert_eq!(user_id, 123);

        // Test query parameter extraction
        let page: Option<u32> =
            parameter_extraction::extract_query_param(&request, "page").unwrap();
        assert_eq!(page, Some(2));

        // Test required query parameter extraction
        let limit: u32 =
            parameter_extraction::extract_required_query_param(&request, "limit").unwrap();
        assert_eq!(limit, 10);

        // Test missing parameter
        let result = parameter_extraction::extract_path_param::<u32>(&request, "nonexistent");
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ParamError::Missing(_)));

        // Test invalid parameter parsing
        request.add_path_param("invalid", "not_a_number");
        let result = parameter_extraction::extract_path_param::<u32>(&request, "invalid");
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ParamError::ParseError { .. }));
    }

    #[tokio::test]
    async fn test_pipeline_stats() {
        let matcher = RouteMatcherBuilder::new()
            .get("route1".to_string(), "/route1".to_string())
            .get("route2".to_string(), "/route2".to_string())
            .build()
            .unwrap();

        let middleware_group = MiddlewarePipelineV2::new().add(LoggingMiddleware);

        let pipeline = RequestPipelineBuilder::new()
            .matcher(matcher)
            .global_middleware(LoggingMiddleware)
            .middleware_group("auth", middleware_group)
            .handler("route1", |_req| Box::pin(async move { ElifResponse::ok() }))
            .handler("route2", |_req| Box::pin(async move { ElifResponse::ok() }))
            .build()
            .unwrap();

        let stats = pipeline.stats();
        assert_eq!(stats.total_routes, 2);
        assert_eq!(stats.global_middleware_count, 1);
        assert_eq!(stats.middleware_groups, 1);
        assert_eq!(stats.registered_handlers, 2);
    }

    #[tokio::test]
    async fn test_arc_optimization_efficiency() {
        // This test demonstrates that Arc::clone is cheap even with many handlers
        let matcher = RouteMatcherBuilder::new()
            .get("test_route".to_string(), "/test".to_string())
            .build()
            .unwrap();

        // Create pipeline with many handlers to test Arc efficiency
        let mut builder = RequestPipelineBuilder::new().matcher(matcher);

        // Add 100 handlers to test performance
        for i in 0..100 {
            builder = builder.handler(format!("handler_{}", i), |_req| {
                Box::pin(async move { ElifResponse::ok() })
            });
        }

        builder = builder.handler("test_route", |_req| {
            Box::pin(async move { ElifResponse::ok().with_text("Test response") })
        });

        let pipeline = builder.build().unwrap();

        // Process multiple requests to verify Arc::clone efficiency
        for _ in 0..10 {
            let request = ElifRequest::new(
                crate::request::ElifMethod::GET,
                "/test".parse().unwrap(),
                crate::response::ElifHeaderMap::new(),
            );

            let response = pipeline.process(request).await;
            assert_eq!(response.status_code(), ElifStatusCode::OK);
        }

        // Verify we have many handlers
        let stats = pipeline.stats();
        assert_eq!(stats.registered_handlers, 101);

        // The key optimization: Arc::clone is O(1) regardless of HashMap size
        // Previously this would have been O(n) for each request due to HashMap cloning
    }

    #[tokio::test]
    async fn test_method_not_allowed_error() {
        let matcher = RouteMatcherBuilder::new()
            .get("test".to_string(), "/test".to_string())
            .build()
            .unwrap();

        let pipeline = RequestPipelineBuilder::new()
            .matcher(matcher)
            .handler("test", |_req| {
                Box::pin(async move { ElifResponse::ok().with_text("Test response") })
            })
            .build()
            .unwrap();

        // Create a request with CONNECT method (unsupported)
        let connect_method = crate::request::ElifMethod::from_axum(axum::http::Method::CONNECT);
        let request = ElifRequest::new(
            connect_method,
            "/test".parse().unwrap(),
            crate::response::ElifHeaderMap::new(),
        );

        let response = pipeline.process(request).await;
        assert_eq!(response.status_code(), ElifStatusCode::METHOD_NOT_ALLOWED);

        // Verify error message structure
        // Note: We can't easily test JSON content without body reading capabilities,
        // but we can verify the status code which is the most important part
    }

    #[tokio::test]
    async fn test_supported_methods_work() {
        let matcher = RouteMatcherBuilder::new()
            .get("get_test".to_string(), "/test".to_string())
            .post("post_test".to_string(), "/test".to_string())
            .put("put_test".to_string(), "/test".to_string())
            .delete("delete_test".to_string(), "/test".to_string())
            .build()
            .unwrap();

        let pipeline = RequestPipelineBuilder::new()
            .matcher(matcher)
            .handler("get_test", |_req| {
                Box::pin(async move { ElifResponse::ok().with_text("GET") })
            })
            .handler("post_test", |_req| {
                Box::pin(async move { ElifResponse::ok().with_text("POST") })
            })
            .handler("put_test", |_req| {
                Box::pin(async move { ElifResponse::ok().with_text("PUT") })
            })
            .handler("delete_test", |_req| {
                Box::pin(async move { ElifResponse::ok().with_text("DELETE") })
            })
            .build()
            .unwrap();

        // Test all supported methods work correctly
        let methods = [
            (crate::request::ElifMethod::GET, "GET"),
            (crate::request::ElifMethod::POST, "POST"),
            (crate::request::ElifMethod::PUT, "PUT"),
            (crate::request::ElifMethod::DELETE, "DELETE"),
        ];

        for (method, _expected_response) in methods {
            let request = ElifRequest::new(
                method,
                "/test".parse().unwrap(),
                crate::response::ElifHeaderMap::new(),
            );

            let response = pipeline.process(request).await;
            assert_eq!(response.status_code(), ElifStatusCode::OK);
        }
    }
}