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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
//! GraphQL schema generation
//!
//! This module generates the GraphQL schema from the ServerHost configuration.
//! It automatically exposes all entities defined by the client in their modules.
//!
//! The schema uses a dynamic approach where entity types are exposed with their
//! actual names (order, invoice, payment) rather than a generic "entity" type.

#[cfg(feature = "graphql")]
use async_graphql::*;
#[cfg(feature = "graphql")]
use serde_json::Value;
#[cfg(feature = "graphql")]
use std::sync::Arc;
#[cfg(feature = "graphql")]
use uuid::Uuid;

#[cfg(feature = "graphql")]
/// Generic entity type for GraphQL (dynamically exposed)
///
/// This type represents any entity in the system and includes
/// methods to access related entities through links.
#[allow(dead_code)]
pub struct Entity {
    /// Entity ID
    pub id: String,

    /// Entity type
    pub entity_type: String,

    /// Entity name
    pub name: String,

    /// Created timestamp
    pub created_at: String,

    /// Updated timestamp
    pub updated_at: String,

    /// Deleted timestamp (if soft deleted)
    pub deleted_at: Option<String>,

    /// Entity status
    pub status: String,

    /// All entity data as JSON (includes custom fields)
    pub data: Value,

    /// Host reference for resolving relations (not exposed in GraphQL)
    pub host: Option<Arc<crate::server::host::ServerHost>>,
}

#[cfg(feature = "graphql")]
#[Object]
impl Entity {
    /// Entity ID
    async fn id(&self) -> &str {
        &self.id
    }

    /// Entity type
    #[graphql(name = "type")]
    async fn entity_type(&self) -> &str {
        &self.entity_type
    }

    /// Entity name
    async fn name(&self) -> &str {
        &self.name
    }

    /// Created timestamp
    #[graphql(name = "createdAt")]
    async fn created_at(&self) -> &str {
        &self.created_at
    }

    /// Updated timestamp
    #[graphql(name = "updatedAt")]
    async fn updated_at(&self) -> &str {
        &self.updated_at
    }

    /// Deleted timestamp (if soft deleted)
    #[graphql(name = "deletedAt")]
    async fn deleted_at(&self) -> Option<&str> {
        self.deleted_at.as_deref()
    }

    /// Entity status
    async fn status(&self) -> &str {
        &self.status
    }

    /// All entity data as JSON (includes custom fields)
    async fn data(&self) -> &Value {
        &self.data
    }

    /// Get linked invoices (for orders)
    async fn invoices(&self) -> Result<Vec<Entity>> {
        self.get_linked_entities("invoices", "invoice").await
    }

    /// Get linked payments (for invoices)
    async fn payments(&self) -> Result<Vec<Entity>> {
        self.get_linked_entities("payments", "payment").await
    }

    /// Get linked order (for invoices)
    async fn order(&self) -> Result<Option<Entity>> {
        let links = self.get_linked_entities("order", "order").await?;
        Ok(links.into_iter().next())
    }

    /// Get linked invoice (for payments)
    async fn invoice(&self) -> Result<Option<Entity>> {
        let links = self.get_linked_entities("invoice", "invoice").await?;
        Ok(links.into_iter().next())
    }

    /// Generic method to get all links of a specific type
    async fn links(&self, link_type: Option<String>) -> Result<Vec<Link>> {
        if let Some(host) = &self.host {
            let uuid = Uuid::parse_str(&self.id)
                .map_err(|e| Error::new(format!("Invalid UUID: {}", e)))?;

            let link_type_str = link_type.as_deref();

            match host
                .link_service
                .find_by_source(&uuid, link_type_str, None)
                .await
            {
                Ok(links) => Ok(links
                    .into_iter()
                    .map(|link_entity| Link {
                        id: link_entity.id.to_string(),
                        source_id: link_entity.source_id.to_string(),
                        target_id: link_entity.target_id.to_string(),
                        link_type: link_entity.link_type.clone(),
                        metadata: link_entity
                            .metadata
                            .clone()
                            .unwrap_or(serde_json::json!({})),
                        created_at: link_entity.created_at.to_rfc3339(),
                        target: None,
                        source: None,
                    })
                    .collect()),
                Err(_) => Ok(vec![]),
            }
        } else {
            Ok(vec![])
        }
    }
}

#[cfg(feature = "graphql")]
impl Entity {
    /// Helper method to get linked entities
    #[allow(dead_code)]
    async fn get_linked_entities(&self, link_type: &str, target_type: &str) -> Result<Vec<Entity>> {
        if let Some(host) = &self.host {
            let uuid = Uuid::parse_str(&self.id)
                .map_err(|e| Error::new(format!("Invalid UUID: {}", e)))?;

            match host
                .link_service
                .find_by_source(&uuid, Some(link_type), Some(target_type))
                .await
            {
                Ok(links) => {
                    let mut entities = Vec::new();

                    if let Some(fetcher) = host.entity_fetchers.get(target_type) {
                        for link in links {
                            if let Ok(value) = fetcher.fetch_as_json(&link.target_id).await {
                                entities.push(Entity {
                                    id: value["id"].as_str().unwrap_or("").to_string(),
                                    entity_type: value["type"].as_str().unwrap_or("").to_string(),
                                    name: value["name"].as_str().unwrap_or("").to_string(),
                                    created_at: value["created_at"]
                                        .as_str()
                                        .unwrap_or("")
                                        .to_string(),
                                    updated_at: value["updated_at"]
                                        .as_str()
                                        .unwrap_or("")
                                        .to_string(),
                                    deleted_at: value["deleted_at"].as_str().map(String::from),
                                    status: value["status"].as_str().unwrap_or("").to_string(),
                                    data: value,
                                    host: Some(host.clone()),
                                });
                            }
                        }
                    }

                    Ok(entities)
                }
                Err(_) => Ok(vec![]),
            }
        } else {
            Ok(vec![])
        }
    }
}

#[cfg(feature = "graphql")]
/// Link between entities
#[derive(SimpleObject)]
#[allow(dead_code)]
pub struct Link {
    /// Link ID
    pub id: String,

    /// Source entity ID
    #[graphql(name = "sourceId")]
    pub source_id: String,

    /// Target entity ID
    #[graphql(name = "targetId")]
    pub target_id: String,

    /// Link type
    #[graphql(name = "linkType")]
    pub link_type: String,

    /// Link metadata
    pub metadata: Value,

    /// Created timestamp
    #[graphql(name = "createdAt")]
    pub created_at: String,

    /// Target entity (enriched)
    pub target: Option<Entity>,

    /// Source entity (enriched)
    pub source: Option<Entity>,
}

#[cfg(feature = "graphql")]
#[allow(dead_code)]
pub struct QueryRoot {
    pub(super) host: Arc<crate::server::host::ServerHost>,
}

#[cfg(feature = "graphql")]
#[Object]
impl QueryRoot {
    /// Get entity by ID and type
    ///
    /// Returns the entity with all its custom fields in the `data` field
    async fn entity(&self, id: String, entity_type: String) -> Result<Option<Entity>> {
        if let Some(fetcher) = self.host.entity_fetchers.get(&entity_type) {
            let uuid =
                Uuid::parse_str(&id).map_err(|e| Error::new(format!("Invalid UUID: {}", e)))?;

            match fetcher.fetch_as_json(&uuid).await {
                Ok(value) => Ok(Some(Entity {
                    id: value["id"].as_str().unwrap_or("").to_string(),
                    entity_type: value["type"].as_str().unwrap_or("").to_string(),
                    name: value["name"].as_str().unwrap_or("").to_string(),
                    created_at: value["created_at"].as_str().unwrap_or("").to_string(),
                    updated_at: value["updated_at"].as_str().unwrap_or("").to_string(),
                    deleted_at: value["deleted_at"].as_str().map(String::from),
                    status: value["status"].as_str().unwrap_or("").to_string(),
                    data: value,
                    host: Some(self.host.clone()),
                })),
                Err(_) => Ok(None),
            }
        } else {
            Ok(None)
        }
    }

    /// List all entity types registered in the system
    async fn entity_types(&self) -> Vec<String> {
        self.host
            .entity_types()
            .iter()
            .map(|s| s.to_string())
            .collect()
    }

    /// Get an order by ID
    #[graphql(name = "order")]
    async fn get_order(&self, id: String) -> Result<Option<Entity>> {
        self.get_entity_by_type(id, "order".to_string()).await
    }

    /// Get an invoice by ID
    #[graphql(name = "invoice")]
    async fn get_invoice(&self, id: String) -> Result<Option<Entity>> {
        self.get_entity_by_type(id, "invoice".to_string()).await
    }

    /// Get a payment by ID
    #[graphql(name = "payment")]
    async fn get_payment(&self, id: String) -> Result<Option<Entity>> {
        self.get_entity_by_type(id, "payment".to_string()).await
    }

    /// List all orders
    #[graphql(name = "orders")]
    async fn list_orders(&self) -> Result<Vec<Entity>> {
        self.list_entities("order").await
    }

    /// List all invoices
    #[graphql(name = "invoices")]
    async fn list_invoices(&self) -> Result<Vec<Entity>> {
        self.list_entities("invoice").await
    }

    /// List all payments
    #[graphql(name = "payments")]
    async fn list_payments(&self) -> Result<Vec<Entity>> {
        self.list_entities("payment").await
    }

    /// Get link by ID
    async fn link(&self, id: String) -> Result<Option<Link>> {
        let uuid = Uuid::parse_str(&id).map_err(|e| Error::new(format!("Invalid UUID: {}", e)))?;

        match self.host.link_service.get(&uuid).await {
            Ok(Some(link_entity)) => Ok(Some(Link {
                id: link_entity.id.to_string(),
                source_id: link_entity.source_id.to_string(),
                target_id: link_entity.target_id.to_string(),
                link_type: link_entity.link_type.clone(),
                metadata: link_entity
                    .metadata
                    .clone()
                    .unwrap_or(serde_json::json!({})),
                created_at: link_entity.created_at.to_rfc3339(),
                target: None,
                source: None,
            })),
            _ => Ok(None),
        }
    }

    /// Get links for an entity
    async fn entity_links(
        &self,
        entity_id: String,
        link_type: Option<String>,
        target_type: Option<String>,
    ) -> Result<Vec<Link>> {
        let uuid =
            Uuid::parse_str(&entity_id).map_err(|e| Error::new(format!("Invalid UUID: {}", e)))?;

        let link_type_str = link_type.as_deref();
        let target_type_str = target_type.as_deref();

        match self
            .host
            .link_service
            .find_by_source(&uuid, link_type_str, target_type_str)
            .await
        {
            Ok(links) => Ok(links
                .into_iter()
                .map(|link_entity| Link {
                    id: link_entity.id.to_string(),
                    source_id: link_entity.source_id.to_string(),
                    target_id: link_entity.target_id.to_string(),
                    link_type: link_entity.link_type.clone(),
                    metadata: link_entity
                        .metadata
                        .clone()
                        .unwrap_or(serde_json::json!({})),
                    created_at: link_entity.created_at.to_rfc3339(),
                    target: None,
                    source: None,
                })
                .collect()),
            _ => Ok(vec![]),
        }
    }
}

#[cfg(feature = "graphql")]
impl QueryRoot {
    /// Helper to get entity by type
    #[allow(dead_code)]
    async fn get_entity_by_type(&self, id: String, entity_type: String) -> Result<Option<Entity>> {
        if let Some(fetcher) = self.host.entity_fetchers.get(&entity_type) {
            let uuid =
                Uuid::parse_str(&id).map_err(|e| Error::new(format!("Invalid UUID: {}", e)))?;

            match fetcher.fetch_as_json(&uuid).await {
                Ok(value) => Ok(Some(Entity {
                    id: value["id"].as_str().unwrap_or("").to_string(),
                    entity_type: value["type"].as_str().unwrap_or("").to_string(),
                    name: value["name"].as_str().unwrap_or("").to_string(),
                    created_at: value["created_at"].as_str().unwrap_or("").to_string(),
                    updated_at: value["updated_at"].as_str().unwrap_or("").to_string(),
                    deleted_at: value["deleted_at"].as_str().map(String::from),
                    status: value["status"].as_str().unwrap_or("").to_string(),
                    data: value,
                    host: Some(self.host.clone()),
                })),
                Err(_) => Ok(None),
            }
        } else {
            Ok(None)
        }
    }

    /// Helper to list entities of a given type
    async fn list_entities(&self, _entity_type: &str) -> Result<Vec<Entity>> {
        // For now, return empty vec as we need pagination support
        // This will be implemented when we add proper list support to EntityFetcher
        Ok(vec![])
    }
}

#[cfg(feature = "graphql")]
#[allow(dead_code)]
pub struct MutationRoot {
    pub(super) host: Arc<crate::server::host::ServerHost>,
}

#[cfg(feature = "graphql")]
#[Object]
impl MutationRoot {
    /// Create a link between entities
    #[allow(dead_code)]
    async fn create_link(
        &self,
        source_id: String,
        target_id: String,
        link_type: String,
        metadata: Option<Value>,
    ) -> Result<Link> {
        let source_uuid = Uuid::parse_str(&source_id)
            .map_err(|e| Error::new(format!("Invalid source UUID: {}", e)))?;
        let target_uuid = Uuid::parse_str(&target_id)
            .map_err(|e| Error::new(format!("Invalid target UUID: {}", e)))?;

        use crate::core::link::LinkEntity as CoreLinkEntity;

        let link_entity = CoreLinkEntity::new(
            link_type,
            source_uuid,
            target_uuid,
            Some(metadata.unwrap_or(serde_json::json!({}))),
        );

        match self.host.link_service.create(link_entity).await {
            Ok(created) => Ok(Link {
                id: created.id.to_string(),
                source_id: created.source_id.to_string(),
                target_id: created.target_id.to_string(),
                link_type: created.link_type.clone(),
                metadata: created.metadata.clone().unwrap_or(serde_json::json!({})),
                created_at: created.created_at.to_rfc3339(),
                target: None,
                source: None,
            }),
            Err(e) => Err(Error::new(format!("Failed to create link: {}", e))),
        }
    }

    /// Delete a link
    #[allow(dead_code)]
    async fn delete_link(&self, id: String) -> Result<bool> {
        let uuid = Uuid::parse_str(&id).map_err(|e| Error::new(format!("Invalid UUID: {}", e)))?;

        match self.host.link_service.delete(&uuid).await {
            Ok(_) => Ok(true),
            Err(_) => Ok(false),
        }
    }
}

#[cfg(feature = "graphql")]
#[allow(dead_code)]
pub type SubscriptionRoot = EmptySubscription;

#[cfg(feature = "graphql")]
/// Build the GraphQL schema from the host
#[allow(dead_code)]
pub fn build_schema(
    host: Arc<crate::server::host::ServerHost>,
) -> Schema<QueryRoot, MutationRoot, EmptySubscription> {
    let query = QueryRoot { host: host.clone() };
    let mutation = MutationRoot { host: host.clone() };

    Schema::build(query, mutation, EmptySubscription).finish()
}

#[cfg(test)]
#[cfg(feature = "graphql")]
mod tests {
    use super::*;
    use crate::config::{EntityAuthConfig, EntityConfig, LinksConfig};
    use crate::core::EntityFetcher;
    use crate::core::link::LinkDefinition;
    use crate::server::entity_registry::{EntityDescriptor, EntityRegistry};
    use crate::server::host::ServerHost;
    use crate::storage::in_memory::InMemoryLinkService;
    use async_trait::async_trait;
    use axum::Router;
    use serde_json::{Value as JsonVal, json};
    use std::collections::HashMap;

    // -----------------------------------------------------------------------
    // Mock infrastructure
    // -----------------------------------------------------------------------

    struct MockFetcher {
        entities: std::sync::Mutex<HashMap<Uuid, JsonVal>>,
    }

    impl MockFetcher {
        fn new() -> Self {
            Self {
                entities: std::sync::Mutex::new(HashMap::new()),
            }
        }

        fn with_entity(self, id: Uuid, entity: JsonVal) -> Self {
            self.entities
                .lock()
                .expect("lock poisoned")
                .insert(id, entity);
            self
        }
    }

    #[async_trait]
    impl EntityFetcher for MockFetcher {
        async fn fetch_as_json(&self, entity_id: &Uuid) -> anyhow::Result<JsonVal> {
            let entities = self.entities.lock().expect("lock poisoned");
            entities
                .get(entity_id)
                .cloned()
                .ok_or_else(|| anyhow::anyhow!("Entity not found: {}", entity_id))
        }
    }

    struct StubDescriptor {
        entity_type: String,
        plural: String,
    }

    impl StubDescriptor {
        fn new(singular: &str, plural: &str) -> Self {
            Self {
                entity_type: singular.to_string(),
                plural: plural.to_string(),
            }
        }
    }

    impl EntityDescriptor for StubDescriptor {
        fn entity_type(&self) -> &str {
            &self.entity_type
        }
        fn plural(&self) -> &str {
            &self.plural
        }
        fn build_routes(&self) -> Router {
            Router::new()
        }
    }

    fn build_test_host(fetchers: HashMap<String, Arc<dyn EntityFetcher>>) -> Arc<ServerHost> {
        let link_service = Arc::new(InMemoryLinkService::new());
        let config = LinksConfig {
            entities: vec![
                EntityConfig {
                    singular: "order".to_string(),
                    plural: "orders".to_string(),
                    auth: EntityAuthConfig::default(),
                },
                EntityConfig {
                    singular: "invoice".to_string(),
                    plural: "invoices".to_string(),
                    auth: EntityAuthConfig::default(),
                },
            ],
            links: vec![LinkDefinition {
                link_type: "has_invoice".to_string(),
                source_type: "order".to_string(),
                target_type: "invoice".to_string(),
                forward_route_name: "invoices".to_string(),
                reverse_route_name: "order".to_string(),
                description: None,
                required_fields: None,
                auth: None,
            }],
            validation_rules: None,
            events: None,
            sinks: None,
        };

        let mut registry = EntityRegistry::new();
        registry.register(Box::new(StubDescriptor::new("order", "orders")));
        registry.register(Box::new(StubDescriptor::new("invoice", "invoices")));

        Arc::new(
            ServerHost::from_builder_components(
                link_service,
                config,
                registry,
                fetchers,
                HashMap::new(),
            )
            .expect("should build test host"),
        )
    }

    fn build_host_with_fetcher(
        entity_type: &str,
        fetcher: Arc<dyn EntityFetcher>,
    ) -> Arc<ServerHost> {
        let mut fetchers: HashMap<String, Arc<dyn EntityFetcher>> = HashMap::new();
        fetchers.insert(entity_type.to_string(), fetcher);
        build_test_host(fetchers)
    }

    // -----------------------------------------------------------------------
    // build_schema smoke test
    // -----------------------------------------------------------------------

    #[test]
    fn test_build_schema_does_not_panic() {
        let host = build_test_host(HashMap::new());
        let _schema = build_schema(host);
    }

    // -----------------------------------------------------------------------
    // Entity struct fields (direct access, not #[Object] resolvers)
    // -----------------------------------------------------------------------

    #[test]
    fn test_entity_struct_fields() {
        let entity = Entity {
            id: "abc-123".to_string(),
            entity_type: "order".to_string(),
            name: "Test Order".to_string(),
            created_at: "2024-01-01T00:00:00Z".to_string(),
            updated_at: "2024-01-02T00:00:00Z".to_string(),
            deleted_at: Some("2024-01-03T00:00:00Z".to_string()),
            status: "active".to_string(),
            data: json!({"custom": "field"}),
            host: None,
        };

        assert_eq!(entity.id, "abc-123");
        assert_eq!(entity.entity_type, "order");
        assert_eq!(entity.name, "Test Order");
        assert_eq!(entity.created_at, "2024-01-01T00:00:00Z");
        assert_eq!(entity.updated_at, "2024-01-02T00:00:00Z");
        assert_eq!(entity.deleted_at.as_deref(), Some("2024-01-03T00:00:00Z"));
        assert_eq!(entity.status, "active");
        assert_eq!(entity.data, json!({"custom": "field"}));
    }

    #[test]
    fn test_entity_deleted_at_none() {
        let entity = Entity {
            id: "x".to_string(),
            entity_type: "order".to_string(),
            name: "".to_string(),
            created_at: "".to_string(),
            updated_at: "".to_string(),
            deleted_at: None,
            status: "".to_string(),
            data: json!(null),
            host: None,
        };

        assert!(entity.deleted_at.is_none());
    }

    // -----------------------------------------------------------------------
    // Entity: get_linked_entities without host returns empty
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_get_linked_entities_no_host_returns_empty() {
        let entity = Entity {
            id: Uuid::new_v4().to_string(),
            entity_type: "order".to_string(),
            name: "".to_string(),
            created_at: "".to_string(),
            updated_at: "".to_string(),
            deleted_at: None,
            status: "".to_string(),
            data: json!({}),
            host: None,
        };

        let result = entity
            .get_linked_entities("invoices", "invoice")
            .await
            .expect("should not error");
        assert!(result.is_empty(), "no host means no linked entities");
    }

    // -----------------------------------------------------------------------
    // Entity: get_linked_entities with host but no links
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_get_linked_entities_host_empty_store() {
        let entity_id = Uuid::new_v4();
        let host = build_test_host(HashMap::new());

        let entity = Entity {
            id: entity_id.to_string(),
            entity_type: "order".to_string(),
            name: "".to_string(),
            created_at: "".to_string(),
            updated_at: "".to_string(),
            deleted_at: None,
            status: "".to_string(),
            data: json!({}),
            host: Some(host),
        };

        let result = entity
            .get_linked_entities("invoices", "invoice")
            .await
            .expect("should not error");
        assert!(result.is_empty(), "empty store means no linked entities");
    }

    // -----------------------------------------------------------------------
    // Entity: get_linked_entities with invalid UUID returns error
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_get_linked_entities_invalid_uuid() {
        let host = build_test_host(HashMap::new());

        let entity = Entity {
            id: "not-a-uuid".to_string(),
            entity_type: "order".to_string(),
            name: "".to_string(),
            created_at: "".to_string(),
            updated_at: "".to_string(),
            deleted_at: None,
            status: "".to_string(),
            data: json!({}),
            host: Some(host),
        };

        let result = entity.get_linked_entities("invoices", "invoice").await;
        assert!(result.is_err(), "invalid UUID should produce an error");
    }

    // -----------------------------------------------------------------------
    // Entity: get_linked_entities with fetcher resolves targets
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_get_linked_entities_resolves_targets() {
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();

        let invoice_json = json!({
            "id": target_id.to_string(),
            "type": "invoice",
            "name": "Invoice #1",
            "created_at": "2024-01-01",
            "updated_at": "2024-01-02",
            "deleted_at": null,
            "status": "paid"
        });

        let host = build_host_with_fetcher(
            "invoice",
            Arc::new(MockFetcher::new().with_entity(target_id, invoice_json)),
        );

        // Create a link in the store
        let link_entity =
            crate::core::link::LinkEntity::new("has_invoice", source_id, target_id, None);
        host.link_service
            .create(link_entity)
            .await
            .expect("should create link");

        let entity = Entity {
            id: source_id.to_string(),
            entity_type: "order".to_string(),
            name: "".to_string(),
            created_at: "".to_string(),
            updated_at: "".to_string(),
            deleted_at: None,
            status: "".to_string(),
            data: json!({}),
            host: Some(host),
        };

        let result = entity
            .get_linked_entities("has_invoice", "invoice")
            .await
            .expect("should not error");
        assert_eq!(result.len(), 1, "should resolve one linked entity");
        assert_eq!(result[0].name, "Invoice #1");
        assert_eq!(result[0].status, "paid");
    }

    // -----------------------------------------------------------------------
    // Link struct fields
    // -----------------------------------------------------------------------

    #[test]
    fn test_link_struct_fields() {
        let link = Link {
            id: "link-1".to_string(),
            source_id: "src-1".to_string(),
            target_id: "tgt-1".to_string(),
            link_type: "has_invoice".to_string(),
            metadata: json!({"key": "val"}),
            created_at: "2024-01-01".to_string(),
            target: None,
            source: None,
        };

        assert_eq!(link.id, "link-1");
        assert_eq!(link.source_id, "src-1");
        assert_eq!(link.target_id, "tgt-1");
        assert_eq!(link.link_type, "has_invoice");
        assert!(link.target.is_none());
        assert!(link.source.is_none());
    }

    // -----------------------------------------------------------------------
    // Schema: entity_types query via schema execution
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_query_root_entity_types() {
        let host = build_test_host(HashMap::new());
        let schema = build_schema(host);

        let result = schema.execute("{ entityTypes }").await;

        assert!(
            result.errors.is_empty(),
            "should have no errors: {:?}",
            result.errors
        );
        let data = result.data.into_json().expect("should serialize");
        let types = data["entityTypes"].as_array().expect("should be array");
        let type_strs: Vec<&str> = types.iter().map(|v| v.as_str().expect("string")).collect();
        assert!(type_strs.contains(&"order"), "should have order");
        assert!(type_strs.contains(&"invoice"), "should have invoice");
    }

    // -----------------------------------------------------------------------
    // Schema: entity query with fetcher
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_query_root_entity_found() {
        let order_id = Uuid::new_v4();
        let order_json = json!({
            "id": order_id.to_string(),
            "type": "order",
            "name": "Order #1",
            "created_at": "2024-01-01",
            "updated_at": "2024-01-02",
            "deleted_at": null,
            "status": "active"
        });

        let host = build_host_with_fetcher(
            "order",
            Arc::new(MockFetcher::new().with_entity(order_id, order_json)),
        );
        let schema = build_schema(host);

        let query = format!(
            r#"{{ entity(id: "{}", entityType: "order") {{ id name status }} }}"#,
            order_id
        );
        let result = schema.execute(&query).await;
        assert!(result.errors.is_empty(), "errors: {:?}", result.errors);
        let data = result.data.into_json().expect("json");
        let entity = &data["entity"];
        assert_eq!(entity["name"], "Order #1");
        assert_eq!(entity["status"], "active");
    }

    // -----------------------------------------------------------------------
    // Schema: entity query unknown type returns null
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_query_root_entity_unknown_type_returns_null() {
        let host = build_test_host(HashMap::new());
        let schema = build_schema(host);

        let id = Uuid::new_v4();
        let query = format!(
            r#"{{ entity(id: "{}", entityType: "widget") {{ id }} }}"#,
            id
        );
        let result = schema.execute(&query).await;
        assert!(result.errors.is_empty(), "errors: {:?}", result.errors);
        let data = result.data.into_json().expect("json");
        assert!(data["entity"].is_null(), "unknown type should return null");
    }

    // -----------------------------------------------------------------------
    // Schema: entity query - entity not found returns null
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_query_root_entity_not_found_returns_null() {
        let host = build_host_with_fetcher("order", Arc::new(MockFetcher::new()));
        let schema = build_schema(host);

        let id = Uuid::new_v4();
        let query = format!(
            r#"{{ entity(id: "{}", entityType: "order") {{ id }} }}"#,
            id
        );
        let result = schema.execute(&query).await;
        assert!(result.errors.is_empty(), "errors: {:?}", result.errors);
        let data = result.data.into_json().expect("json");
        assert!(data["entity"].is_null(), "not found should return null");
    }

    // -----------------------------------------------------------------------
    // Schema: entity query with invalid UUID returns error
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_query_root_entity_invalid_uuid() {
        let mut fetchers: HashMap<String, Arc<dyn EntityFetcher>> = HashMap::new();
        fetchers.insert("order".to_string(), Arc::new(MockFetcher::new()));
        let host = build_test_host(fetchers);
        let schema = build_schema(host);

        let query = r#"{ entity(id: "not-a-uuid", entityType: "order") { id } }"#;
        let result = schema.execute(query).await;
        assert!(
            !result.errors.is_empty(),
            "invalid UUID should produce errors"
        );
    }

    // -----------------------------------------------------------------------
    // Schema: entityLinks query
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_query_root_entity_links() {
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();
        let host = build_test_host(HashMap::new());

        // Create a link in the store
        let link_entity = crate::core::link::LinkEntity::new(
            "has_invoice",
            source_id,
            target_id,
            Some(json!({"amount": 100})),
        );
        host.link_service
            .create(link_entity)
            .await
            .expect("should create link");

        let schema = build_schema(host);

        let query = format!(
            r#"{{ entityLinks(entityId: "{}") {{ linkType sourceId targetId }} }}"#,
            source_id
        );
        let result = schema.execute(&query).await;
        assert!(result.errors.is_empty(), "errors: {:?}", result.errors);
        let data = result.data.into_json().expect("json");
        let links = data["entityLinks"].as_array().expect("should be array");
        assert_eq!(links.len(), 1);
        assert_eq!(links[0]["linkType"], "has_invoice");
        assert_eq!(links[0]["sourceId"], source_id.to_string());
    }

    // -----------------------------------------------------------------------
    // Schema: createLink mutation
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_mutation_create_link() {
        let host = build_test_host(HashMap::new());
        let schema = build_schema(host);

        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();
        let query = format!(
            r#"mutation {{ createLink(sourceId: "{}", targetId: "{}", linkType: "has_invoice") {{ id sourceId targetId linkType }} }}"#,
            source_id, target_id
        );

        let result = schema.execute(&query).await;
        assert!(result.errors.is_empty(), "errors: {:?}", result.errors);
        let data = result.data.into_json().expect("json");
        let link = &data["createLink"];
        assert_eq!(link["sourceId"], source_id.to_string());
        assert_eq!(link["targetId"], target_id.to_string());
        assert_eq!(link["linkType"], "has_invoice");
        assert!(link["id"].as_str().is_some(), "link should have an id");
    }

    // -----------------------------------------------------------------------
    // Schema: createLink with invalid UUID
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_mutation_create_link_invalid_source_uuid() {
        let host = build_test_host(HashMap::new());
        let schema = build_schema(host);

        let query = format!(
            r#"mutation {{ createLink(sourceId: "not-a-uuid", targetId: "{}", linkType: "x") {{ id }} }}"#,
            Uuid::new_v4()
        );

        let result = schema.execute(&query).await;
        assert!(
            !result.errors.is_empty(),
            "invalid UUID should produce errors"
        );
    }

    // -----------------------------------------------------------------------
    // Schema: deleteLink mutation
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_mutation_delete_link() {
        let host = build_test_host(HashMap::new());

        // First create a link
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();
        let link_entity =
            crate::core::link::LinkEntity::new("has_invoice", source_id, target_id, None);
        let created = host
            .link_service
            .create(link_entity)
            .await
            .expect("should create link");

        let schema = build_schema(host);

        let query = format!(r#"mutation {{ deleteLink(id: "{}") }}"#, created.id);
        let result = schema.execute(&query).await;
        assert!(result.errors.is_empty(), "errors: {:?}", result.errors);
        let data = result.data.into_json().expect("json");
        assert_eq!(data["deleteLink"], true);
    }

    // -----------------------------------------------------------------------
    // Schema: list_entities returns empty (stub implementation)
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_query_root_list_orders_returns_empty() {
        let host = build_test_host(HashMap::new());
        let schema = build_schema(host);

        let result = schema.execute("{ orders { id } }").await;
        assert!(result.errors.is_empty(), "errors: {:?}", result.errors);
        let data = result.data.into_json().expect("json");
        let orders = data["orders"].as_array().expect("should be array");
        assert!(orders.is_empty(), "list_entities returns empty for now");
    }

    // -----------------------------------------------------------------------
    // Schema: link query by ID
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_query_root_link_by_id() {
        let host = build_test_host(HashMap::new());

        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();
        let link_entity =
            crate::core::link::LinkEntity::new("has_invoice", source_id, target_id, None);
        let created = host
            .link_service
            .create(link_entity)
            .await
            .expect("should create link");

        let schema = build_schema(host);

        let query = format!(
            r#"{{ link(id: "{}") {{ id linkType sourceId targetId }} }}"#,
            created.id
        );
        let result = schema.execute(&query).await;
        assert!(result.errors.is_empty(), "errors: {:?}", result.errors);
        let data = result.data.into_json().expect("json");
        let link = &data["link"];
        assert_eq!(link["linkType"], "has_invoice");
        assert_eq!(link["sourceId"], source_id.to_string());
    }

    // -----------------------------------------------------------------------
    // Schema: link query not found returns null
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_query_root_link_not_found() {
        let host = build_test_host(HashMap::new());
        let schema = build_schema(host);

        let id = Uuid::new_v4();
        let query = format!(r#"{{ link(id: "{}") {{ id }} }}"#, id);
        let result = schema.execute(&query).await;
        assert!(result.errors.is_empty(), "errors: {:?}", result.errors);
        let data = result.data.into_json().expect("json");
        assert!(
            data["link"].is_null(),
            "non-existent link should return null"
        );
    }
}