this-rs 0.0.9

Framework for building complex multi-entity REST and GraphQL APIs with many relationships
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
//! ServerBuilder for fluent API to build HTTP servers

use super::entity_registry::EntityRegistry;
use super::exposure::RestExposure;
use super::host::ServerHost;
use crate::config::LinksConfig;
use crate::core::events::EventBus;
use crate::core::module::Module;
use crate::core::service::LinkService;
use crate::core::{EntityCreator, EntityFetcher};
use crate::events::SinkFactory;
use crate::events::sinks::SinkRegistry;
use crate::events::sinks::device_tokens::DeviceTokenStore;
use crate::events::sinks::in_app::NotificationStore;
use crate::events::sinks::preferences::NotificationPreferencesStore;
use anyhow::Result;
use axum::Router;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::net::TcpListener;

/// Builder for creating HTTP servers with auto-registered routes
///
/// # Example
///
/// ```ignore
/// let app = ServerBuilder::new()
///     .with_link_service(InMemoryLinkService::new())
///     .register_module(MyModule)
///     .build()?;
/// ```
pub struct ServerBuilder {
    link_service: Option<Arc<dyn LinkService>>,
    entity_registry: EntityRegistry,
    configs: Vec<LinksConfig>,
    modules: Vec<Arc<dyn Module>>,
    custom_routes: Vec<Router>,
    event_bus: Option<EventBus>,

    // Manual overrides for event system stores
    sink_registry: Option<SinkRegistry>,
    notification_store: Option<Arc<NotificationStore>>,
    device_token_store: Option<Arc<DeviceTokenStore>>,
    preferences_store: Option<Arc<NotificationPreferencesStore>>,
}

impl ServerBuilder {
    /// Create a new ServerBuilder
    pub fn new() -> Self {
        Self {
            link_service: None,
            entity_registry: EntityRegistry::new(),
            configs: Vec::new(),
            modules: Vec::new(),
            custom_routes: Vec::new(),
            event_bus: None,
            sink_registry: None,
            notification_store: None,
            device_token_store: None,
            preferences_store: None,
        }
    }

    /// Set the link service (required)
    pub fn with_link_service(mut self, service: impl LinkService + 'static) -> Self {
        self.link_service = Some(Arc::new(service));
        self
    }

    /// Add custom routes to the server
    ///
    /// Use this to add routes that don't fit the CRUD pattern, such as:
    /// - Authentication endpoints (/login, /logout)
    /// - OAuth flows (/oauth/token, /oauth/callback)
    /// - Webhooks (/webhooks/stripe)
    /// - Custom business logic endpoints
    ///
    /// # Example
    ///
    /// ```ignore
    /// use axum::{Router, routing::{post, get}, Json};
    /// use serde_json::json;
    ///
    /// let auth_routes = Router::new()
    ///     .route("/login", post(login_handler))
    ///     .route("/logout", post(logout_handler))
    ///     .route("/oauth/token", post(oauth_token_handler));
    ///
    /// ServerBuilder::new()
    ///     .with_link_service(service)
    ///     .with_custom_routes(auth_routes)
    ///     .register_module(module)?
    ///     .build()?;
    /// ```
    pub fn with_custom_routes(mut self, routes: Router) -> Self {
        self.custom_routes.push(routes);
        self
    }

    /// Enable the event bus for real-time notifications
    ///
    /// When enabled, REST/GraphQL handlers will publish events for mutations,
    /// and real-time exposures (WebSocket, SSE) can subscribe to receive them.
    ///
    /// # Arguments
    ///
    /// * `capacity` - Buffer size for the broadcast channel (recommended: 1024)
    ///
    /// # Example
    ///
    /// ```ignore
    /// ServerBuilder::new()
    ///     .with_link_service(service)
    ///     .with_event_bus(1024)
    ///     .register_module(module)?
    ///     .build_host()?;
    /// ```
    pub fn with_event_bus(mut self, capacity: usize) -> Self {
        self.event_bus = Some(EventBus::new(capacity));
        self
    }

    /// Provide a pre-built sink registry (overrides auto-wiring from config)
    ///
    /// Use this when you need full control over which sinks are registered.
    /// If not provided and `sinks` is present in config, sinks are auto-wired.
    pub fn with_sink_registry(mut self, registry: SinkRegistry) -> Self {
        self.sink_registry = Some(registry);
        self
    }

    /// Provide a pre-built notification store
    ///
    /// If not provided, one is auto-created when InApp sinks are configured.
    pub fn with_notification_store(mut self, store: Arc<NotificationStore>) -> Self {
        self.notification_store = Some(store);
        self
    }

    /// Provide a pre-built device token store
    ///
    /// If not provided, one is auto-created when sinks are configured.
    pub fn with_device_token_store(mut self, store: Arc<DeviceTokenStore>) -> Self {
        self.device_token_store = Some(store);
        self
    }

    /// Provide a pre-built notification preferences store
    ///
    /// If not provided, one is auto-created when sinks are configured.
    pub fn with_preferences_store(mut self, store: Arc<NotificationPreferencesStore>) -> Self {
        self.preferences_store = Some(store);
        self
    }

    /// Register a module
    ///
    /// This will:
    /// 1. Load the module's configuration
    /// 2. Register all entities from the module
    /// 3. Store the module for entity fetching
    pub fn register_module(mut self, module: impl Module + 'static) -> Result<Self> {
        let module = Arc::new(module);

        // Load the module's configuration
        let config = module.links_config()?;
        self.configs.push(config);

        // Register entities from the module
        module.register_entities(&mut self.entity_registry);

        // Store module for fetchers
        self.modules.push(module);

        Ok(self)
    }

    /// Build the transport-agnostic host
    ///
    /// This generates a `ServerHost` that can be used with any exposure type
    /// (REST, GraphQL, gRPC, etc.).
    ///
    /// # Returns
    ///
    /// Returns a `ServerHost` containing all framework state.
    pub fn build_host(mut self) -> Result<ServerHost> {
        // Merge all configs
        let merged_config = self.merge_configs()?;

        // Extract link service
        let link_service = self
            .link_service
            .take()
            .ok_or_else(|| anyhow::anyhow!("LinkService is required. Call .with_link_service()"))?;

        // Build entity fetchers map from all modules
        let mut fetchers_map: HashMap<String, Arc<dyn EntityFetcher>> = HashMap::new();
        for module in &self.modules {
            for entity_type in module.entity_types() {
                if let Some(fetcher) = module.get_entity_fetcher(entity_type) {
                    fetchers_map.insert(entity_type.to_string(), fetcher);
                }
            }
        }

        // Build entity creators map from all modules
        let mut creators_map: HashMap<String, Arc<dyn EntityCreator>> = HashMap::new();
        for module in &self.modules {
            for entity_type in module.entity_types() {
                if let Some(creator) = module.get_entity_creator(entity_type) {
                    creators_map.insert(entity_type.to_string(), creator);
                }
            }
        }

        // Build the host
        let mut host = ServerHost::from_builder_components(
            link_service,
            merged_config,
            self.entity_registry,
            fetchers_map,
            creators_map,
        )?;

        // Attach event bus if configured
        if let Some(event_bus) = self.event_bus.take() {
            host = host.with_event_bus(event_bus);
        }

        // Auto-wire event pipeline from config (sinks section)
        let has_sinks = host.config.sinks.as_ref().is_some_and(|s| !s.is_empty());

        if has_sinks || self.sink_registry.is_some() {
            // Build or use provided stores
            let notification_store = self
                .notification_store
                .take()
                .unwrap_or_else(|| Arc::new(NotificationStore::new()));
            let preferences_store = self
                .preferences_store
                .take()
                .unwrap_or_else(|| Arc::new(NotificationPreferencesStore::new()));
            let device_token_store = self
                .device_token_store
                .take()
                .unwrap_or_else(|| Arc::new(DeviceTokenStore::new()));

            // Build or use provided sink registry
            let sink_registry = if let Some(registry) = self.sink_registry.take() {
                registry
            } else if let Some(ref sink_configs) = host.config.sinks {
                let factory = SinkFactory::with_stores(
                    notification_store.clone(),
                    preferences_store.clone(),
                    device_token_store.clone(),
                );
                factory.build_registry(sink_configs)
            } else {
                SinkRegistry::new()
            };

            // Attach everything to the host
            host = host
                .with_notification_store(notification_store)
                .with_preferences_store(preferences_store)
                .with_device_token_store(device_token_store)
                .with_sink_registry(sink_registry);

            tracing::info!("event pipeline auto-wired from config");
        }

        // Auto-wire event log if events section is present
        if host.config.events.is_some() {
            let event_log = Arc::new(crate::events::InMemoryEventLog::new());
            host = host.with_event_log(event_log);
            tracing::info!("event log auto-wired (InMemoryEventLog)");
        }

        Ok(host)
    }

    /// Build the final REST router
    ///
    /// This generates:
    /// - CRUD routes for all registered entities
    /// - Link routes (bidirectional)
    /// - Introspection routes
    ///
    /// Note: This is a convenience method that builds the host and immediately
    /// exposes it via REST. For other exposure types, use `build_host_arc()`.
    pub fn build(mut self) -> Result<Router> {
        let custom_routes = std::mem::take(&mut self.custom_routes);
        let host = Arc::new(self.build_host()?);
        RestExposure::build_router(host, custom_routes)
    }

    /// Merge all configurations from registered modules
    fn merge_configs(&self) -> Result<LinksConfig> {
        Ok(LinksConfig::merge(self.configs.clone()))
    }

    /// Build a combined REST + gRPC router
    ///
    /// This is a convenience method that builds both REST and gRPC routers
    /// from the registered modules and merges them safely into a single router.
    ///
    /// Internally, it uses [`GrpcExposure::build_router_no_fallback`](super::GrpcExposure::build_router_no_fallback) for the
    /// gRPC side (no fallback) and [`RestExposure::build_router`] for REST
    /// (with its nested link path fallback), then merges them via
    /// [`combine_rest_and_grpc`](super::router::combine_rest_and_grpc).
    ///
    /// # Example
    ///
    /// ```ignore
    /// let app = ServerBuilder::new()
    ///     .with_link_service(InMemoryLinkService::new())
    ///     .register_module(MyModule)?
    ///     .build_with_grpc()?;
    ///
    /// let listener = TcpListener::bind("127.0.0.1:3000").await?;
    /// axum::serve(listener, app).await?;
    /// ```
    #[cfg(feature = "grpc")]
    pub fn build_with_grpc(mut self) -> Result<Router> {
        use super::exposure::grpc::GrpcExposure;
        use super::router::combine_rest_and_grpc;

        let custom_routes = std::mem::take(&mut self.custom_routes);
        let host = Arc::new(self.build_host()?);

        let rest_router = RestExposure::build_router(host.clone(), custom_routes)?;
        let grpc_router = GrpcExposure::build_router_no_fallback(host)?;

        Ok(combine_rest_and_grpc(rest_router, grpc_router))
    }

    /// Serve the application with graceful shutdown
    ///
    /// This will:
    /// - Bind to the provided address
    /// - Start serving requests
    /// - Handle SIGTERM and SIGINT (Ctrl+C) for graceful shutdown
    ///
    /// # Example
    ///
    /// ```ignore
    /// ServerBuilder::new()
    ///     .with_link_service(service)
    ///     .register_module(module)?
    ///     .serve("127.0.0.1:3000").await?;
    /// ```
    pub async fn serve(self, addr: &str) -> Result<()> {
        let app = self.build()?;
        let listener = TcpListener::bind(addr).await?;

        tracing::info!("Server listening on {}", addr);

        axum::serve(listener, app)
            .with_graceful_shutdown(shutdown_signal())
            .await?;

        tracing::info!("Server shutdown complete");
        Ok(())
    }

    /// Serve the application with REST + gRPC and graceful shutdown
    ///
    /// This is the gRPC equivalent of [`serve`](Self::serve). It builds a combined
    /// REST+gRPC router and serves it on the given address.
    ///
    /// # Example
    ///
    /// ```ignore
    /// ServerBuilder::new()
    ///     .with_link_service(service)
    ///     .register_module(module)?
    ///     .serve_with_grpc("127.0.0.1:3000").await?;
    /// ```
    #[cfg(feature = "grpc")]
    pub async fn serve_with_grpc(self, addr: &str) -> Result<()> {
        let app = self.build_with_grpc()?;
        let listener = TcpListener::bind(addr).await?;

        tracing::info!("Server listening on {} (REST + gRPC)", addr);

        axum::serve(listener, app)
            .with_graceful_shutdown(shutdown_signal())
            .await?;

        tracing::info!("Server shutdown complete");
        Ok(())
    }
}

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

/// Wait for shutdown signal (SIGTERM or Ctrl+C)
async fn shutdown_signal() {
    use tokio::signal;

    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("failed to install SIGTERM handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {
            tracing::info!("Received Ctrl+C signal, initiating graceful shutdown...");
        },
        _ = terminate => {
            tracing::info!("Received SIGTERM signal, initiating graceful shutdown...");
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{EntityAuthConfig, EntityConfig, LinksConfig};
    use crate::core::LinkDefinition;
    use crate::core::module::Module;
    use crate::server::entity_registry::EntityRegistry;
    use crate::storage::InMemoryLinkService;
    use std::sync::Arc;

    // ── Mock Module for testing ──────────────────────────────────────────

    /// A minimal Module implementation for builder tests
    struct StubModule {
        name: &'static str,
        entity_types: Vec<&'static str>,
        config: LinksConfig,
    }

    impl StubModule {
        fn single_entity() -> Self {
            Self {
                name: "stub",
                entity_types: vec!["order"],
                config: LinksConfig {
                    entities: vec![EntityConfig {
                        singular: "order".to_string(),
                        plural: "orders".to_string(),
                        auth: EntityAuthConfig::default(),
                    }],
                    links: vec![],
                    validation_rules: None,
                    events: None,
                    sinks: None,
                },
            }
        }

        fn with_link() -> Self {
            Self {
                name: "linked_stub",
                entity_types: vec!["user", "car"],
                config: LinksConfig {
                    entities: vec![
                        EntityConfig {
                            singular: "user".to_string(),
                            plural: "users".to_string(),
                            auth: EntityAuthConfig::default(),
                        },
                        EntityConfig {
                            singular: "car".to_string(),
                            plural: "cars".to_string(),
                            auth: EntityAuthConfig::default(),
                        },
                    ],
                    links: vec![LinkDefinition {
                        link_type: "owner".to_string(),
                        source_type: "user".to_string(),
                        target_type: "car".to_string(),
                        forward_route_name: "cars-owned".to_string(),
                        reverse_route_name: "users-owners".to_string(),
                        description: Some("User owns a car".to_string()),
                        required_fields: None,
                        auth: None,
                    }],
                    validation_rules: None,
                    events: None,
                    sinks: None,
                },
            }
        }
    }

    impl Module for StubModule {
        fn name(&self) -> &str {
            self.name
        }

        fn entity_types(&self) -> Vec<&str> {
            self.entity_types.clone()
        }

        fn links_config(&self) -> anyhow::Result<LinksConfig> {
            Ok(self.config.clone())
        }

        fn register_entities(&self, _registry: &mut EntityRegistry) {
            // No entity descriptors in stub
        }

        fn get_entity_fetcher(
            &self,
            _entity_type: &str,
        ) -> Option<Arc<dyn crate::core::EntityFetcher>> {
            None
        }

        fn get_entity_creator(
            &self,
            _entity_type: &str,
        ) -> Option<Arc<dyn crate::core::EntityCreator>> {
            None
        }
    }

    /// A module whose links_config() returns an error
    struct FailingModule;

    impl Module for FailingModule {
        fn name(&self) -> &str {
            "failing"
        }

        fn entity_types(&self) -> Vec<&str> {
            vec![]
        }

        fn links_config(&self) -> anyhow::Result<LinksConfig> {
            Err(anyhow::anyhow!("config load failed"))
        }

        fn register_entities(&self, _registry: &mut EntityRegistry) {}

        fn get_entity_fetcher(
            &self,
            _entity_type: &str,
        ) -> Option<Arc<dyn crate::core::EntityFetcher>> {
            None
        }

        fn get_entity_creator(
            &self,
            _entity_type: &str,
        ) -> Option<Arc<dyn crate::core::EntityCreator>> {
            None
        }
    }

    // ── Constructor tests ────────────────────────────────────────────────

    #[test]
    fn test_new_creates_empty_builder() {
        let builder = ServerBuilder::new();
        assert!(builder.link_service.is_none());
        assert!(builder.configs.is_empty());
        assert!(builder.modules.is_empty());
        assert!(builder.custom_routes.is_empty());
        assert!(builder.event_bus.is_none());
    }

    #[test]
    fn test_default_is_same_as_new() {
        let builder = ServerBuilder::default();
        assert!(builder.link_service.is_none());
        assert!(builder.configs.is_empty());
        assert!(builder.modules.is_empty());
        assert!(builder.custom_routes.is_empty());
        assert!(builder.event_bus.is_none());
    }

    // ── with_link_service ────────────────────────────────────────────────

    #[test]
    fn test_with_link_service_sets_service() {
        let builder = ServerBuilder::new().with_link_service(InMemoryLinkService::new());
        assert!(builder.link_service.is_some());
    }

    // ── with_event_bus ───────────────────────────────────────────────────

    #[test]
    fn test_with_event_bus_sets_bus() {
        let builder = ServerBuilder::new().with_event_bus(1024);
        assert!(builder.event_bus.is_some());
    }

    // ── with_custom_routes ───────────────────────────────────────────────

    #[test]
    fn test_with_custom_routes_appends_router() {
        let builder = ServerBuilder::new()
            .with_custom_routes(Router::new())
            .with_custom_routes(Router::new());
        assert_eq!(builder.custom_routes.len(), 2);
    }

    // ── register_module ──────────────────────────────────────────────────

    #[test]
    fn test_register_module_stores_config_and_module() {
        let builder = ServerBuilder::new()
            .register_module(StubModule::single_entity())
            .expect("register_module should succeed");
        assert_eq!(builder.configs.len(), 1);
        assert_eq!(builder.modules.len(), 1);
    }

    #[test]
    fn test_register_multiple_modules() {
        let builder = ServerBuilder::new()
            .register_module(StubModule::single_entity())
            .expect("first module should register")
            .register_module(StubModule::with_link())
            .expect("second module should register");
        assert_eq!(builder.configs.len(), 2);
        assert_eq!(builder.modules.len(), 2);
    }

    #[test]
    fn test_register_module_failing_config_returns_error() {
        let result = ServerBuilder::new().register_module(FailingModule);
        assert!(result.is_err());
        let err_msg = format!("{}", result.err().expect("should be Err"));
        assert!(
            err_msg.contains("config load failed"),
            "error should contain cause: {}",
            err_msg
        );
    }

    // ── build_host ───────────────────────────────────────────────────────

    #[test]
    fn test_build_host_without_link_service_fails() {
        let result = ServerBuilder::new()
            .register_module(StubModule::single_entity())
            .expect("register should succeed")
            .build_host();
        assert!(result.is_err());
        let err_msg = format!("{}", result.err().expect("should be Err"));
        assert!(
            err_msg.contains("LinkService is required"),
            "error should mention LinkService: {}",
            err_msg
        );
    }

    #[test]
    fn test_build_host_single_module() {
        let host = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .register_module(StubModule::single_entity())
            .expect("register should succeed")
            .build_host()
            .expect("build_host should succeed");

        assert_eq!(host.config.entities.len(), 1);
        assert_eq!(host.config.entities[0].singular, "order");
        assert!(host.event_bus.is_none());
    }

    #[test]
    fn test_build_host_multi_module_merges_configs() {
        let host = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .register_module(StubModule::single_entity())
            .expect("register first should succeed")
            .register_module(StubModule::with_link())
            .expect("register second should succeed")
            .build_host()
            .expect("build_host should succeed");

        // Merged config should contain entities from both modules
        let entity_names: Vec<&str> = host
            .config
            .entities
            .iter()
            .map(|e| e.singular.as_str())
            .collect();
        assert!(entity_names.contains(&"order"), "should contain order");
        assert!(entity_names.contains(&"user"), "should contain user");
        assert!(entity_names.contains(&"car"), "should contain car");
    }

    #[test]
    fn test_build_host_with_event_bus_attaches_bus() {
        let host = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .with_event_bus(16)
            .register_module(StubModule::single_entity())
            .expect("register should succeed")
            .build_host()
            .expect("build_host should succeed");

        assert!(host.event_bus().is_some());
    }

    #[test]
    fn test_build_host_no_modules_empty_config() {
        let host = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .build_host()
            .expect("build_host with no modules should succeed");

        assert!(host.config.entities.is_empty());
        assert!(host.config.links.is_empty());
    }

    // ── build (REST router) ──────────────────────────────────────────────

    #[test]
    fn test_build_produces_router() {
        let router = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .register_module(StubModule::single_entity())
            .expect("register should succeed")
            .build()
            .expect("build should produce a Router");

        // We cannot inspect the Router deeply, but it should not panic
        let _ = router;
    }

    #[test]
    fn test_build_without_link_service_fails() {
        let result = ServerBuilder::new()
            .register_module(StubModule::single_entity())
            .expect("register should succeed")
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn test_build_with_custom_routes() {
        use axum::routing::get;

        let custom = Router::new().route("/custom", get(|| async { "ok" }));
        let router = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .with_custom_routes(custom)
            .register_module(StubModule::single_entity())
            .expect("register should succeed")
            .build()
            .expect("build should succeed with custom routes");

        let _ = router;
    }

    // ── Fluent chaining ──────────────────────────────────────────────────

    #[test]
    fn test_fluent_chaining_full_pipeline() {
        let result = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .with_event_bus(256)
            .with_custom_routes(Router::new())
            .register_module(StubModule::with_link())
            .expect("register should succeed")
            .build();
        assert!(result.is_ok(), "full fluent pipeline should succeed");
    }

    // ── Auto-wiring tests ──────────────────────────────────────────────

    /// A module whose config includes sinks
    struct StubModuleWithSinks;

    impl Module for StubModuleWithSinks {
        fn name(&self) -> &str {
            "with_sinks"
        }

        fn entity_types(&self) -> Vec<&str> {
            vec!["user"]
        }

        fn links_config(&self) -> anyhow::Result<LinksConfig> {
            use crate::config::events::EventsConfig;
            use crate::config::sinks::{SinkConfig, SinkType};

            Ok(LinksConfig {
                entities: vec![EntityConfig {
                    singular: "user".to_string(),
                    plural: "users".to_string(),
                    auth: EntityAuthConfig::default(),
                }],
                links: vec![],
                validation_rules: None,
                events: Some(EventsConfig::default()),
                sinks: Some(vec![SinkConfig {
                    name: "in-app-notif".to_string(),
                    sink_type: SinkType::InApp,
                    config: Default::default(),
                }]),
            })
        }

        fn register_entities(&self, _registry: &mut EntityRegistry) {}

        fn get_entity_fetcher(
            &self,
            _entity_type: &str,
        ) -> Option<Arc<dyn crate::core::EntityFetcher>> {
            None
        }

        fn get_entity_creator(
            &self,
            _entity_type: &str,
        ) -> Option<Arc<dyn crate::core::EntityCreator>> {
            None
        }
    }

    #[test]
    fn test_auto_wire_sinks_from_config() {
        let host = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .with_event_bus(16)
            .register_module(StubModuleWithSinks)
            .expect("register should succeed")
            .build_host()
            .expect("build_host should succeed");

        // Auto-wired: InApp sink registered
        assert!(host.sink_registry().is_some());
        let registry = host.sink_registry().unwrap();
        assert!(registry.get("in-app-notif").is_some());
        assert_eq!(registry.len(), 1);

        // Auto-wired: stores created
        assert!(host.notification_store().is_some());
        assert!(host.device_token_store().is_some());
        assert!(host.preferences_store().is_some());

        // Auto-wired: event log created (events section present)
        assert!(host.event_log().is_some());
    }

    #[test]
    fn test_no_auto_wire_without_sinks_config() {
        let host = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .register_module(StubModule::single_entity())
            .expect("register should succeed")
            .build_host()
            .expect("build_host should succeed");

        // No sinks in config → no auto-wiring
        assert!(host.sink_registry().is_none());
        assert!(host.notification_store().is_none());
        assert!(host.device_token_store().is_none());
        assert!(host.preferences_store().is_none());
        assert!(host.event_log().is_none());
    }

    #[test]
    fn test_manual_sink_registry_overrides_auto_wire() {
        let manual_registry = SinkRegistry::new();

        let host = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .with_sink_registry(manual_registry)
            .register_module(StubModuleWithSinks)
            .expect("register should succeed")
            .build_host()
            .expect("build_host should succeed");

        // Manual registry used instead of auto-wired → empty, no InApp
        let registry = host.sink_registry().unwrap();
        assert!(registry.is_empty());
        // InApp from config NOT auto-created because we provided a manual registry
        assert!(registry.get("in-app-notif").is_none());
    }

    #[test]
    fn test_manual_stores_used_in_auto_wire() {
        let custom_store = Arc::new(crate::events::sinks::in_app::NotificationStore::new());
        let store_clone = custom_store.clone();

        let host = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .with_notification_store(custom_store)
            .register_module(StubModuleWithSinks)
            .expect("register should succeed")
            .build_host()
            .expect("build_host should succeed");

        // The custom store should be the one on the host
        assert!(Arc::ptr_eq(
            host.notification_store().unwrap(),
            &store_clone
        ));
    }

    #[test]
    fn test_retro_compatible_no_sinks_no_events() {
        // Exact same test as before — nothing changes
        let host = ServerBuilder::new()
            .with_link_service(InMemoryLinkService::new())
            .with_event_bus(16)
            .register_module(StubModule::single_entity())
            .expect("register should succeed")
            .build_host()
            .expect("build_host should succeed");

        assert!(host.event_bus().is_some());
        assert!(host.sink_registry().is_none());
        assert!(host.event_log().is_none());
        assert_eq!(host.config.entities.len(), 1);
    }
}