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
//! Link-specific mutations for GraphQL
//!
//! After each successful link mutation, events are published to the EventBus
//! (if configured) for real-time notification to all protocol subscribers.

use anyhow::{Result, bail};
use graphql_parser::query::Field;
use serde_json::{Value, json};
use std::sync::Arc;
use uuid::Uuid;

use super::field_resolver;
use super::utils;
use crate::core::events::{FrameworkEvent, LinkEvent};
use crate::core::link::LinkEntity;
use crate::server::host::ServerHost;

/// Create a link between two existing entities
pub async fn create_link_mutation(
    host: &Arc<ServerHost>,
    field: &Field<'_, String>,
) -> Result<Value> {
    // Get arguments
    let source_id = utils::get_string_arg(field, "sourceId")
        .ok_or_else(|| anyhow::anyhow!("Missing required argument 'sourceId'"))?;
    let target_id = utils::get_string_arg(field, "targetId")
        .ok_or_else(|| anyhow::anyhow!("Missing required argument 'targetId'"))?;
    let link_type = utils::get_string_arg(field, "linkType")
        .ok_or_else(|| anyhow::anyhow!("Missing required argument 'linkType'"))?;

    let source_uuid = Uuid::parse_str(&source_id)?;
    let target_uuid = Uuid::parse_str(&target_id)?;

    // Get optional metadata
    let metadata = utils::get_json_arg(field, "metadata");

    // Create the link
    let link_entity = LinkEntity::new(link_type, source_uuid, target_uuid, metadata);
    let created_link = host.link_service.create(link_entity).await?;

    // Publish event to EventBus
    if let Some(event_bus) = host.event_bus() {
        event_bus.publish(FrameworkEvent::Link(LinkEvent::Created {
            link_type: created_link.link_type.clone(),
            link_id: created_link.id,
            source_id: created_link.source_id,
            target_id: created_link.target_id,
            metadata: created_link.metadata.clone(),
        }));
    }

    // Return the created link as JSON
    Ok(json!({
        "id": created_link.id.to_string(),
        "sourceId": created_link.source_id.to_string(),
        "targetId": created_link.target_id.to_string(),
        "linkType": created_link.link_type,
        "metadata": created_link.metadata,
        "createdAt": created_link.created_at.to_rfc3339(),
    }))
}

/// Delete a link by ID
pub async fn delete_link_mutation(
    host: &Arc<ServerHost>,
    field: &Field<'_, String>,
) -> Result<Value> {
    let link_id = utils::get_string_arg(field, "id")
        .ok_or_else(|| anyhow::anyhow!("Missing required argument 'id'"))?;
    let uuid = Uuid::parse_str(&link_id)?;

    // Fetch link details before deleting (for event payload)
    let link = host.link_service.get(&uuid).await?;

    host.link_service.delete(&uuid).await?;

    // Publish event to EventBus (only if we found the link details)
    if let (Some(event_bus), Some(link)) = (host.event_bus(), link) {
        event_bus.publish(FrameworkEvent::Link(LinkEvent::Deleted {
            link_type: link.link_type,
            link_id: link.id,
            source_id: link.source_id,
            target_id: link.target_id,
        }));
    }

    Ok(Value::Bool(true))
}

/// Create an entity and link it to another entity (e.g., createInvoiceForOrder)
pub async fn create_and_link_mutation(
    host: &Arc<ServerHost>,
    field: &Field<'_, String>,
) -> Result<Value> {
    let field_name = field.name.as_str();

    // Parse field name: createInvoiceForOrder -> (invoice, order)
    let parts: Vec<&str> = field_name
        .strip_prefix("create")
        .unwrap_or("")
        .split("For")
        .collect();

    if parts.len() != 2 {
        bail!("Invalid createAndLink mutation format: {}", field_name);
    }

    let entity_type = utils::pascal_to_snake(parts[0]);
    let parent_type = utils::pascal_to_snake(parts[1]);

    // Get arguments
    let parent_id = utils::get_string_arg(field, "parentId")
        .ok_or_else(|| anyhow::anyhow!("Missing required argument 'parentId'"))?;
    let data = utils::get_json_arg(field, "data")
        .ok_or_else(|| anyhow::anyhow!("Missing required argument 'data'"))?;
    let link_type = utils::get_string_arg(field, "linkType");

    let parent_uuid = Uuid::parse_str(&parent_id)?;

    // Create the entity
    if let Some(creator) = host.entity_creators.get(&entity_type) {
        let created = creator.create_from_json(data).await?;

        // Extract the new entity's ID
        let entity_id = created
            .get("id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Created entity missing id field"))?;
        let entity_uuid = Uuid::parse_str(entity_id)?;

        // Publish entity creation event
        if let Some(event_bus) = host.event_bus() {
            event_bus.publish(FrameworkEvent::Entity(
                crate::core::events::EntityEvent::Created {
                    entity_type: entity_type.clone(),
                    entity_id: entity_uuid,
                    data: created.clone(),
                },
            ));
        }

        // Find the appropriate link type from config
        let actual_link_type = if let Some(lt) = link_type {
            lt
        } else {
            // Try to find link type from config
            utils::find_link_type(&host.config.links, &parent_type, &entity_type)?
        };

        // Create the link
        let link_entity = LinkEntity::new(actual_link_type, parent_uuid, entity_uuid, None);
        let created_link = host.link_service.create(link_entity).await?;

        // Publish link creation event
        if let Some(event_bus) = host.event_bus() {
            event_bus.publish(FrameworkEvent::Link(LinkEvent::Created {
                link_type: created_link.link_type,
                link_id: created_link.id,
                source_id: created_link.source_id,
                target_id: created_link.target_id,
                metadata: created_link.metadata,
            }));
        }

        // Resolve sub-fields for the created entity
        let resolved = field_resolver::resolve_entity_fields(
            host,
            created,
            &field.selection_set.items,
            &entity_type,
        )
        .await?;

        Ok(resolved)
    } else {
        bail!("Unknown entity type: {}", entity_type);
    }
}

/// Link two existing entities (e.g., linkInvoiceToOrder)
pub async fn link_entities_mutation(
    host: &Arc<ServerHost>,
    field: &Field<'_, String>,
) -> Result<Value> {
    let field_name = field.name.as_str();

    // Parse field name: linkInvoiceToOrder -> (invoice, order)
    let parts: Vec<&str> = field_name
        .strip_prefix("link")
        .unwrap_or("")
        .split("To")
        .collect();

    if parts.len() != 2 {
        bail!("Invalid link mutation format: {}", field_name);
    }

    let source_type = utils::pascal_to_snake(parts[0]);
    let target_type = utils::pascal_to_snake(parts[1]);

    // Get arguments
    let source_id = utils::get_string_arg(field, "sourceId")
        .ok_or_else(|| anyhow::anyhow!("Missing required argument 'sourceId'"))?;
    let target_id = utils::get_string_arg(field, "targetId")
        .ok_or_else(|| anyhow::anyhow!("Missing required argument 'targetId'"))?;
    let link_type = utils::get_string_arg(field, "linkType");

    let source_uuid = Uuid::parse_str(&source_id)?;
    let target_uuid = Uuid::parse_str(&target_id)?;

    // Find the appropriate link type from config
    let actual_link_type = if let Some(lt) = link_type {
        lt
    } else {
        utils::find_link_type(&host.config.links, &source_type, &target_type)?
    };

    // Get optional metadata
    let metadata = utils::get_json_arg(field, "metadata");

    // Create the link
    let link_entity = LinkEntity::new(actual_link_type, source_uuid, target_uuid, metadata);
    let created_link = host.link_service.create(link_entity).await?;

    // Publish event to EventBus
    if let Some(event_bus) = host.event_bus() {
        event_bus.publish(FrameworkEvent::Link(LinkEvent::Created {
            link_type: created_link.link_type.clone(),
            link_id: created_link.id,
            source_id: created_link.source_id,
            target_id: created_link.target_id,
            metadata: created_link.metadata.clone(),
        }));
    }

    // Return the created link
    Ok(json!({
        "id": created_link.id.to_string(),
        "sourceId": created_link.source_id.to_string(),
        "targetId": created_link.target_id.to_string(),
        "linkType": created_link.link_type,
        "metadata": created_link.metadata,
        "createdAt": created_link.created_at.to_rfc3339(),
    }))
}

/// Unlink two entities (e.g., unlinkInvoiceFromOrder)
pub async fn unlink_entities_mutation(
    host: &Arc<ServerHost>,
    field: &Field<'_, String>,
) -> Result<Value> {
    let field_name = field.name.as_str();

    // Parse field name: unlinkInvoiceFromOrder -> (invoice, order)
    let parts: Vec<&str> = field_name
        .strip_prefix("unlink")
        .unwrap_or("")
        .split("From")
        .collect();

    if parts.len() != 2 {
        bail!("Invalid unlink mutation format: {}", field_name);
    }

    let source_type = utils::pascal_to_snake(parts[0]);
    let target_type = utils::pascal_to_snake(parts[1]);

    // Get arguments
    let source_id = utils::get_string_arg(field, "sourceId")
        .ok_or_else(|| anyhow::anyhow!("Missing required argument 'sourceId'"))?;
    let target_id = utils::get_string_arg(field, "targetId")
        .ok_or_else(|| anyhow::anyhow!("Missing required argument 'targetId'"))?;
    let link_type = utils::get_string_arg(field, "linkType");

    let source_uuid = Uuid::parse_str(&source_id)?;
    let target_uuid = Uuid::parse_str(&target_id)?;

    // Find the appropriate link type from config
    let actual_link_type = if let Some(lt) = link_type {
        Some(lt)
    } else {
        utils::find_link_type(&host.config.links, &source_type, &target_type).ok()
    };

    // Find and delete the link
    let links = host
        .link_service
        .find_by_source(
            &source_uuid,
            actual_link_type.as_deref(),
            Some(&target_type),
        )
        .await?;

    for link in links {
        if link.target_id == target_uuid {
            host.link_service.delete(&link.id).await?;

            // Publish event to EventBus
            if let Some(event_bus) = host.event_bus() {
                event_bus.publish(FrameworkEvent::Link(LinkEvent::Deleted {
                    link_type: link.link_type,
                    link_id: link.id,
                    source_id: link.source_id,
                    target_id: link.target_id,
                }));
            }

            return Ok(Value::Bool(true));
        }
    }

    Ok(Value::Bool(false))
}

#[cfg(test)]
#[cfg(feature = "graphql")]
mod tests {
    use super::super::core::GraphQLExecutor;
    use crate::config::{EntityAuthConfig, EntityConfig, LinksConfig};
    use crate::core::link::{LinkDefinition, LinkEntity};
    use crate::core::service::LinkService;
    use crate::core::{EntityCreator, EntityFetcher};
    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, json};
    use std::collections::HashMap;
    use std::sync::Arc;
    use uuid::Uuid;

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

    struct MockFetcher;

    #[async_trait]
    impl EntityFetcher for MockFetcher {
        async fn fetch_as_json(&self, _entity_id: &Uuid) -> anyhow::Result<Value> {
            Ok(json!({}))
        }
    }

    struct MockCreator;

    #[async_trait]
    impl EntityCreator for MockCreator {
        async fn create_from_json(&self, mut data: Value) -> anyhow::Result<Value> {
            let id = Uuid::new_v4();
            if let Some(obj) = data.as_object_mut() {
                obj.insert("id".to_string(), json!(id.to_string()));
            }
            Ok(data)
        }

        async fn update_from_json(
            &self,
            entity_id: &Uuid,
            mut data: Value,
        ) -> anyhow::Result<Value> {
            if let Some(obj) = data.as_object_mut() {
                obj.insert("id".to_string(), json!(entity_id.to_string()));
            }
            Ok(data)
        }

        async fn delete(&self, _entity_id: &Uuid) -> anyhow::Result<()> {
            Ok(())
        }
    }

    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_with_link_service(
        link_service: Arc<InMemoryLinkService>,
    ) -> Arc<ServerHost> {
        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")));

        let mut fetchers: HashMap<String, Arc<dyn EntityFetcher>> = HashMap::new();
        fetchers.insert("order".to_string(), Arc::new(MockFetcher));
        fetchers.insert("invoice".to_string(), Arc::new(MockFetcher));

        let mut creators: HashMap<String, Arc<dyn EntityCreator>> = HashMap::new();
        creators.insert("order".to_string(), Arc::new(MockCreator));
        creators.insert("invoice".to_string(), Arc::new(MockCreator));

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

    fn default_host() -> (Arc<ServerHost>, Arc<InMemoryLinkService>) {
        let link_service = Arc::new(InMemoryLinkService::new());
        let host = build_test_host_with_link_service(link_service.clone());
        (host, link_service)
    }

    // -----------------------------------------------------------------------
    // create_link_mutation tests (via executor)
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_create_link_mutation_success() {
        let (host, _) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ createLink(sourceId: "{}", targetId: "{}", linkType: "has_invoice") {{ id }} }}"#,
            source_id, target_id
        );
        let result = executor
            .execute(&query, None)
            .await
            .expect("should create link");

        let link_result = result
            .get("data")
            .and_then(|d| d.get("createLink"))
            .expect("should have createLink");
        assert!(link_result.get("id").is_some(), "should have id");
    }

    #[tokio::test]
    async fn test_create_link_mutation_missing_source_id() {
        let (host, _) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let target_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ createLink(targetId: "{}", linkType: "has_invoice") {{ id }} }}"#,
            target_id
        );
        let result = executor.execute(&query, None).await;
        assert!(result.is_err(), "missing sourceId should error");
        let err_msg = result.expect_err("error").to_string();
        assert!(
            err_msg.contains("sourceId"),
            "should mention sourceId: {}",
            err_msg
        );
    }

    #[tokio::test]
    async fn test_create_link_mutation_missing_link_type() {
        let (host, _) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ createLink(sourceId: "{}", targetId: "{}") {{ id }} }}"#,
            source_id, target_id
        );
        let result = executor.execute(&query, None).await;
        assert!(result.is_err(), "missing linkType should error");
        let err_msg = result.expect_err("error").to_string();
        assert!(
            err_msg.contains("linkType"),
            "should mention linkType: {}",
            err_msg
        );
    }

    // -----------------------------------------------------------------------
    // delete_link_mutation tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_delete_link_mutation_direct_call() {
        // Note: deleteLink via executor gets caught by the "delete*" prefix check
        // and routes to delete_entity_mutation instead of delete_link_mutation.
        // So we test delete_link_mutation directly using a manually constructed Field.
        use super::delete_link_mutation;
        use graphql_parser::Pos;
        use graphql_parser::query::{SelectionSet, Value as GqlValue};

        let (host, link_service) = default_host();

        // Create a link first
        let link = LinkEntity::new("has_invoice", Uuid::new_v4(), Uuid::new_v4(), None);
        let created = link_service.create(link).await.expect("should create link");

        let pos = Pos { line: 1, column: 1 };
        let field = graphql_parser::query::Field {
            position: pos,
            alias: None,
            name: "deleteLink".to_string(),
            arguments: vec![("id".to_string(), GqlValue::String(created.id.to_string()))],
            directives: vec![],
            selection_set: SelectionSet {
                span: (pos, pos),
                items: vec![],
            },
        };

        let result = delete_link_mutation(&host, &field)
            .await
            .expect("should delete link");
        assert_eq!(result, Value::Bool(true));
    }

    #[tokio::test]
    async fn test_delete_link_mutation_missing_id_direct_call() {
        use super::delete_link_mutation;
        use graphql_parser::Pos;
        use graphql_parser::query::SelectionSet;

        let (host, _) = default_host();

        let pos = Pos { line: 1, column: 1 };
        let field = graphql_parser::query::Field {
            position: pos,
            alias: None,
            name: "deleteLink".to_string(),
            arguments: vec![],
            directives: vec![],
            selection_set: SelectionSet {
                span: (pos, pos),
                items: vec![],
            },
        };

        let result = delete_link_mutation(&host, &field).await;
        assert!(result.is_err(), "missing id should error");
    }

    // -----------------------------------------------------------------------
    // create_and_link_mutation tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_create_and_link_mutation_success() {
        let (host, link_service) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let parent_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ createInvoiceForOrder(parentId: "{}", data: {{amount: 100}}) {{ id }} }}"#,
            parent_id
        );
        let result = executor
            .execute(&query, None)
            .await
            .expect("should create and link");

        let created = result
            .get("data")
            .and_then(|d| d.get("createInvoiceForOrder"))
            .expect("should have createInvoiceForOrder");
        assert!(created.get("id").is_some(), "created entity should have id");

        // Verify the link was created
        let links = link_service
            .find_by_source(&parent_id, Some("has_invoice"), None)
            .await
            .expect("should find links");
        assert_eq!(links.len(), 1, "should have one link from parent");
    }

    #[tokio::test]
    async fn test_create_and_link_mutation_missing_parent_id() {
        let (host, _) = default_host();
        let executor = GraphQLExecutor::new(host).await;

        let result = executor
            .execute(
                r#"mutation { createInvoiceForOrder(data: {amount: 100}) { id } }"#,
                None,
            )
            .await;
        assert!(result.is_err(), "missing parentId should error");
        let err_msg = result.expect_err("error").to_string();
        assert!(
            err_msg.contains("parentId"),
            "should mention parentId: {}",
            err_msg
        );
    }

    #[tokio::test]
    async fn test_create_and_link_mutation_missing_data() {
        let (host, _) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let parent_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ createInvoiceForOrder(parentId: "{}") {{ id }} }}"#,
            parent_id
        );
        let result = executor.execute(&query, None).await;
        assert!(result.is_err(), "missing data should error");
    }

    #[tokio::test]
    async fn test_create_and_link_mutation_unknown_entity_type() {
        let (host, _) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let parent_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ createWidgetForGadget(parentId: "{}", data: {{name: "w"}}) {{ id }} }}"#,
            parent_id
        );
        let result = executor.execute(&query, None).await;
        assert!(result.is_err(), "unknown entity type should error");
    }

    #[tokio::test]
    async fn test_create_and_link_mutation_with_explicit_link_type() {
        let (host, link_service) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let parent_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ createInvoiceForOrder(parentId: "{}", data: {{amount: 200}}, linkType: "has_invoice") {{ id }} }}"#,
            parent_id
        );
        let result = executor
            .execute(&query, None)
            .await
            .expect("should succeed with explicit linkType");

        let created = result
            .get("data")
            .and_then(|d| d.get("createInvoiceForOrder"))
            .expect("should have result");
        assert!(created.get("id").is_some());

        let links = link_service
            .find_by_source(&parent_id, Some("has_invoice"), None)
            .await
            .expect("should find links");
        assert_eq!(links.len(), 1);
    }

    // -----------------------------------------------------------------------
    // link_entities_mutation tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_link_entities_mutation_success() {
        let (host, link_service) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();

        // linkOrderToInvoice -> source_type="order", target_type="invoice" -> matches config
        let query = format!(
            r#"mutation {{ linkOrderToInvoice(sourceId: "{}", targetId: "{}") {{ id }} }}"#,
            source_id, target_id
        );
        let result = executor
            .execute(&query, None)
            .await
            .expect("should link entities");

        let link_result = result
            .get("data")
            .and_then(|d| d.get("linkOrderToInvoice"))
            .expect("should have result");
        assert!(link_result.get("id").is_some(), "link should have id");

        // Verify link in storage
        let links = link_service
            .find_by_source(&source_id, Some("has_invoice"), None)
            .await
            .expect("should find links");
        assert_eq!(links.len(), 1);
    }

    #[tokio::test]
    async fn test_link_entities_mutation_missing_source_id() {
        let (host, _) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let target_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ linkOrderToInvoice(targetId: "{}") {{ id }} }}"#,
            target_id
        );
        let result = executor.execute(&query, None).await;
        assert!(result.is_err(), "missing sourceId should error");
    }

    #[tokio::test]
    async fn test_link_entities_mutation_with_explicit_link_type() {
        let (host, _) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ linkOrderToInvoice(sourceId: "{}", targetId: "{}", linkType: "has_invoice") {{ id }} }}"#,
            source_id, target_id
        );
        let result = executor
            .execute(&query, None)
            .await
            .expect("should succeed with explicit linkType");

        let link_result = result
            .get("data")
            .and_then(|d| d.get("linkOrderToInvoice"))
            .expect("should have result");
        assert!(link_result.get("id").is_some());
    }

    // -----------------------------------------------------------------------
    // unlink_entities_mutation tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_unlink_entities_mutation_found_and_deleted() {
        let (host, link_service) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();

        // Create a link first
        let link = LinkEntity::new("has_invoice", source_id, target_id, None);
        link_service.create(link).await.expect("should create link");

        // unlinkOrderFromInvoice -> source_type="order", target_type="invoice"
        // find_link_type("order", "invoice") -> "has_invoice"
        // find_by_source(source_id, "has_invoice", "invoice")
        let query = format!(
            r#"mutation {{ unlinkOrderFromInvoice(sourceId: "{}", targetId: "{}") }}"#,
            source_id, target_id
        );
        let result = executor
            .execute(&query, None)
            .await
            .expect("should succeed");

        let unlink_result = result
            .get("data")
            .and_then(|d| d.get("unlinkOrderFromInvoice"))
            .expect("should have result");
        assert_eq!(
            *unlink_result,
            Value::Bool(true),
            "should return true when link found and deleted"
        );
    }

    #[tokio::test]
    async fn test_unlink_entities_mutation_no_link_found() {
        let (host, _) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ unlinkOrderFromInvoice(sourceId: "{}", targetId: "{}") }}"#,
            source_id, target_id
        );
        let result = executor
            .execute(&query, None)
            .await
            .expect("should succeed even without link");

        let unlink_result = result
            .get("data")
            .and_then(|d| d.get("unlinkOrderFromInvoice"))
            .expect("should have result");
        assert_eq!(
            *unlink_result,
            Value::Bool(false),
            "should return false when no link found"
        );
    }

    #[tokio::test]
    async fn test_unlink_entities_mutation_missing_source_id() {
        let (host, _) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let target_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ unlinkOrderFromInvoice(targetId: "{}") }}"#,
            target_id
        );
        let result = executor.execute(&query, None).await;
        assert!(result.is_err(), "missing sourceId should error");
    }

    #[tokio::test]
    async fn test_unlink_entities_mutation_missing_target_id() {
        let (host, _) = default_host();
        let executor = GraphQLExecutor::new(host).await;
        let source_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ unlinkOrderFromInvoice(sourceId: "{}") }}"#,
            source_id
        );
        let result = executor.execute(&query, None).await;
        assert!(result.is_err(), "missing targetId should error");
    }

    // -----------------------------------------------------------------------
    // Tests with EventBus configured (cover event publishing paths)
    // -----------------------------------------------------------------------

    fn build_host_with_event_bus(link_service: Arc<InMemoryLinkService>) -> Arc<ServerHost> {
        use crate::core::events::EventBus;

        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")));

        let mut fetchers: HashMap<String, Arc<dyn EntityFetcher>> = HashMap::new();
        fetchers.insert("order".to_string(), Arc::new(MockFetcher));
        fetchers.insert("invoice".to_string(), Arc::new(MockFetcher));

        let mut creators: HashMap<String, Arc<dyn EntityCreator>> = HashMap::new();
        creators.insert("order".to_string(), Arc::new(MockCreator));
        creators.insert("invoice".to_string(), Arc::new(MockCreator));

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

    fn host_with_event_bus() -> (Arc<ServerHost>, Arc<InMemoryLinkService>) {
        let link_service = Arc::new(InMemoryLinkService::new());
        let host = build_host_with_event_bus(link_service.clone());
        (host, link_service)
    }

    #[tokio::test]
    async fn test_create_link_with_event_bus() {
        let (host, _) = host_with_event_bus();
        let executor = GraphQLExecutor::new(host).await;
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ createLink(sourceId: "{}", targetId: "{}", linkType: "has_invoice") {{ id }} }}"#,
            source_id, target_id
        );
        let result = executor
            .execute(&query, None)
            .await
            .expect("should create link with EventBus");

        let link_result = result
            .get("data")
            .and_then(|d| d.get("createLink"))
            .expect("should have createLink");
        assert!(link_result.get("id").is_some());
    }

    #[tokio::test]
    async fn test_delete_link_with_event_bus() {
        use super::delete_link_mutation;
        use graphql_parser::Pos;
        use graphql_parser::query::{SelectionSet, Value as GqlValue};

        let (host, link_service) = host_with_event_bus();

        let link = LinkEntity::new("has_invoice", Uuid::new_v4(), Uuid::new_v4(), None);
        let created = link_service.create(link).await.expect("should create link");

        let pos = Pos { line: 1, column: 1 };
        let field = graphql_parser::query::Field {
            position: pos,
            alias: None,
            name: "deleteLink".to_string(),
            arguments: vec![("id".to_string(), GqlValue::String(created.id.to_string()))],
            directives: vec![],
            selection_set: SelectionSet {
                span: (pos, pos),
                items: vec![],
            },
        };

        let result = delete_link_mutation(&host, &field)
            .await
            .expect("should delete link with EventBus");
        assert_eq!(result, Value::Bool(true));
    }

    #[tokio::test]
    async fn test_create_and_link_with_event_bus() {
        let (host, link_service) = host_with_event_bus();
        let executor = GraphQLExecutor::new(host).await;
        let parent_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ createInvoiceForOrder(parentId: "{}", data: {{amount: 100}}) {{ id }} }}"#,
            parent_id
        );
        let result = executor
            .execute(&query, None)
            .await
            .expect("should create and link with EventBus");

        let created = result
            .get("data")
            .and_then(|d| d.get("createInvoiceForOrder"))
            .expect("should have result");
        assert!(created.get("id").is_some());

        let links = link_service
            .find_by_source(&parent_id, Some("has_invoice"), None)
            .await
            .expect("should find links");
        assert_eq!(links.len(), 1);
    }

    #[tokio::test]
    async fn test_link_entities_with_event_bus() {
        let (host, _) = host_with_event_bus();
        let executor = GraphQLExecutor::new(host).await;
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();

        let query = format!(
            r#"mutation {{ linkOrderToInvoice(sourceId: "{}", targetId: "{}") {{ id }} }}"#,
            source_id, target_id
        );
        let result = executor
            .execute(&query, None)
            .await
            .expect("should link entities with EventBus");

        let link_result = result
            .get("data")
            .and_then(|d| d.get("linkOrderToInvoice"))
            .expect("should have result");
        assert!(link_result.get("id").is_some());
    }

    #[tokio::test]
    async fn test_unlink_entities_with_event_bus() {
        let (host, link_service) = host_with_event_bus();
        let executor = GraphQLExecutor::new(host).await;
        let source_id = Uuid::new_v4();
        let target_id = Uuid::new_v4();

        // Create a link first
        let link = LinkEntity::new("has_invoice", source_id, target_id, None);
        link_service.create(link).await.expect("should create link");

        let query = format!(
            r#"mutation {{ unlinkOrderFromInvoice(sourceId: "{}", targetId: "{}") }}"#,
            source_id, target_id
        );
        let result = executor
            .execute(&query, None)
            .await
            .expect("should unlink with EventBus");

        let unlink_result = result
            .get("data")
            .and_then(|d| d.get("unlinkOrderFromInvoice"))
            .expect("should have result");
        assert_eq!(*unlink_result, Value::Bool(true));
    }
}