server-less 0.6.0

Composable derive macros for common Rust patterns
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
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
//! Integration tests for the GraphQL macro.

#![allow(dead_code)]
#![allow(unused_variables)]

use serde::{Deserialize, Serialize};
use server_less::{graphql, graphql_enum, serve, server};

#[derive(Clone)]
struct SimpleService {
    prefix: String,
}

impl SimpleService {
    fn new() -> Self {
        Self {
            prefix: "Hello".to_string(),
        }
    }
}

#[graphql]
impl SimpleService {
    /// Get greeting
    pub fn get_greeting(&self) -> String {
        format!("{}, World!", self.prefix)
    }

    /// List items
    pub fn list_items(&self) -> Vec<String> {
        vec!["a".to_string(), "b".to_string()]
    }

    /// Create item
    pub fn create_item(&self, name: String) -> String {
        format!("Created: {}", name)
    }

    /// Get count
    pub fn get_count(&self) -> i32 {
        42
    }

    /// Check active
    pub fn is_active(&self) -> bool {
        true
    }
}

#[test]
fn test_graphql_schema_created() {
    let service = SimpleService::new();
    let schema = service.graphql_schema();
    // Schema is created successfully
    let _ = schema;
}

#[test]
fn test_graphql_sdl_generated() {
    let service = SimpleService::new();
    let sdl = service.graphql_sdl();

    // Check SDL contains expected types
    assert!(
        sdl.contains("SimpleServiceQuery"),
        "SDL should have Query type, got:\n{}",
        sdl
    );
    assert!(
        sdl.contains("SimpleServiceMutation"),
        "SDL should have Mutation type"
    );

    // Check query methods (camelCase)
    assert!(
        sdl.contains("getGreeting"),
        "SDL should have getGreeting query"
    );
    assert!(sdl.contains("listItems"), "SDL should have listItems query");

    // Check mutation methods
    assert!(
        sdl.contains("createItem"),
        "SDL should have createItem mutation"
    );
}

#[test]
fn test_graphql_router_created() {
    let service = SimpleService::new();
    let router = service.graphql_router();
    // Router is created successfully
    let _ = router;
}

// Test query-only service (no mutations)
#[derive(Clone)]
struct ReadOnlyService;

#[graphql]
impl ReadOnlyService {
    /// Get info
    pub fn get_info(&self) -> String {
        "read only".to_string()
    }

    /// List things
    pub fn list_things(&self) -> Vec<String> {
        vec![]
    }
}

#[test]
fn test_graphql_query_only_service() {
    let service = ReadOnlyService;
    let sdl = service.graphql_sdl();

    // Should have query type
    assert!(sdl.contains("ReadOnlyServiceQuery"));
}

// Test actual query execution
#[tokio::test]
async fn test_graphql_execute_query() {
    let service = SimpleService::new();
    let schema = service.graphql_schema();

    let result = schema.execute("{ getGreeting }").await;
    assert!(
        result.errors.is_empty(),
        "Query should succeed: {:?}",
        result.errors
    );

    // The result should contain our greeting
    let data = result.data.into_json().unwrap();
    assert!(data["getGreeting"].as_str().is_some());
}

#[tokio::test]
async fn test_graphql_execute_query_with_int() {
    let service = SimpleService::new();
    let schema = service.graphql_schema();

    let result = schema.execute("{ getCount }").await;
    assert!(
        result.errors.is_empty(),
        "Query should succeed: {:?}",
        result.errors
    );
}

#[tokio::test]
async fn test_graphql_execute_query_with_bool() {
    let service = SimpleService::new();
    let schema = service.graphql_schema();

    let result = schema.execute("{ isActive }").await;
    assert!(
        result.errors.is_empty(),
        "Query should succeed: {:?}",
        result.errors
    );
}

#[tokio::test]
async fn test_graphql_execute_mutation() {
    let service = SimpleService::new();
    let schema = service.graphql_schema();

    let result = schema
        .execute(r#"mutation { createItem(name: "test") }"#)
        .await;
    assert!(
        result.errors.is_empty(),
        "Mutation should succeed: {:?}",
        result.errors
    );
}

#[tokio::test]
async fn test_graphql_execute_list_query() {
    let service = SimpleService::new();
    let schema = service.graphql_schema();

    let result = schema.execute("{ listItems }").await;
    assert!(
        result.errors.is_empty(),
        "List query should succeed: {:?}",
        result.errors
    );
}

// Test custom struct objects
#[derive(Clone, Debug, Serialize, Deserialize)]
struct User {
    id: i32,
    name: String,
    email: String,
    active: bool,
}

#[derive(Clone)]
struct UserService;

#[graphql]
impl UserService {
    /// Get user by ID
    pub fn get_user(&self, id: i32) -> User {
        User {
            id,
            name: "Alice".to_string(),
            email: "alice@example.com".to_string(),
            active: true,
        }
    }

    /// List all users
    pub fn list_users(&self) -> Vec<User> {
        vec![
            User {
                id: 1,
                name: "Alice".to_string(),
                email: "alice@example.com".to_string(),
                active: true,
            },
            User {
                id: 2,
                name: "Bob".to_string(),
                email: "bob@example.com".to_string(),
                active: false,
            },
        ]
    }

    /// Create user
    pub fn create_user(&self, name: String, email: String) -> User {
        User {
            id: 99,
            name,
            email,
            active: true,
        }
    }
}

#[tokio::test]
async fn test_graphql_custom_struct_query() {
    let service = UserService;
    let schema = service.graphql_schema();

    let result = schema.execute("{ getUser(id: 1) }").await;
    assert!(
        result.errors.is_empty(),
        "Custom struct query should succeed: {:?}",
        result.errors
    );

    // The result should be a proper object, not a string
    let data = result.data.into_json().unwrap();
    let user = &data["getUser"];

    // Verify we get an object with fields
    assert!(user.is_object(), "Should return object, got: {:?}", user);
    assert_eq!(user["id"], 1, "Should have correct id field");
    assert_eq!(user["name"], "Alice", "Should have correct name field");
    assert_eq!(
        user["email"], "alice@example.com",
        "Should have correct email field"
    );
    assert_eq!(user["active"], true, "Should have correct active field");
}

#[tokio::test]
async fn test_graphql_custom_struct_list_query() {
    let service = UserService;
    let schema = service.graphql_schema();

    let result = schema.execute("{ listUsers }").await;
    assert!(
        result.errors.is_empty(),
        "Custom struct list query should succeed: {:?}",
        result.errors
    );

    let data = result.data.into_json().unwrap();
    let users = &data["listUsers"];

    assert!(users.is_array(), "Should return array");
    let users_array = users.as_array().unwrap();
    assert_eq!(users_array.len(), 2, "Should have 2 users");

    // Check first user
    assert!(users_array[0].is_object(), "User should be object");
    assert_eq!(users_array[0]["id"], 1);
    assert_eq!(users_array[0]["name"], "Alice");
}

#[tokio::test]
async fn test_graphql_custom_struct_mutation() {
    let service = UserService;
    let schema = service.graphql_schema();

    let result = schema
        .execute(r#"mutation { createUser(name: "Charlie", email: "charlie@example.com") }"#)
        .await;
    assert!(
        result.errors.is_empty(),
        "Custom struct mutation should succeed: {:?}",
        result.errors
    );

    let data = result.data.into_json().unwrap();
    let user = &data["createUser"];

    assert!(user.is_object(), "Should return object");
    assert_eq!(user["id"], 99);
    assert_eq!(user["name"], "Charlie");
    assert_eq!(user["email"], "charlie@example.com");
    assert_eq!(user["active"], true);
}

#[test]
fn test_graphql_openapi_paths_generated() {
    let paths = SimpleService::graphql_openapi_paths();

    // Should have 2 paths: POST /graphql (query) and GET /graphql (playground)
    assert_eq!(paths.len(), 2);

    // Find the POST endpoint
    let post_path = paths.iter().find(|p| p.method == "post").unwrap();
    assert_eq!(post_path.path, "/graphql");
    assert!(
        post_path
            .operation
            .summary
            .as_ref()
            .unwrap()
            .contains("query")
    );
    assert!(post_path.operation.request_body.is_some());
    assert!(post_path.operation.responses.contains_key("200"));

    // Find the GET endpoint (playground)
    let get_path = paths.iter().find(|p| p.method == "get").unwrap();
    assert_eq!(get_path.path, "/graphql");
    assert!(
        get_path
            .operation
            .summary
            .as_ref()
            .unwrap()
            .contains("Playground")
    );
}

// ============================================================================
// Custom Scalar Tests
// ============================================================================

#[derive(Clone)]
struct JsonService;

#[graphql]
impl JsonService {
    /// Get raw JSON data
    pub fn get_data(&self) -> serde_json::Value {
        serde_json::json!({"key": "value"})
    }

    /// Echo JSON data
    pub fn create_entry(&self, data: serde_json::Value) -> serde_json::Value {
        data
    }
}

#[test]
fn test_graphql_json_scalar_schema() {
    let service = JsonService;
    let sdl = service.graphql_sdl();

    // The JSON scalar should be registered in the schema
    assert!(
        sdl.contains("scalar JSON"),
        "Should register JSON scalar type. SDL:\n{}",
        sdl
    );
}

#[tokio::test]
async fn test_graphql_json_scalar_query() {
    let service = JsonService;
    let schema = service.graphql_schema();

    let result = schema.execute("{ getData }").await;
    assert!(
        result.errors.is_empty(),
        "JSON scalar query should succeed: {:?}",
        result.errors
    );

    let data = result.data.into_json().unwrap();
    assert!(data["getData"].is_object(), "Should return JSON object");
    assert_eq!(data["getData"]["key"], "value");
}

// ============================================================================
// Enum Type Tests
// ============================================================================

#[graphql_enum]
#[derive(Clone, Debug)]
enum Priority {
    /// Low priority
    Low,
    /// Medium priority
    Medium,
    /// High priority
    High,
    /// Critical priority
    Critical,
}

#[test]
fn test_graphql_enum_type_definition() {
    let enum_type = Priority::__graphql_enum_type();
    // The enum type should have been created (we can't easily inspect it,
    // but at least it compiles and returns the right type)
    let _ = enum_type;
}

#[test]
fn test_graphql_enum_to_value() {
    let value = Priority::High.__to_graphql_value();
    // The value should be an Enum variant in SCREAMING_SNAKE_CASE
    assert_eq!(
        value,
        async_graphql::Value::Enum(async_graphql::Name::new("HIGH"))
    );
}

#[test]
fn test_graphql_enum_all_variants() {
    assert_eq!(
        Priority::Low.__to_graphql_value(),
        async_graphql::Value::Enum(async_graphql::Name::new("LOW"))
    );
    assert_eq!(
        Priority::Medium.__to_graphql_value(),
        async_graphql::Value::Enum(async_graphql::Name::new("MEDIUM"))
    );
    assert_eq!(
        Priority::High.__to_graphql_value(),
        async_graphql::Value::Enum(async_graphql::Name::new("HIGH"))
    );
    assert_eq!(
        Priority::Critical.__to_graphql_value(),
        async_graphql::Value::Enum(async_graphql::Name::new("CRITICAL"))
    );
}

#[derive(Clone)]
struct PriorityService;

#[graphql(enums(Priority))]
impl PriorityService {
    /// Get default priority
    pub fn get_default_priority(&self) -> String {
        // For now returns as String until full enum return type support
        "HIGH".to_string()
    }
}

#[test]
fn test_graphql_enum_registered_in_schema() {
    let service = PriorityService;
    let sdl = service.graphql_sdl();

    // The Priority enum should be registered in the SDL
    assert!(
        sdl.contains("enum Priority"),
        "Should register Priority enum type. SDL:\n{}",
        sdl
    );

    // Should have SCREAMING_SNAKE_CASE variants
    assert!(
        sdl.contains("LOW"),
        "Should have LOW variant. SDL:\n{}",
        sdl
    );
    assert!(
        sdl.contains("MEDIUM"),
        "Should have MEDIUM variant. SDL:\n{}",
        sdl
    );
    assert!(
        sdl.contains("HIGH"),
        "Should have HIGH variant. SDL:\n{}",
        sdl
    );
    assert!(
        sdl.contains("CRITICAL"),
        "Should have CRITICAL variant. SDL:\n{}",
        sdl
    );
}

// ============================================================================
// Nested Object Tests
// ============================================================================

#[derive(Clone, Debug, Serialize, Deserialize)]
struct NestedProfile {
    bio: String,
    avatar_url: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct UserWithProfile {
    id: i32,
    name: String,
    profile: NestedProfile,
}

#[derive(Clone)]
struct NestedService;

#[graphql]
impl NestedService {
    /// Get user with nested profile
    pub fn get_user_with_profile(&self, id: i32) -> UserWithProfile {
        UserWithProfile {
            id,
            name: "Alice".to_string(),
            profile: NestedProfile {
                bio: "Software engineer".to_string(),
                avatar_url: "https://example.com/avatar.jpg".to_string(),
            },
        }
    }

    /// Get list of users with profiles
    pub fn list_users_with_profiles(&self) -> Vec<UserWithProfile> {
        vec![
            UserWithProfile {
                id: 1,
                name: "Alice".to_string(),
                profile: NestedProfile {
                    bio: "Engineer".to_string(),
                    avatar_url: "https://example.com/alice.jpg".to_string(),
                },
            },
            UserWithProfile {
                id: 2,
                name: "Bob".to_string(),
                profile: NestedProfile {
                    bio: "Designer".to_string(),
                    avatar_url: "https://example.com/bob.jpg".to_string(),
                },
            },
        ]
    }
}

#[tokio::test]
async fn test_graphql_nested_object_query() {
    let service = NestedService;
    let schema = service.graphql_schema();

    // Query nested object
    let result = schema.execute("{ getUserWithProfile(id: 42) }").await;

    assert!(
        result.errors.is_empty(),
        "Query should succeed: {:?}",
        result.errors
    );

    // Convert to JSON for easier inspection
    let json: serde_json::Value = serde_json::to_value(&result.data).unwrap();
    let user = &json["getUserWithProfile"];

    // Check top-level fields
    assert_eq!(user["id"], 42);
    assert_eq!(user["name"], "Alice");

    // Check nested profile object (should NOT be a string)
    let profile = &user["profile"];
    assert!(
        profile.is_object(),
        "Profile should be an object, not a string. Got: {:?}",
        profile
    );
    assert_eq!(profile["bio"], "Software engineer");
    assert_eq!(profile["avatar_url"], "https://example.com/avatar.jpg");
}

#[tokio::test]
async fn test_graphql_nested_object_in_list() {
    let service = NestedService;
    let schema = service.graphql_schema();

    // Query list of nested objects
    let result = schema.execute("{ listUsersWithProfiles }").await;

    assert!(
        result.errors.is_empty(),
        "Query should succeed: {:?}",
        result.errors
    );

    // Convert to JSON for easier inspection
    let json: serde_json::Value = serde_json::to_value(&result.data).unwrap();
    let users = json["listUsersWithProfiles"]
        .as_array()
        .expect("Should be an array");

    assert_eq!(users.len(), 2);

    // Check first user's nested profile
    let alice = &users[0];
    assert_eq!(alice["name"], "Alice");
    let alice_profile = &alice["profile"];
    assert!(
        alice_profile.is_object(),
        "Profile should be an object. Got: {:?}",
        alice_profile
    );
    assert_eq!(alice_profile["bio"], "Engineer");

    // Check second user's nested profile
    let bob = &users[1];
    assert_eq!(bob["name"], "Bob");
    let bob_profile = &bob["profile"];
    assert!(
        bob_profile.is_object(),
        "Profile should be an object. Got: {:?}",
        bob_profile
    );
    assert_eq!(bob_profile["bio"], "Designer");
}

// ============================================================================
// Skip Tests
// ============================================================================

#[derive(Clone)]
struct SkipService;

#[graphql]
impl SkipService {
    /// Public query: should appear in schema
    pub fn get_public(&self) -> String {
        "public".to_string()
    }

    /// Internal mutation: should appear in schema
    pub fn create_public(&self, value: String) -> String {
        value
    }

    /// This method is skipped via #[server(skip)] and must NOT appear in the schema
    #[server(skip)]
    pub fn get_internal(&self) -> String {
        "internal".to_string()
    }

    /// Skipped mutation — must NOT appear in schema
    #[server(skip)]
    pub fn create_internal(&self, value: String) -> String {
        value
    }
}

#[test]
fn test_graphql_server_skip_excluded_from_sdl() {
    let service = SkipService;
    let sdl = service.graphql_sdl();

    // Non-skipped methods must be present
    assert!(
        sdl.contains("getPublic"),
        "getPublic should appear in schema. SDL:\n{}",
        sdl
    );
    assert!(
        sdl.contains("createPublic"),
        "createPublic should appear in schema. SDL:\n{}",
        sdl
    );

    // Skipped methods must NOT appear
    assert!(
        !sdl.contains("getInternal"),
        "getInternal is #[server(skip)] and must not appear in schema. SDL:\n{}",
        sdl
    );
    assert!(
        !sdl.contains("createInternal"),
        "createInternal is #[server(skip)] and must not appear in schema. SDL:\n{}",
        sdl
    );
}

// ============================================================================
// Input Type Tests
// ============================================================================

use server_less::graphql_input;

#[graphql_input]
#[derive(Clone, Debug, Deserialize)]
struct CreateUserInput {
    /// User's name
    name: String,
    /// User's email address
    email: String,
    /// Optional age
    age: Option<i32>,
}

#[derive(Clone)]
struct InputService;

#[graphql(inputs(CreateUserInput))]
impl InputService {
    /// Get service status
    pub fn get_status(&self) -> String {
        "running".to_string()
    }

    /// Create a user
    pub fn create_user(&self, input: CreateUserInput) -> String {
        format!("Created: {} <{}>", input.name, input.email)
    }
}

#[test]
fn test_graphql_input_type_generated() {
    // Verify the input type helper exists
    let input_type = CreateUserInput::__graphql_input_type();
    assert_eq!(input_type.type_name(), "CreateUserInput");
}

#[test]
fn test_graphql_input_schema_registration() {
    let service = InputService;
    let sdl = service.graphql_sdl();

    // Should have input type in schema
    assert!(
        sdl.contains("input CreateUserInput"),
        "Should register CreateUserInput input type. SDL:\n{}",
        sdl
    );

    // Check fields
    assert!(
        sdl.contains("name: String!"),
        "Should have name field. SDL:\n{}",
        sdl
    );
    assert!(
        sdl.contains("email: String!"),
        "Should have email field. SDL:\n{}",
        sdl
    );
    // Optional field should not have !
    assert!(
        sdl.contains("age: Int"),
        "Should have age field. SDL:\n{}",
        sdl
    );
}

// ============================================================================
// Hidden Method Tests (#[server(hidden)])
// ============================================================================

#[derive(Clone)]
struct HiddenGraphqlService;

#[graphql]
impl HiddenGraphqlService {
    /// Public query
    pub fn get_public(&self) -> String {
        "public".to_string()
    }

    /// Hidden query - callable but not in schema SDL
    #[server(hidden)]
    pub fn get_hidden(&self) -> String {
        "hidden".to_string()
    }

    /// Public mutation
    pub fn create_public(&self, name: String) -> String {
        format!("created: {}", name)
    }

    /// Hidden mutation - not in schema SDL
    #[server(hidden)]
    pub fn create_hidden(&self, value: i32) -> i32 {
        value
    }
}

#[test]
fn test_graphql_hidden_method_not_in_sdl() {
    let svc = HiddenGraphqlService;
    let sdl = svc.graphql_sdl();

    // Public methods appear in SDL
    assert!(sdl.contains("getPublic"), "getPublic must appear in SDL");
    assert!(sdl.contains("createPublic"), "createPublic must appear in SDL");

    // Hidden methods do NOT appear in SDL
    assert!(!sdl.contains("getHidden"), "getHidden must not appear in SDL");
    assert!(!sdl.contains("createHidden"), "createHidden must not appear in SDL");
}

#[test]
fn test_graphql_hidden_schema_builds_successfully() {
    let svc = HiddenGraphqlService;
    // Schema must build without errors even with hidden methods
    let schema = svc.graphql_schema();
    let sdl = schema.sdl();
    assert!(!sdl.is_empty());
}

// ============================================================================
// Context Injection Tests
// ============================================================================

/// Service with a Context parameter — context must not appear as a GraphQL field argument.
#[derive(Clone)]
struct ContextGraphqlService;

#[graphql]
impl ContextGraphqlService {
    /// Get greeting using context (context should be invisible to callers)
    pub fn get_greeting(&self, ctx: server_less::Context, name: String) -> String {
        let _ = ctx;
        format!("Hello, {}!", name)
    }

    /// No context — should work normally
    pub fn get_ping(&self) -> String {
        "pong".to_string()
    }
}

#[test]
fn test_graphql_context_param_not_in_sdl() {
    let service = ContextGraphqlService;
    let sdl = service.graphql_sdl();

    // `ctx` must NOT appear as a GraphQL argument in the SDL
    assert!(
        !sdl.contains("ctx:"),
        "Context parameter should not appear in GraphQL SDL, got:\n{}",
        sdl
    );

    // `name` must still be there as a field argument
    assert!(
        sdl.contains("name:"),
        "Regular parameter 'name' should appear in SDL, got:\n{}",
        sdl
    );
}

#[tokio::test]
async fn test_graphql_context_param_method_callable() {
    let service = ContextGraphqlService;
    let schema = service.graphql_schema();

    // Execute without providing ctx — the macro injects it automatically
    let result = schema
        .execute(r#"{ getGreeting(name: "Alice") }"#)
        .await;
    assert!(
        result.errors.is_empty(),
        "Query with context injection should succeed: {:?}",
        result.errors
    );

    let data = result.data.into_json().unwrap();
    assert_eq!(
        data["getGreeting"].as_str(),
        Some("Hello, Alice!"),
        "Should return greeting, got: {:?}",
        data
    );
}

// ============================================================================
// Mount / Composition Tests
//
// A parent service can expose a child service's queries/mutations by returning
// `&ChildService` from a method. The macro inlines all child fields into the
// parent's query/mutation Objects so a single schema contains everything.
// ============================================================================

/// Child service with its own queries and mutations.
#[derive(Clone)]
struct ProductService {
    tax_rate: f64,
}

impl ProductService {
    fn new() -> Self {
        Self { tax_rate: 0.1 }
    }
}

#[graphql]
impl ProductService {
    /// Get product name
    pub fn get_product_name(&self) -> String {
        "Widget".to_string()
    }

    /// Get product price
    pub fn get_product_price(&self) -> i32 {
        100
    }

    /// Create product
    pub fn create_product(&self, name: String) -> String {
        format!("Created: {}", name)
    }
}

/// Parent service that mounts `ProductService` as a child.
#[derive(Clone)]
struct CatalogService {
    product_service: ProductService,
}

impl CatalogService {
    fn new() -> Self {
        Self {
            product_service: ProductService::new(),
        }
    }
}

#[graphql]
impl CatalogService {
    /// Get catalog name
    pub fn get_catalog_name(&self) -> String {
        "Main Catalog".to_string()
    }

    /// Get catalog version
    pub fn get_catalog_version(&self) -> i32 {
        1
    }

    /// Update catalog description
    pub fn update_catalog_description(&self, description: String) -> String {
        format!("Updated: {}", description)
    }

    /// Mount: expose ProductService fields in this schema
    pub fn products(&self) -> &ProductService {
        &self.product_service
    }
}

#[test]
fn test_graphql_mount_schema_created() {
    let service = CatalogService::new();
    let schema = service.graphql_schema();
    let _ = schema;
}

#[test]
fn test_graphql_mount_sdl_contains_parent_fields() {
    let service = CatalogService::new();
    let sdl = service.graphql_sdl();

    // Parent query fields should be present
    assert!(
        sdl.contains("getCatalogName"),
        "SDL should have getCatalogName from parent. SDL:\n{}",
        sdl
    );
    assert!(
        sdl.contains("getCatalogVersion"),
        "SDL should have getCatalogVersion from parent. SDL:\n{}",
        sdl
    );
}

#[test]
fn test_graphql_mount_sdl_contains_child_fields() {
    let service = CatalogService::new();
    let sdl = service.graphql_sdl();

    // Child query fields should be inlined into parent's schema
    assert!(
        sdl.contains("getProductName"),
        "SDL should have getProductName from child ProductService. SDL:\n{}",
        sdl
    );
    assert!(
        sdl.contains("getProductPrice"),
        "SDL should have getProductPrice from child ProductService. SDL:\n{}",
        sdl
    );
}

#[test]
fn test_graphql_mount_sdl_contains_child_mutations() {
    let service = CatalogService::new();
    let sdl = service.graphql_sdl();

    // Child mutation fields should be inlined into parent's mutation type
    assert!(
        sdl.contains("createProduct"),
        "SDL should have createProduct mutation from child ProductService. SDL:\n{}",
        sdl
    );
    // Parent's own mutation should also be present
    assert!(
        sdl.contains("updateCatalogDescription"),
        "SDL should have updateCatalogDescription mutation from parent. SDL:\n{}",
        sdl
    );
}

#[tokio::test]
async fn test_graphql_mount_execute_parent_query() {
    let service = CatalogService::new();
    let schema = service.graphql_schema();

    let result = schema.execute("{ getCatalogName }").await;
    assert!(
        result.errors.is_empty(),
        "Parent query should succeed: {:?}",
        result.errors
    );

    let data = result.data.into_json().unwrap();
    assert_eq!(data["getCatalogName"], "Main Catalog");
}

#[tokio::test]
async fn test_graphql_mount_execute_child_query() {
    let service = CatalogService::new();
    let schema = service.graphql_schema();

    // Child's query field is now accessible directly through the parent schema
    let result = schema.execute("{ getProductName }").await;
    assert!(
        result.errors.is_empty(),
        "Child query through parent schema should succeed: {:?}",
        result.errors
    );

    let data = result.data.into_json().unwrap();
    assert_eq!(data["getProductName"], "Widget");
}

#[tokio::test]
async fn test_graphql_mount_execute_child_query_int() {
    let service = CatalogService::new();
    let schema = service.graphql_schema();

    let result = schema.execute("{ getProductPrice }").await;
    assert!(
        result.errors.is_empty(),
        "Child int query through parent schema should succeed: {:?}",
        result.errors
    );

    let data = result.data.into_json().unwrap();
    assert_eq!(data["getProductPrice"], 100);
}

#[tokio::test]
async fn test_graphql_mount_execute_child_mutation() {
    let service = CatalogService::new();
    let schema = service.graphql_schema();

    let result = schema
        .execute(r#"mutation { createProduct(name: "Gadget") }"#)
        .await;
    assert!(
        result.errors.is_empty(),
        "Child mutation through parent schema should succeed: {:?}",
        result.errors
    );

    let data = result.data.into_json().unwrap();
    assert_eq!(data["createProduct"], "Created: Gadget");
}

#[tokio::test]
async fn test_graphql_mount_execute_parent_mutation() {
    let service = CatalogService::new();
    let schema = service.graphql_schema();

    let result = schema
        .execute(r#"mutation { updateCatalogDescription(description: "New desc") }"#)
        .await;
    assert!(
        result.errors.is_empty(),
        "Parent mutation should succeed: {:?}",
        result.errors
    );

    let data = result.data.into_json().unwrap();
    assert_eq!(data["updateCatalogDescription"], "Updated: New desc");
}

/// Child-only service with queries but no mutations.
#[derive(Clone)]
struct TagService;

#[graphql]
impl TagService {
    /// List all tags
    pub fn list_tags(&self) -> Vec<String> {
        vec!["rust".to_string(), "graphql".to_string()]
    }

    /// Get tag count
    pub fn get_tag_count(&self) -> i32 {
        2
    }
}

/// Parent service that mounts a query-only child (no child mutations).
#[derive(Clone)]
struct BlogService {
    tag_service: TagService,
}

impl BlogService {
    fn new() -> Self {
        Self {
            tag_service: TagService,
        }
    }
}

#[graphql]
impl BlogService {
    /// Get blog title
    pub fn get_blog_title(&self) -> String {
        "My Blog".to_string()
    }

    /// Publish post
    pub fn publish_post(&self, title: String) -> String {
        format!("Published: {}", title)
    }

    /// Mount: expose TagService fields (queries only, no mutations)
    pub fn tags(&self) -> &TagService {
        &self.tag_service
    }
}

#[test]
fn test_graphql_mount_query_only_child_sdl() {
    let service = BlogService::new();
    let sdl = service.graphql_sdl();

    // Both parent and child query fields should be present
    assert!(
        sdl.contains("getBlogTitle"),
        "SDL should have getBlogTitle. SDL:\n{}",
        sdl
    );
    assert!(
        sdl.contains("listTags"),
        "SDL should have listTags from child TagService. SDL:\n{}",
        sdl
    );
    assert!(
        sdl.contains("getTagCount"),
        "SDL should have getTagCount from child TagService. SDL:\n{}",
        sdl
    );
    // Parent mutation should still be present
    assert!(
        sdl.contains("publishPost"),
        "SDL should have publishPost mutation. SDL:\n{}",
        sdl
    );
}

#[tokio::test]
async fn test_graphql_mount_query_only_child_dispatch() {
    let service = BlogService::new();
    let schema = service.graphql_schema();

    let result = schema.execute("{ listTags }").await;
    assert!(
        result.errors.is_empty(),
        "Child list query through parent should succeed: {:?}",
        result.errors
    );

    let data = result.data.into_json().unwrap();
    let tags = data["listTags"].as_array().unwrap();
    assert_eq!(tags.len(), 2);
}

// ============================================================================
// #[serve] + #[graphql] Integration Test
//
// Verifies that a service annotated with both #[graphql] and #[serve(graphql)]
// produces a working axum router that responds to GraphQL introspection queries.
// ============================================================================

use axum::body::Body;
use axum::http::{Request, StatusCode};
use tower::ServiceExt;

#[derive(Clone)]
struct ServeGraphqlService;

#[graphql]
#[serve(graphql)]
impl ServeGraphqlService {
    /// Get server version
    pub fn get_server_version(&self) -> String {
        "1.0.0".to_string()
    }

    /// Ping the server
    pub fn get_ping(&self) -> String {
        "pong".to_string()
    }
}

#[tokio::test]
async fn test_serve_graphql_router_responds() {
    let service = ServeGraphqlService;
    let router = service.router();

    // Send a basic introspection query to the /graphql endpoint
    let query = serde_json::json!({
        "query": "{ __typename }"
    });

    let request = Request::builder()
        .method("POST")
        .uri("/graphql")
        .header("content-type", "application/json")
        .body(Body::from(serde_json::to_string(&query).unwrap()))
        .unwrap();

    let response = router.oneshot(request).await.unwrap();

    assert_eq!(
        response.status(),
        StatusCode::OK,
        "GraphQL endpoint should return 200"
    );
}

#[tokio::test]
async fn test_serve_graphql_introspection_query() {
    let service = ServeGraphqlService;
    let router = service.router();

    let query = serde_json::json!({
        "query": "{ getServerVersion getping: getPing }"
    });

    let request = Request::builder()
        .method("POST")
        .uri("/graphql")
        .header("content-type", "application/json")
        .body(Body::from(serde_json::to_string(&query).unwrap()))
        .unwrap();

    let response = router.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);

    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

    assert!(
        body["errors"].is_null() || body["errors"].as_array().map(|a| a.is_empty()).unwrap_or(true),
        "GraphQL response should have no errors: {}",
        body
    );
    assert!(
        body["data"].is_object(),
        "GraphQL response should have data: {}",
        body
    );
}

#[tokio::test]
async fn test_serve_graphql_health_endpoint() {
    let service = ServeGraphqlService;
    let router = service.router();

    let request = Request::builder()
        .method("GET")
        .uri("/health")
        .body(Body::empty())
        .unwrap();

    let response = router.oneshot(request).await.unwrap();
    assert_eq!(
        response.status(),
        StatusCode::OK,
        "#[serve] health endpoint should respond with 200"
    );
}

#[tokio::test]
async fn test_serve_graphql_openapi_spec() {
    let spec = ServeGraphqlService::openapi_spec();

    // The spec should include the GraphQL endpoint paths
    let paths = &spec["paths"];
    assert!(
        paths.is_object(),
        "OpenAPI spec should have paths. Spec: {}",
        serde_json::to_string_pretty(&spec).unwrap()
    );

    // GraphQL endpoint should be documented
    assert!(
        paths["/graphql"].is_object(),
        "OpenAPI spec should document /graphql endpoint. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );
}