idemio 0.1.1

Core framework for idemio products
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
//! Router configuration structures and builders
//!
//! This module provides the configuration system for the router, supporting both
//! single service configurations and shared multiservice configurations. It includes
//! builder patterns for constructing complex routing configurations programmatically.

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

/// Top-level configuration structure for router services
///
/// This enum represents the two main configuration patterns supported:
/// - Single service configuration for simple routing scenarios
/// - Shared configuration for multiservice routing with different routing keys
#[derive(Debug, Serialize, Deserialize)]
pub enum ConfigStructure {
    /// Single service configuration
    ///
    /// Use this for simple routing scenarios where all routes belong to a single service.
    /// This is the most common configuration type for straightforward applications.
    #[serde(alias = "single", alias = "SINGLE")]
    Single(RouterConfig),

    /// Shared configuration for multiple services
    ///
    /// Use this for complex routing scenarios where multiple services need to be
    /// routed based on different criteria (headers, paths, etc.). Each service
    /// can have its own routing configuration.
    #[serde(alias = "shared", alias = "SHARED")]
    Shared(SharedConfig),
}

/// Types of routing keys supported by the router
///
/// This enum defines the different ways requests can be routed to services
/// in a shared configuration setup.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub enum RouteType {
    /// No specific routing - uses default routing behavior
    None,

    /// Route based on HTTP header value
    ///
    /// The string parameter specifies which header to examine for routing decisions.
    /// This is useful for service versioning, tenant isolation, or API key routing.
    #[serde(rename = "header", alias = "Header", alias = "HEADER")]
    Header(String),

    /// Route based on a request path
    ///
    /// This is the standard HTTP path-based routing used by most web applications.
    #[serde(rename = "path", alias = "Path", alias = "PATH")]
    Path,
}

impl RouteType {
    /// Create a header-based routing type
    ///
    /// # Arguments
    ///
    /// * `header_name` - The name of the HTTP header to use for routing
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let route_type = RouteType::header("X-Service-Version");
    /// ```
    pub fn header(header_name: impl Into<String>) -> Self {
        Self::Header(header_name.into())
    }

    /// Create a path-based routing type
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let route_type = RouteType::path();
    /// ```
    pub fn path() -> Self {
        Self::Path
    }
}

/// Configuration for shared multiservice routing
///
/// This structure defines how multiple services should be routed based on
/// a shared routing key. Each service can have its own complete router configuration.
#[derive(Debug, Serialize, Deserialize)]
pub struct SharedConfig {
    /// The routing key type that determines how to select services
    key: RouteType,
    /// Map of service names to their individual router configurations
    services: HashMap<String, RouterConfig>,
}

/// Main router configuration structure
///
/// This structure defines all the routing information for a service, including
/// - Available handlers
/// - Handler chains
/// - Route definitions mapping paths/methods to handler chains
///
/// # Fields
///
/// * `handlers` - Set of all available handler names
/// * `chains` - Named sequences of handlers that can be reused
/// * `routes` - Route definitions mapping requests to handler chains
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouterConfig {
    /// Set of all handler names available for routing
    pub(crate) handlers: HashSet<String>,
    /// Named handler chains for reusability
    pub(crate) chains: HashMap<String, Vec<String>>,
    /// Route definitions specifying how requests are handled
    pub(crate) routes: Routes,
}

/// Route definition structures for different routing types
///
/// This enum supports different types of routing mechanisms, allowing
/// flexibility in how requests are matched to handler chains.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Routes {
    /// HTTP request path-based routing
    ///
    /// Maps paths to HTTP methods to handler chains. This is the standard
    /// web application routing pattern.
    ///
    /// Structure: `path -> method -> PathChain`
    #[serde(rename = "path", alias = "Path", alias = "PATH")]
    HttpRequestPaths(HashMap<String, HashMap<String, PathChain>>),

    /// HTTP-header-based routing
    ///
    /// Maps header values to HTTP methods to handler chains. This is useful
    /// for service versioning, tenant routing, or API key-based routing.
    ///
    /// Structure: `header_value -> method -> PathChain`
    #[serde(rename = "header", alias = "Header", alias = "HEADER")]
    HttpHeaderPaths(HashMap<String, HashMap<String, PathChain>>),
}

/// Handler chain definition for a specific route
///
/// This structure defines the complete handler execution pipeline for a route,
/// including request processing, termination, and response processing phases.
/// All phases are optional, providing flexibility in handler chain design.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathChain {
    /// Handlers executed during the request processing phase
    ///
    /// These handlers run before the termination handler and can modify
    /// the request, perform authentication, validation, etc.
    #[serde(skip_serializing_if = "Option::is_none", rename = "request")]
    pub(crate) request_handlers: Option<Vec<String>>,

    /// The termination handler that produces the final response
    ///
    /// This handler is responsible for generating the actual response content.
    /// Only one termination handler is allowed per route.
    #[serde(skip_serializing_if = "Option::is_none", rename = "termination")]
    pub(crate) termination_handler: Option<String>,

    /// Handlers executed during the response processing phase
    ///
    /// These handlers run after the termination handler and can modify
    /// the response, add headers, perform logging, etc.
    #[serde(skip_serializing_if = "Option::is_none", rename = "response")]
    pub(crate) response_handlers: Option<Vec<String>>,
}

impl PathChain {
    /// Create a new empty path chain
    ///
    /// # Returns
    ///
    /// A new `PathChain` with all handler lists set to `None`
    pub fn new() -> Self {
        Self {
            request_handlers: None,
            termination_handler: None,
            response_handlers: None,
        }
    }

    /// Add a handler to the request processing phase
    ///
    /// # Arguments
    ///
    /// * `handler` - Name of the handler to add to the request phase
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    fn add_request_handler(&mut self, handler: impl Into<String>) -> &mut Self {
        self.request_handlers
            .get_or_insert_with(Vec::new)
            .push(handler.into());
        self
    }

    /// Set the termination handler for this path chain
    ///
    /// # Arguments
    ///
    /// * `handler` - Name of the termination handler
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    fn termination_handler(&mut self, handler: impl Into<String>) -> &mut Self {
        self.termination_handler = Some(handler.into());
        self
    }

    /// Add a handler to the response processing phase
    ///
    /// # Arguments
    ///
    /// * `handler` - Name of the handler to add to the response phase
    ///
    /// # Returns
    ///
    /// A mutable reference to self for method chaining
    fn add_response_handler(&mut self, handler: impl Into<String>) -> &mut Self {
        self.response_handlers
            .get_or_insert_with(Vec::new)
            .push(handler.into());
        self
    }
}

impl Default for PathChain {
    /// Create a default empty path chain
    fn default() -> Self {
        Self::new()
    }
}

/// Builder patterns for constructing router configurations
///
/// This module provides fluent builder APIs for creating complex router configurations
/// programmatically. It supports both single service and shared multiservice configurations.
pub mod builder {
    use super::*;

    /// Core configuration data shared across builders
    ///
    /// This structure holds the fundamental routing data that gets built up
    /// through the various builder patterns.
    pub struct ServiceConfigCore {
        /// Set of available handler names
        handlers: HashSet<String>,
        /// Named handler chains
        chains: HashMap<String, Vec<String>>,
        /// Route mappings from paths to methods to path chains
        routes: HashMap<String, HashMap<String, PathChain>>,
    }

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

    impl ServiceConfigCore {
        /// Create a new empty service configuration core
        pub fn new() -> Self {
            Self {
                handlers: HashSet::new(),
                chains: HashMap::new(),
                routes: HashMap::new(),
            }
        }

        /// Add a single handler to the configuration
        ///
        /// # Arguments
        ///
        /// * `handler_name` - Name of the handler to register
        pub fn add_handler(&mut self, handler_name: impl Into<String>) {
            self.handlers.insert(handler_name.into());
        }

        /// Add multiple handlers to the configuration
        ///
        /// # Arguments
        ///
        /// * `handler_names` - Slice of handler names to register
        pub fn add_handlers(&mut self, handler_names: &[impl AsRef<str>]) {
            for name in handler_names {
                self.handlers.insert(name.as_ref().to_string());
            }
        }

        /// Add a named handler chain to the configuration
        ///
        /// # Arguments
        ///
        /// * `chain_name` - Name of the chain for later reference
        /// * `handler_names` - Ordered list of handlers in the chain
        pub fn add_chain(
            &mut self,
            chain_name: impl Into<String>,
            handler_names: &[impl AsRef<str>],
        ) {
            let chain = handler_names
                .iter()
                .map(|name| name.as_ref().to_string())
                .collect();
            self.chains.insert(chain_name.into(), chain);
        }

        /// Ensure a route path exists in the configuration
        ///
        /// # Arguments
        ///
        /// * `path` - The route path to ensure exists
        pub fn ensure_route_exists(&mut self, path: &str) {
            self.routes.entry(path.to_string()).or_default();
        }

        /// Add a method handler to a specific path
        ///
        /// # Arguments
        ///
        /// * `path` - The route path
        /// * `method` - HTTP method (GET, POST, etc.)
        /// * `path_chain` - Handler chain configuration for this path/method
        pub fn add_method(&mut self, path: &str, method: String, path_chain: PathChain) {
            self.routes
                .entry(path.to_string())
                .or_default()
                .insert(method, path_chain);
        }

        /// Build the final router configuration
        ///
        /// # Returns
        ///
        /// A complete `RouterConfig` ready for use
        pub fn build(self) -> RouterConfig {
            RouterConfig {
                handlers: self.handlers,
                chains: self.chains,
                routes: Routes::HttpRequestPaths(self.routes),
            }
        }
    }

    /// Trait for service-level configuration builders
    ///
    /// This trait provides the common interface for building service configurations,
    /// supporting both single and shared service scenarios.
    pub trait ServiceBuilder: Sized {
        /// The route builder type for this service builder
        type RouteBuilder;

        /// Get mutable access to the core configuration
        fn core(&mut self) -> &mut ServiceConfigCore;

        /// Add a single handler to the service
        ///
        /// # Arguments
        ///
        /// * `handler_name` - Name of the handler to add
        fn handler(mut self, handler_name: impl Into<String>) -> Self {
            self.core().add_handler(handler_name);
            self
        }

        /// Add multiple handlers to the service
        ///
        /// # Arguments
        ///
        /// * `handler_names` - Slice of handler names to add
        fn handlers(mut self, handler_names: &[impl AsRef<str>]) -> Self {
            self.core().add_handlers(handler_names);
            self
        }

        /// Add a named handler chain to the service
        ///
        /// # Arguments
        ///
        /// * `chain_name` - Name of the chain
        /// * `handler_names` - Ordered handlers in the chain
        fn chain(
            mut self,
            chain_name: impl Into<String>,
            handler_names: &[impl AsRef<str>],
        ) -> Self {
            self.core().add_chain(chain_name, handler_names);
            self
        }

        /// Start building a route configuration
        ///
        /// # Arguments
        ///
        /// * `path` - The route path to configure
        fn route(self, path: impl Into<String>) -> Self::RouteBuilder;
    }

    /// Trait for route-level configuration builders
    ///
    /// This trait provides the interface for configuring individual routes
    /// and their associated HTTP methods.
    pub trait RouteBuilder: Sized {
        /// The method builder type for this route builder
        type MethodBuilder;
        /// The parent service builder type
        type ServiceBuilder;

        /// Create a method builder for a specific HTTP method
        ///
        /// # Arguments
        ///
        /// * `method` - The HTTP method to configure
        fn create_method_builder(self, method: impl Into<String>) -> Self::MethodBuilder;

        /// Finish configuring this route and return to the service builder
        fn end_route(self) -> Self::ServiceBuilder;

        /// Configure the HEAD method for this route
        fn head(self) -> Self::MethodBuilder {
            self.create_method_builder("HEAD")
        }

        /// Configure the OPTIONS method for this route
        fn options(self) -> Self::MethodBuilder {
            self.create_method_builder("OPTIONS")
        }

        /// Configure the GET method for this route
        fn get(self) -> Self::MethodBuilder {
            self.create_method_builder("GET")
        }

        /// Configure the POST method for this route
        fn post(self) -> Self::MethodBuilder {
            self.create_method_builder("POST")
        }

        /// Configure the PUT method for this route
        fn put(self) -> Self::MethodBuilder {
            self.create_method_builder("PUT")
        }

        /// Configure the DELETE method for this route
        fn delete(self) -> Self::MethodBuilder {
            self.create_method_builder("DELETE")
        }

        /// Configure the PATCH method for this route
        fn patch(self) -> Self::MethodBuilder {
            self.create_method_builder("PATCH")
        }
    }

    /// Trait for method-level configuration builders
    ///
    /// This trait provides the interface for configuring handler chains
    /// for specific route/method combinations.
    pub trait MethodBuilder: Sized {
        /// The parent route builder type
        type RouteBuilder;

        /// Get mutable access to the path chain being built
        fn path_chain(&mut self) -> &mut PathChain;

        /// Get access to the available handler chains
        fn chains(&self) -> &HashMap<String, Vec<String>>;

        /// Set multiple request handlers
        ///
        /// # Arguments
        ///
        /// * `handlers` - List of handler names for request processing
        fn request_handlers(mut self, handlers: &[impl AsRef<str>]) -> Self {
            let path_chain = self.path_chain();
            for handler in handlers {
                path_chain.add_request_handler(handler.as_ref().to_string());
            }
            self
        }

        /// Add a single request handler
        ///
        /// # Arguments
        ///
        /// * `handler` - Handler name for request processing
        fn request_handler(mut self, handler: impl Into<String>) -> Self {
            self.path_chain().add_request_handler(handler);
            self
        }

        /// Set the termination handler
        ///
        /// # Arguments
        ///
        /// * `handler` - Handler name for response generation
        fn termination_handler(mut self, handler: impl Into<String>) -> Self {
            self.path_chain().termination_handler(handler);
            self
        }

        /// Set multiple response handlers
        ///
        /// # Arguments
        ///
        /// * `handlers` - List of handler names for response processing
        fn response_handlers(mut self, handlers: &[impl AsRef<str>]) -> Self {
            let path_chain = self.path_chain();
            for handler in handlers {
                path_chain.add_response_handler(handler.as_ref().to_string());
            }
            self
        }

        /// Add a single response handler
        ///
        /// # Arguments
        ///
        /// * `handler` - Handler name for response processing
        fn response_handler(mut self, handler: impl Into<String>) -> Self {
            self.path_chain().add_response_handler(handler);
            self
        }

        /// Use a pre-defined chain for request processing
        ///
        /// # Arguments
        ///
        /// * `chain_name` - Name of the chain to use
        fn request_chain(mut self, chain_name: impl AsRef<str>) -> Self {
            if let Some(chain_handlers) = self.chains().get(chain_name.as_ref()) {
                let handlers: Vec<String> = chain_handlers.clone();
                for handler in handlers {
                    self.path_chain().add_request_handler(handler);
                }
            }
            self
        }

        /// Use a pre-defined chain for response processing
        ///
        /// # Arguments
        ///
        /// * `chain_name` - Name of the chain to use
        fn response_chain(mut self, chain_name: impl AsRef<str>) -> Self {
            if let Some(chain_handlers) = self.chains().get(chain_name.as_ref()) {
                let handlers: Vec<String> = chain_handlers.clone();
                for handler in handlers {
                    self.path_chain().add_response_handler(handler);
                }
            }
            self
        }

        /// Finish configuring this method and return to the route builder
        fn end_method(self) -> Self::RouteBuilder;
    }

    /// Builder for single service configurations
    ///
    /// This builder creates configurations for single-service routing scenarios,
    /// which is the most common use case for simple applications.
    pub struct SingleServiceConfigBuilder {
        /// Core configuration being built
        core: ServiceConfigCore,
    }

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

    impl SingleServiceConfigBuilder {
        /// Create a new single service configuration builder
        pub fn new() -> Self {
            Self {
                core: ServiceConfigCore::new(),
            }
        }

        /// Build the final router configuration
        ///
        /// # Returns
        ///
        /// A complete `RouterConfig` ready for use
        pub fn build(self) -> RouterConfig {
            self.core.build()
        }
    }

    impl ServiceBuilder for SingleServiceConfigBuilder {
        type RouteBuilder = SingleServiceRouteBuilder;

        fn core(&mut self) -> &mut ServiceConfigCore {
            &mut self.core
        }

        fn route(mut self, path: impl Into<String>) -> Self::RouteBuilder {
            let path_str = path.into();
            self.core.ensure_route_exists(&path_str);
            SingleServiceRouteBuilder {
                config_builder: self,
                current_path: path_str,
            }
        }
    }

    /// Route builder for single service configurations
    pub struct SingleServiceRouteBuilder {
        /// Parent configuration builder
        config_builder: SingleServiceConfigBuilder,
        /// Path being configured
        current_path: String,
    }

    impl RouteBuilder for SingleServiceRouteBuilder {
        type MethodBuilder = SingleServiceMethodBuilder;
        type ServiceBuilder = SingleServiceConfigBuilder;

        fn create_method_builder(self, method: impl Into<String>) -> Self::MethodBuilder {
            SingleServiceMethodBuilder {
                route_builder: self,
                method: method.into(),
                path_chain: PathChain::new(),
            }
        }

        fn end_route(self) -> Self::ServiceBuilder {
            self.config_builder
        }
    }

    /// Method builder for single service configurations
    pub struct SingleServiceMethodBuilder {
        /// Parent route builder
        route_builder: SingleServiceRouteBuilder,
        /// HTTP method being configured
        method: String,
        /// Path chain being built
        path_chain: PathChain,
    }

    impl MethodBuilder for SingleServiceMethodBuilder {
        type RouteBuilder = SingleServiceRouteBuilder;

        fn path_chain(&mut self) -> &mut PathChain {
            &mut self.path_chain
        }

        fn chains(&self) -> &HashMap<String, Vec<String>> {
            &self.route_builder.config_builder.core.chains
        }

        fn end_method(self) -> Self::RouteBuilder {
            let mut route_builder = self.route_builder;
            route_builder.config_builder.core.add_method(
                &route_builder.current_path,
                self.method,
                self.path_chain,
            );
            route_builder
        }
    }

    /// Builder for shared multiservice configurations
    ///
    /// This builder creates configurations for complex routing scenarios where
    /// multiple services need different routing strategies.
    pub struct SharedConfigBuilder {
        /// The routing key type
        key: RouteType,
        /// Map of services being configured
        services: HashMap<String, RouterConfig>,
    }

    impl SharedConfigBuilder {
        /// Create a new shared configuration builder
        pub fn new() -> Self {
            Self {
                key: RouteType::None,
                services: HashMap::new(),
            }
        }

        /// Set the routing type for service selection
        ///
        /// # Arguments
        ///
        /// * `route_type` - How to route between services
        pub fn route_type(mut self, route_type: RouteType) -> Self {
            self.key = route_type;
            self
        }

        /// Start configuring a specific service
        ///
        /// # Arguments
        ///
        /// * `service_name` - Name of the service to configure
        pub fn service(self, service_name: impl Into<String>) -> SharedServiceBuilder {
            SharedServiceBuilder {
                shared_builder: self,
                service_name: service_name.into(),
                core: ServiceConfigCore::new(),
            }
        }

        /// Build the final shared configuration
        ///
        /// # Returns
        ///
        /// A complete `SharedConfig` ready for use
        pub fn build(self) -> SharedConfig {
            SharedConfig {
                key: self.key,
                services: self.services,
            }
        }
    }

    /// Service builder for shared configurations
    pub struct SharedServiceBuilder {
        /// Parent shared configuration builder
        shared_builder: SharedConfigBuilder,
        /// Name of the service being configured
        service_name: String,
        /// Core configuration for this service
        core: ServiceConfigCore,
    }

    impl SharedServiceBuilder {
        /// Finish configuring this service and return to the shared builder
        pub fn end_service(mut self) -> SharedConfigBuilder {
            let config = self.core.build();
            self.shared_builder
                .services
                .insert(self.service_name, config);
            self.shared_builder
        }
    }

    impl ServiceBuilder for SharedServiceBuilder {
        type RouteBuilder = SharedServiceRouteBuilder;

        fn core(&mut self) -> &mut ServiceConfigCore {
            &mut self.core
        }

        fn route(mut self, path: impl Into<String>) -> Self::RouteBuilder {
            let path_str = path.into();
            self.core.ensure_route_exists(&path_str);
            SharedServiceRouteBuilder {
                service_builder: self,
                current_path: path_str,
            }
        }
    }

    /// Route builder for shared service configurations
    pub struct SharedServiceRouteBuilder {
        /// Parent service builder
        service_builder: SharedServiceBuilder,
        /// Path being configured
        current_path: String,
    }

    impl RouteBuilder for SharedServiceRouteBuilder {
        type MethodBuilder = SharedServiceMethodBuilder;
        type ServiceBuilder = SharedServiceBuilder;

        fn create_method_builder(self, method: impl Into<String>) -> Self::MethodBuilder {
            SharedServiceMethodBuilder {
                route_builder: self,
                method: method.into(),
                path_chain: PathChain::new(),
            }
        }

        fn end_route(self) -> Self::ServiceBuilder {
            self.service_builder
        }
    }

    /// Method builder for shared service configurations
    pub struct SharedServiceMethodBuilder {
        /// Parent route builder
        route_builder: SharedServiceRouteBuilder,
        /// HTTP method being configured
        method: String,
        /// Path chain being built
        path_chain: PathChain,
    }

    impl MethodBuilder for SharedServiceMethodBuilder {
        type RouteBuilder = SharedServiceRouteBuilder;

        fn path_chain(&mut self) -> &mut PathChain {
            &mut self.path_chain
        }

        fn chains(&self) -> &HashMap<String, Vec<String>> {
            &self.route_builder.service_builder.core.chains
        }

        fn end_method(self) -> Self::RouteBuilder {
            let mut route_builder = self.route_builder;
            route_builder.service_builder.core.add_method(
                &route_builder.current_path,
                self.method,
                self.path_chain,
            );
            route_builder
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        /// Test building configurations with multiple methods on the same route
        #[test]
        #[rustfmt::skip]
        fn test_single_service_multiple_methods_same_route() {
            let config = SingleServiceConfigBuilder::new()
                .handler("handler1")
                .handler("handler2")
                .route("/api/test")
                    .get()
                        .request_handler("handler1")
                        .termination_handler("handler2")
                    .end_method()
                    .post()
                        .request_handler("handler1")
                        .termination_handler("handler2")
                    .end_method()
                .end_route()
                .build();

            assert!(config.handlers.contains("handler1"));
            assert!(config.handlers.contains("handler2"));
        }

        /// Test shared service configuration building
        #[test]
        #[rustfmt::skip]
        fn test_shared_service_multiple_methods_same_route() {
            let config = SharedConfigBuilder::new()
                .route_type(RouteType::path())
                .service("service1")
                    .handler("handler1")
                    .route("/api/test")
                        .get()
                            .termination_handler("handler1")
                        .end_method()
                    .end_route()
                .end_service()
                .build();

            assert!(config.services.contains_key("service1"));
        }

        /// Test fluent builder chaining
        #[test]
        #[rustfmt::skip]
        fn test_route_builder_chaining() {
            let config = SingleServiceConfigBuilder::new()
                .handlers(&["auth", "validate", "process", "respond"])
                .chain("request_chain", &["auth", "validate"])
                .chain("response_chain", &["respond"])
                .route("/api/users")
                    .get()
                        .request_chain("request_chain")
                        .termination_handler("process")
                        .response_chain("response_chain")
                    .end_method()
                    .post()
                        .request_handlers(&["auth", "validate"])
                        .termination_handler("process")
                        .response_handler("respond")
                    .end_method()
                .end_route()
                .build();

            assert_eq!(config.handlers.len(), 4);
            assert_eq!(config.chains.len(), 2);
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use serde_json;

    /// Test loading shared configuration from JSON
    #[test]
    fn load_shared_config() {
        let json_config = r#"
        {
            "shared": {
                "key": "path",
                "services": {
                    "api_v1": {
                        "handlers": ["auth", "handler1"],
                        "chains": {},
                        "routes": {
                            "path": {
                                "/users": {
                                    "GET": {
                                        "request": ["auth"],
                                        "termination": "handler1"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        "#;

        let config: ConfigStructure = serde_json::from_str(json_config).unwrap();
        match config {
            ConfigStructure::Shared(shared) => {
                assert_eq!(shared.key, RouteType::Path);
                assert!(shared.services.contains_key("api_v1"));
            }
            _ => panic!("Expected shared configuration"),
        }
    }

    /// Test loading a single service configuration from JSON
    #[test]
    fn load_single_config() {
        let json_config = r#"
        {
            "single": {
                "handlers": ["handler1", "handler2"],
                "chains": {
                    "auth_chain": ["handler1", "handler2"]
                },
                "routes": {
                    "path": {
                        "/test": {
                            "GET": {
                                "termination": "handler1"
                            }
                        }
                    }
                }
            }
        }
        "#;

        let config: ConfigStructure = serde_json::from_str(json_config).unwrap();
        match config {
            ConfigStructure::Single(single) => {
                assert!(single.handlers.contains("handler1"));
                assert!(single.handlers.contains("handler2"));
                assert!(single.chains.contains_key("auth_chain"));
            }
            _ => panic!("Expected single configuration"),
        }
    }
}