fraiseql-cli 2.0.0-rc.13

CLI tools for FraiseQL v2 - Schema compilation and development utilities
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
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
//! Intermediate Schema Format
//!
//! Language-agnostic schema representation that all language libraries output.
//! See .`claude/INTERMEDIATE_SCHEMA_FORMAT.md` for full specification.

use fraiseql_core::validation::ValidationRule;
use serde::{Deserialize, Serialize};

/// Intermediate schema - universal format from all language libraries
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct IntermediateSchema {
    /// Schema format version
    #[serde(default = "default_version")]
    pub version: String,

    /// GraphQL object types
    #[serde(default)]
    pub types: Vec<IntermediateType>,

    /// GraphQL enum types
    #[serde(default)]
    pub enums: Vec<IntermediateEnum>,

    /// GraphQL input object types
    #[serde(default)]
    pub input_types: Vec<IntermediateInputObject>,

    /// GraphQL interface types (per GraphQL spec §3.7)
    #[serde(default)]
    pub interfaces: Vec<IntermediateInterface>,

    /// GraphQL union types (per GraphQL spec §3.10)
    #[serde(default)]
    pub unions: Vec<IntermediateUnion>,

    /// GraphQL queries
    #[serde(default)]
    pub queries: Vec<IntermediateQuery>,

    /// GraphQL mutations
    #[serde(default)]
    pub mutations: Vec<IntermediateMutation>,

    /// GraphQL subscriptions
    #[serde(default)]
    pub subscriptions: Vec<IntermediateSubscription>,

    /// GraphQL fragments (reusable field selections)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fragments: Option<Vec<IntermediateFragment>>,

    /// GraphQL directive definitions (custom directives)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub directives: Option<Vec<IntermediateDirective>>,

    /// Analytics fact tables (optional)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fact_tables: Option<Vec<IntermediateFactTable>>,

    /// Analytics aggregate queries (optional)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aggregate_queries: Option<Vec<IntermediateAggregateQuery>>,

    /// Observer definitions (database change event listeners)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observers: Option<Vec<IntermediateObserver>>,

    /// Custom scalar type definitions
    ///
    /// Defines custom GraphQL scalar types with validation rules.
    /// Custom scalars can be defined in Python, TypeScript, Java, Go, and Rust SDKs,
    /// and are compiled into the CompiledSchema's CustomTypeRegistry.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub custom_scalars: Option<Vec<IntermediateScalar>>,

    /// Security configuration (from fraiseql.toml)
    /// Compiled from the security section of fraiseql.toml at compile time.
    /// Optional - if not provided, defaults are used.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub security: Option<serde_json::Value>,

    /// Observers/event system configuration (from fraiseql.toml).
    ///
    /// Contains backend connection settings (redis_url, nats_url, etc.) compiled
    /// from the `[observers]` TOML section. Embedded verbatim into the compiled schema.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observers_config: Option<serde_json::Value>,

    /// Federation configuration (from fraiseql.toml).
    ///
    /// Contains Apollo Federation settings and circuit breaker configuration compiled
    /// from the `[federation]` TOML section. Embedded verbatim into the compiled schema.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub federation_config: Option<serde_json::Value>,
}

fn default_version() -> String {
    "2.0.0".to_string()
}

/// Type definition in intermediate format
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateType {
    /// Type name (e.g., "User")
    pub name: String,

    /// Type fields
    pub fields: Vec<IntermediateField>,

    /// Type description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Interfaces this type implements (GraphQL spec §3.6)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub implements: Vec<String>,

    /// Whether this type is a mutation error type (tagged with `@fraiseql.error`).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub is_error: bool,
}

/// Field definition in intermediate format
///
/// **NOTE**: Uses `type` field (not `field_type`)
/// This is the language-agnostic format. Rust conversion happens in converter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateField {
    /// Field name (e.g., "id")
    pub name: String,

    /// Field type name (e.g., "Int", "String", "User")
    ///
    /// **Language-agnostic**: All languages use "type", not "`field_type`"
    #[serde(rename = "type")]
    pub field_type: String,

    /// Is field nullable?
    pub nullable: bool,

    /// Field description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Applied directives (e.g., @deprecated)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub directives: Option<Vec<IntermediateAppliedDirective>>,

    /// Scope required to access this field (field-level access control)
    ///
    /// When set, users must have this scope in their JWT to query this field.
    /// Supports patterns like "read:Type.field" or custom scopes like "hr:view_pii".
    ///
    /// # Example
    ///
    /// ```json
    /// {
    ///   "name": "salary",
    ///   "type": "Int",
    ///   "nullable": false,
    ///   "requires_scope": "read:Employee.salary"
    /// }
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub requires_scope: Option<String>,
}

// =============================================================================
// Enum Definitions
// =============================================================================

/// GraphQL enum type definition in intermediate format.
///
/// Enums represent a finite set of possible values.
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "OrderStatus",
///   "values": [
///     {"name": "PENDING"},
///     {"name": "PROCESSING"},
///     {"name": "SHIPPED", "description": "Package has been shipped"},
///     {"name": "DELIVERED"}
///   ],
///   "description": "Possible states of an order"
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateEnum {
    /// Enum type name (e.g., "OrderStatus")
    pub name: String,

    /// Possible values for this enum
    pub values: Vec<IntermediateEnumValue>,

    /// Enum description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// A single value within an enum type.
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "ACTIVE",
///   "description": "The item is currently active",
///   "deprecated": {"reason": "Use ENABLED instead"}
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateEnumValue {
    /// Value name (e.g., "PENDING")
    pub name: String,

    /// Value description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Deprecation info (if value is deprecated)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<IntermediateDeprecation>,
}

/// Deprecation information for enum values or input fields.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateDeprecation {
    /// Deprecation reason (what to use instead)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

// =============================================================================
// Custom Scalar Definitions
// =============================================================================

/// Custom scalar type definition in intermediate format.
///
/// Custom scalars allow applications to define domain-specific types with validation.
/// Scalars are defined in language SDKs (Python, TypeScript, Java, Go, Rust)
/// and compiled into the schema.
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "Email",
///   "description": "Valid email address",
///   "specified_by_url": "https://tools.ietf.org/html/rfc5322",
///   "base_type": "String",
///   "validation_rules": [
///     {
///       "type": "pattern",
///       "value": {
///         "pattern": "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$"
///       }
///     }
///   ]
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IntermediateScalar {
    /// Scalar name (e.g., "Email", "Phone", "ISBN")
    pub name: String,

    /// Scalar description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// URL to specification/RFC (GraphQL spec §3.5.1)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub specified_by_url: Option<String>,

    /// Built-in validation rules
    #[serde(default)]
    pub validation_rules: Vec<ValidationRule>,

    /// Base type for type aliases (e.g., "String" for Email scalar)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_type: Option<String>,
}

// =============================================================================
// Input Object Definitions
// =============================================================================

/// GraphQL input object type definition in intermediate format.
///
/// Input objects are used for complex query arguments like filters,
/// ordering, and mutation inputs.
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "UserFilter",
///   "fields": [
///     {"name": "name", "type": "String", "nullable": true},
///     {"name": "email", "type": "String", "nullable": true},
///     {"name": "active", "type": "Boolean", "nullable": true, "default": true}
///   ],
///   "description": "Filter criteria for users"
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateInputObject {
    /// Input object type name (e.g., "UserFilter")
    pub name: String,

    /// Input fields
    pub fields: Vec<IntermediateInputField>,

    /// Input type description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// A field within an input object type.
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "email",
///   "type": "String!",
///   "description": "User's email address",
///   "default": "user@example.com"
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateInputField {
    /// Field name
    pub name: String,

    /// Field type name (e.g., `"String!"`, `"[Int]"`, `"UserFilter"`)
    #[serde(rename = "type")]
    pub field_type: String,

    /// Is field nullable?
    #[serde(default)]
    pub nullable: bool,

    /// Field description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Default value (as JSON)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<serde_json::Value>,

    /// Deprecation info (if field is deprecated)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<IntermediateDeprecation>,
}

/// Query definition in intermediate format
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateQuery {
    /// Query name (e.g., "users")
    pub name: String,

    /// Return type name (e.g., "User")
    pub return_type: String,

    /// Returns a list?
    #[serde(default)]
    pub returns_list: bool,

    /// Result is nullable?
    #[serde(default)]
    pub nullable: bool,

    /// Query arguments
    #[serde(default)]
    pub arguments: Vec<IntermediateArgument>,

    /// Query description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// SQL source (table/view name)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sql_source: Option<String>,

    /// Auto-generated parameters config
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_params: Option<IntermediateAutoParams>,

    /// Deprecation info (from @deprecated directive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<IntermediateDeprecation>,

    /// JSONB column name for extracting data (e.g., "data")
    /// Used for tv_* (denormalized JSONB tables) pattern
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jsonb_column: Option<String>,
}

/// Mutation definition in intermediate format
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateMutation {
    /// Mutation name (e.g., "createUser")
    pub name: String,

    /// Return type name (e.g., "User")
    pub return_type: String,

    /// Returns a list?
    #[serde(default)]
    pub returns_list: bool,

    /// Result is nullable?
    #[serde(default)]
    pub nullable: bool,

    /// Mutation arguments
    #[serde(default)]
    pub arguments: Vec<IntermediateArgument>,

    /// Mutation description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// SQL source (function name)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sql_source: Option<String>,

    /// Operation type (CREATE, UPDATE, DELETE, CUSTOM)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operation: Option<String>,

    /// Deprecation info (from @deprecated directive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<IntermediateDeprecation>,
}

// =============================================================================
// Interface Definitions (GraphQL Spec §3.7)
// =============================================================================

/// GraphQL interface type definition in intermediate format.
///
/// Interfaces define a common set of fields that multiple object types can implement.
/// Per GraphQL spec §3.7, interfaces enable polymorphic queries.
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "Node",
///   "fields": [
///     {"name": "id", "type": "ID", "nullable": false}
///   ],
///   "description": "An object with a globally unique ID"
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateInterface {
    /// Interface name (e.g., "Node")
    pub name: String,

    /// Interface fields (all implementing types must have these fields)
    pub fields: Vec<IntermediateField>,

    /// Interface description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Argument definition in intermediate format
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateArgument {
    /// Argument name
    pub name: String,

    /// Argument type name
    ///
    /// **Language-agnostic**: Uses "type", not "`arg_type`"
    #[serde(rename = "type")]
    pub arg_type: String,

    /// Is argument optional?
    pub nullable: bool,

    /// Default value (JSON)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<serde_json::Value>,

    /// Deprecation info (from @deprecated directive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<IntermediateDeprecation>,
}

// =============================================================================
// Union Definitions (GraphQL Spec §3.10)
// =============================================================================

/// GraphQL union type definition in intermediate format.
///
/// Unions represent a type that could be one of several object types.
/// Per GraphQL spec §3.10, unions are abstract types with member types.
/// Unlike interfaces, unions don't define common fields.
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "SearchResult",
///   "member_types": ["User", "Post", "Comment"],
///   "description": "A result from a search query"
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateUnion {
    /// Union type name (e.g., "SearchResult")
    pub name: String,

    /// Member types (object type names that belong to this union)
    pub member_types: Vec<String>,

    /// Union description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Auto-params configuration in intermediate format
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateAutoParams {
    /// Enable automatic limit parameter
    #[serde(default)]
    pub limit:        bool,
    /// Enable automatic offset parameter
    #[serde(default)]
    pub offset:       bool,
    /// Enable automatic where clause parameter
    #[serde(rename = "where", default)]
    pub where_clause: bool,
    /// Enable automatic order_by parameter
    #[serde(default)]
    pub order_by:     bool,
}

// =============================================================================
// Subscription Definitions
// =============================================================================

/// Subscription definition in intermediate format.
///
/// Subscriptions provide real-time event streams for GraphQL clients.
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "orderUpdated",
///   "return_type": "Order",
///   "arguments": [
///     {"name": "orderId", "type": "ID", "nullable": true}
///   ],
///   "topic": "order_events",
///   "filter": {
///     "conditions": [
///       {"argument": "orderId", "path": "$.id"}
///     ]
///   },
///   "description": "Stream of order update events"
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateSubscription {
    /// Subscription name (e.g., "orderUpdated")
    pub name: String,

    /// Return type name (e.g., "Order")
    pub return_type: String,

    /// Subscription arguments (for filtering events)
    #[serde(default)]
    pub arguments: Vec<IntermediateArgument>,

    /// Subscription description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Event topic to subscribe to (e.g., "order_events")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub topic: Option<String>,

    /// Filter configuration for event matching
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter: Option<IntermediateSubscriptionFilter>,

    /// Fields to project from event data
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fields: Vec<String>,

    /// Deprecation info (from @deprecated directive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<IntermediateDeprecation>,
}

/// Subscription filter definition for event matching.
///
/// Maps subscription arguments to JSONB paths in event data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateSubscriptionFilter {
    /// Filter conditions mapping arguments to event data paths
    pub conditions: Vec<IntermediateFilterCondition>,
}

/// A single filter condition for subscription event matching.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateFilterCondition {
    /// Argument name from subscription arguments
    pub argument: String,

    /// JSON path to the value in event data (e.g., "$.id", "$.order_status")
    pub path: String,
}

// =============================================================================
// Fragment and Directive Definitions (GraphQL Spec §2.9-2.12)
// =============================================================================

/// Fragment definition in intermediate format.
///
/// Fragments are reusable field selections that can be spread into queries.
/// Per GraphQL spec §2.9-2.10, fragments have a type condition and field list.
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "UserFields",
///   "on": "User",
///   "fields": ["id", "name", "email"]
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateFragment {
    /// Fragment name (e.g., "UserFields")
    pub name: String,

    /// Type condition - the type this fragment applies to (e.g., "User")
    #[serde(rename = "on")]
    pub type_condition: String,

    /// Fields to select (can be field names or nested fragment spreads)
    pub fields: Vec<IntermediateFragmentField>,

    /// Fragment description (from docstring)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Fragment field selection - either a simple field or a nested object/fragment spread.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum IntermediateFragmentField {
    /// Simple field name (e.g., "id", "name")
    Simple(String),

    /// Complex field with nested selections or directives
    Complex(IntermediateFragmentFieldDef),
}

/// Complex fragment field definition with optional alias, directives, and nested fields.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateFragmentFieldDef {
    /// Field name (source field in the type)
    pub name: String,

    /// Output alias (optional, per GraphQL spec §2.13)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alias: Option<String>,

    /// Nested field selections (for object fields)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fields: Option<Vec<IntermediateFragmentField>>,

    /// Fragment spread (e.g., "...UserFields")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub spread: Option<String>,

    /// Applied directives (e.g., @skip, @include)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub directives: Option<Vec<IntermediateAppliedDirective>>,
}

/// Directive definition in intermediate format.
///
/// Directives provide a way to describe alternate runtime execution and type validation.
/// Per GraphQL spec §2.12, directives can be applied to various locations.
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "auth",
///   "locations": ["FIELD_DEFINITION", "OBJECT"],
///   "arguments": [{"name": "role", "type": "String", "nullable": false}],
///   "description": "Requires authentication with specified role"
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateDirective {
    /// Directive name (without @, e.g., "auth", "deprecated")
    pub name: String,

    /// Valid locations where this directive can be applied
    pub locations: Vec<String>,

    /// Directive arguments
    #[serde(default)]
    pub arguments: Vec<IntermediateArgument>,

    /// Whether the directive can be applied multiple times
    #[serde(default)]
    pub repeatable: bool,

    /// Directive description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// An applied directive instance (used on fields, types, etc.).
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "skip",
///   "arguments": {"if": true}
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateAppliedDirective {
    /// Directive name (without @)
    pub name: String,

    /// Directive arguments as key-value pairs
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub arguments: Option<serde_json::Value>,
}

// =============================================================================
// Analytics Definitions
// =============================================================================

/// Fact table definition in intermediate format (Analytics)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateFactTable {
    /// Name of the fact table
    pub table_name:           String,
    /// Measure columns (numeric aggregates)
    pub measures:             Vec<IntermediateMeasure>,
    /// Dimension metadata
    pub dimensions:           IntermediateDimensions,
    /// Denormalized filter columns
    pub denormalized_filters: Vec<IntermediateFilter>,
}

/// Measure column definition
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateMeasure {
    /// Measure column name
    pub name:     String,
    /// SQL data type of the measure
    pub sql_type: String,
    /// Whether the column can be NULL
    pub nullable: bool,
}

/// Dimensions metadata
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateDimensions {
    /// Dimension name
    pub name:  String,
    /// Paths to dimension fields within JSONB
    pub paths: Vec<IntermediateDimensionPath>,
}

/// Dimension path within JSONB
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateDimensionPath {
    /// Path name identifier
    pub name:      String,
    /// JSON path (accepts both "`json_path`" and "path" for cross-language compat)
    #[serde(alias = "path")]
    pub json_path: String,
    /// Data type (accepts both "`data_type`" and "type" for cross-language compat)
    #[serde(alias = "type")]
    pub data_type: String,
}

/// Denormalized filter column
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateFilter {
    /// Filter column name
    pub name:     String,
    /// SQL data type of the filter
    pub sql_type: String,
    /// Whether this column should be indexed
    pub indexed:  bool,
}

/// Aggregate query definition (Analytics)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateAggregateQuery {
    /// Aggregate query name
    pub name:            String,
    /// Fact table to aggregate from
    pub fact_table:      String,
    /// Automatically generate GROUP BY clauses
    pub auto_group_by:   bool,
    /// Automatically generate aggregate functions
    pub auto_aggregates: bool,
    /// Optional description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description:     Option<String>,
}

// =============================================================================
// Observer Definitions
// =============================================================================

/// Observer definition in intermediate format.
///
/// Observers listen to database change events (INSERT/UPDATE/DELETE) and execute
/// actions (webhooks, Slack, email) when conditions are met.
///
/// # Example JSON
///
/// ```json
/// {
///   "name": "onHighValueOrder",
///   "entity": "Order",
///   "event": "INSERT",
///   "condition": "total > 1000",
///   "actions": [
///     {
///       "type": "webhook",
///       "url": "https://api.example.com/orders",
///       "headers": {"Content-Type": "application/json"}
///     },
///     {
///       "type": "slack",
///       "channel": "#sales",
///       "message": "New order: {id}",
///       "webhook_url_env": "SLACK_WEBHOOK_URL"
///     }
///   ],
///   "retry": {
///     "max_attempts": 3,
///     "backoff_strategy": "exponential",
///     "initial_delay_ms": 100,
///     "max_delay_ms": 60000
///   }
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IntermediateObserver {
    /// Observer name (unique identifier)
    pub name: String,

    /// Entity type to observe (e.g., "Order", "User")
    pub entity: String,

    /// Event type: INSERT, UPDATE, or DELETE
    pub event: String,

    /// Actions to execute when observer triggers
    pub actions: Vec<IntermediateObserverAction>,

    /// Optional condition expression in FraiseQL DSL
    #[serde(skip_serializing_if = "Option::is_none")]
    pub condition: Option<String>,

    /// Retry configuration for action execution
    pub retry: IntermediateRetryConfig,
}

/// Observer action (webhook, Slack, email, etc.).
///
/// Actions are stored as flexible JSON objects since they have different
/// structures based on action type.
pub type IntermediateObserverAction = serde_json::Value;

/// Retry configuration for observer actions.
///
/// # Example JSON
///
/// ```json
/// {
///   "max_attempts": 5,
///   "backoff_strategy": "exponential",
///   "initial_delay_ms": 100,
///   "max_delay_ms": 60000
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateRetryConfig {
    /// Maximum number of retry attempts
    pub max_attempts: u32,

    /// Backoff strategy: exponential, linear, or fixed
    pub backoff_strategy: String,

    /// Initial delay in milliseconds
    pub initial_delay_ms: u32,

    /// Maximum delay in milliseconds
    pub max_delay_ms: u32,
}

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

    #[test]
    fn test_parse_minimal_schema() {
        let json = r#"{
            "types": [],
            "queries": [],
            "mutations": []
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.version, "2.0.0");
        assert_eq!(schema.types.len(), 0);
        assert_eq!(schema.queries.len(), 0);
        assert_eq!(schema.mutations.len(), 0);
    }

    #[test]
    fn test_parse_type_with_type_field() {
        let json = r#"{
            "types": [{
                "name": "User",
                "fields": [
                    {
                        "name": "id",
                        "type": "Int",
                        "nullable": false
                    },
                    {
                        "name": "name",
                        "type": "String",
                        "nullable": false
                    }
                ]
            }],
            "queries": [],
            "mutations": []
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.types.len(), 1);
        assert_eq!(schema.types[0].name, "User");
        assert_eq!(schema.types[0].fields.len(), 2);
        assert_eq!(schema.types[0].fields[0].name, "id");
        assert_eq!(schema.types[0].fields[0].field_type, "Int");
        assert!(!schema.types[0].fields[0].nullable);
    }

    #[test]
    fn test_parse_query_with_arguments() {
        let json = r#"{
            "types": [],
            "queries": [{
                "name": "users",
                "return_type": "User",
                "returns_list": true,
                "nullable": false,
                "arguments": [
                    {
                        "name": "limit",
                        "type": "Int",
                        "nullable": false,
                        "default": 10
                    }
                ],
                "sql_source": "v_user"
            }],
            "mutations": []
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.queries.len(), 1);
        assert_eq!(schema.queries[0].arguments.len(), 1);
        assert_eq!(schema.queries[0].arguments[0].arg_type, "Int");
        assert_eq!(schema.queries[0].arguments[0].default, Some(serde_json::json!(10)));
    }

    #[test]
    fn test_parse_fragment_simple() {
        let json = r#"{
            "types": [],
            "queries": [],
            "mutations": [],
            "fragments": [{
                "name": "UserFields",
                "on": "User",
                "fields": ["id", "name", "email"]
            }]
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        assert!(schema.fragments.is_some());
        let fragments = schema.fragments.unwrap();
        assert_eq!(fragments.len(), 1);
        assert_eq!(fragments[0].name, "UserFields");
        assert_eq!(fragments[0].type_condition, "User");
        assert_eq!(fragments[0].fields.len(), 3);

        // Check simple fields
        match &fragments[0].fields[0] {
            IntermediateFragmentField::Simple(name) => assert_eq!(name, "id"),
            IntermediateFragmentField::Complex(_) => panic!("Expected simple field"),
        }
    }

    #[test]
    fn test_parse_fragment_with_nested_fields() {
        let json = r#"{
            "types": [],
            "queries": [],
            "mutations": [],
            "fragments": [{
                "name": "PostFields",
                "on": "Post",
                "fields": [
                    "id",
                    "title",
                    {
                        "name": "author",
                        "alias": "writer",
                        "fields": ["id", "name"]
                    }
                ]
            }]
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        let fragments = schema.fragments.unwrap();
        assert_eq!(fragments[0].fields.len(), 3);

        // Check nested field
        match &fragments[0].fields[2] {
            IntermediateFragmentField::Complex(def) => {
                assert_eq!(def.name, "author");
                assert_eq!(def.alias, Some("writer".to_string()));
                assert!(def.fields.is_some());
                assert_eq!(def.fields.as_ref().unwrap().len(), 2);
            },
            IntermediateFragmentField::Simple(_) => panic!("Expected complex field"),
        }
    }

    #[test]
    fn test_parse_directive_definition() {
        let json = r#"{
            "types": [],
            "queries": [],
            "mutations": [],
            "directives": [{
                "name": "auth",
                "locations": ["FIELD_DEFINITION", "OBJECT"],
                "arguments": [
                    {"name": "role", "type": "String", "nullable": false}
                ],
                "description": "Requires authentication"
            }]
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        assert!(schema.directives.is_some());
        let directives = schema.directives.unwrap();
        assert_eq!(directives.len(), 1);
        assert_eq!(directives[0].name, "auth");
        assert_eq!(directives[0].locations, vec!["FIELD_DEFINITION", "OBJECT"]);
        assert_eq!(directives[0].arguments.len(), 1);
        assert_eq!(directives[0].description, Some("Requires authentication".to_string()));
    }

    #[test]
    fn test_parse_field_with_directive() {
        let json = r#"{
            "types": [{
                "name": "User",
                "fields": [
                    {
                        "name": "oldId",
                        "type": "Int",
                        "nullable": false,
                        "directives": [
                            {"name": "deprecated", "arguments": {"reason": "Use 'id' instead"}}
                        ]
                    }
                ]
            }],
            "queries": [],
            "mutations": []
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        let field = &schema.types[0].fields[0];
        assert_eq!(field.name, "oldId");
        assert!(field.directives.is_some());
        let directives = field.directives.as_ref().unwrap();
        assert_eq!(directives.len(), 1);
        assert_eq!(directives[0].name, "deprecated");
        assert_eq!(
            directives[0].arguments,
            Some(serde_json::json!({"reason": "Use 'id' instead"}))
        );
    }

    #[test]
    fn test_parse_fragment_with_spread() {
        let json = r#"{
            "types": [],
            "queries": [],
            "mutations": [],
            "fragments": [
                {
                    "name": "UserFields",
                    "on": "User",
                    "fields": ["id", "name"]
                },
                {
                    "name": "PostWithAuthor",
                    "on": "Post",
                    "fields": [
                        "id",
                        "title",
                        {
                            "name": "author",
                            "spread": "UserFields"
                        }
                    ]
                }
            ]
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        let fragments = schema.fragments.unwrap();
        assert_eq!(fragments.len(), 2);

        // Check the spread reference
        match &fragments[1].fields[2] {
            IntermediateFragmentField::Complex(def) => {
                assert_eq!(def.name, "author");
                assert_eq!(def.spread, Some("UserFields".to_string()));
            },
            IntermediateFragmentField::Simple(_) => panic!("Expected complex field"),
        }
    }

    #[test]
    fn test_parse_enum() {
        let json = r#"{
            "types": [],
            "queries": [],
            "mutations": [],
            "enums": [{
                "name": "OrderStatus",
                "values": [
                    {"name": "PENDING"},
                    {"name": "PROCESSING", "description": "Currently being processed"},
                    {"name": "SHIPPED"},
                    {"name": "DELIVERED"}
                ],
                "description": "Possible states of an order"
            }]
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.enums.len(), 1);
        let enum_def = &schema.enums[0];
        assert_eq!(enum_def.name, "OrderStatus");
        assert_eq!(enum_def.description, Some("Possible states of an order".to_string()));
        assert_eq!(enum_def.values.len(), 4);
        assert_eq!(enum_def.values[0].name, "PENDING");
        assert_eq!(enum_def.values[1].description, Some("Currently being processed".to_string()));
    }

    #[test]
    fn test_parse_enum_with_deprecated_value() {
        let json = r#"{
            "types": [],
            "queries": [],
            "mutations": [],
            "enums": [{
                "name": "UserRole",
                "values": [
                    {"name": "ADMIN"},
                    {"name": "USER"},
                    {"name": "GUEST", "deprecated": {"reason": "Use USER with limited permissions instead"}}
                ]
            }]
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        let enum_def = &schema.enums[0];
        assert_eq!(enum_def.values.len(), 3);

        // Check deprecated value
        let guest = &enum_def.values[2];
        assert_eq!(guest.name, "GUEST");
        assert!(guest.deprecated.is_some());
        assert_eq!(
            guest.deprecated.as_ref().unwrap().reason,
            Some("Use USER with limited permissions instead".to_string())
        );
    }

    #[test]
    fn test_parse_input_object() {
        let json = r#"{
            "types": [],
            "queries": [],
            "mutations": [],
            "input_types": [{
                "name": "UserFilter",
                "fields": [
                    {"name": "name", "type": "String", "nullable": true},
                    {"name": "email", "type": "String", "nullable": true},
                    {"name": "active", "type": "Boolean", "nullable": true, "default": true}
                ],
                "description": "Filter criteria for users"
            }]
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.input_types.len(), 1);
        let input = &schema.input_types[0];
        assert_eq!(input.name, "UserFilter");
        assert_eq!(input.description, Some("Filter criteria for users".to_string()));
        assert_eq!(input.fields.len(), 3);

        // Check fields
        assert_eq!(input.fields[0].name, "name");
        assert_eq!(input.fields[0].field_type, "String");
        assert!(input.fields[0].nullable);

        // Check default value
        assert_eq!(input.fields[2].name, "active");
        assert_eq!(input.fields[2].default, Some(serde_json::json!(true)));
    }

    #[test]
    fn test_parse_interface() {
        let json = r#"{
            "types": [],
            "queries": [],
            "mutations": [],
            "interfaces": [{
                "name": "Node",
                "fields": [
                    {"name": "id", "type": "ID", "nullable": false}
                ],
                "description": "An object with a globally unique ID"
            }]
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.interfaces.len(), 1);
        let interface = &schema.interfaces[0];
        assert_eq!(interface.name, "Node");
        assert_eq!(interface.description, Some("An object with a globally unique ID".to_string()));
        assert_eq!(interface.fields.len(), 1);
        assert_eq!(interface.fields[0].name, "id");
        assert_eq!(interface.fields[0].field_type, "ID");
        assert!(!interface.fields[0].nullable);
    }

    #[test]
    fn test_parse_type_implements_interface() {
        let json = r#"{
            "types": [{
                "name": "User",
                "fields": [
                    {"name": "id", "type": "ID", "nullable": false},
                    {"name": "name", "type": "String", "nullable": false}
                ],
                "implements": ["Node"]
            }],
            "queries": [],
            "mutations": [],
            "interfaces": [{
                "name": "Node",
                "fields": [
                    {"name": "id", "type": "ID", "nullable": false}
                ]
            }]
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.types.len(), 1);
        assert_eq!(schema.types[0].name, "User");
        assert_eq!(schema.types[0].implements, vec!["Node"]);

        assert_eq!(schema.interfaces.len(), 1);
        assert_eq!(schema.interfaces[0].name, "Node");
    }

    #[test]
    fn test_parse_input_object_with_deprecated_field() {
        let json = r#"{
            "types": [],
            "queries": [],
            "mutations": [],
            "input_types": [{
                "name": "CreateUserInput",
                "fields": [
                    {"name": "email", "type": "String!", "nullable": false},
                    {"name": "name", "type": "String!", "nullable": false},
                    {
                        "name": "username",
                        "type": "String",
                        "nullable": true,
                        "deprecated": {"reason": "Use email as unique identifier instead"}
                    }
                ]
            }]
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        let input = &schema.input_types[0];

        // Check deprecated field
        let username_field = &input.fields[2];
        assert_eq!(username_field.name, "username");
        assert!(username_field.deprecated.is_some());
        assert_eq!(
            username_field.deprecated.as_ref().unwrap().reason,
            Some("Use email as unique identifier instead".to_string())
        );
    }

    #[test]
    fn test_parse_union() {
        let json = r#"{
            "types": [
                {"name": "User", "fields": [{"name": "id", "type": "ID", "nullable": false}]},
                {"name": "Post", "fields": [{"name": "id", "type": "ID", "nullable": false}]}
            ],
            "queries": [],
            "mutations": [],
            "unions": [{
                "name": "SearchResult",
                "member_types": ["User", "Post"],
                "description": "Result from a search query"
            }]
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.unions.len(), 1);
        let union_def = &schema.unions[0];
        assert_eq!(union_def.name, "SearchResult");
        assert_eq!(union_def.member_types, vec!["User", "Post"]);
        assert_eq!(union_def.description, Some("Result from a search query".to_string()));
    }

    #[test]
    fn test_parse_field_with_requires_scope() {
        let json = r#"{
            "types": [{
                "name": "Employee",
                "fields": [
                    {
                        "name": "id",
                        "type": "ID",
                        "nullable": false
                    },
                    {
                        "name": "name",
                        "type": "String",
                        "nullable": false
                    },
                    {
                        "name": "salary",
                        "type": "Float",
                        "nullable": false,
                        "description": "Employee salary - protected field",
                        "requires_scope": "read:Employee.salary"
                    },
                    {
                        "name": "ssn",
                        "type": "String",
                        "nullable": true,
                        "description": "Social Security Number",
                        "requires_scope": "admin"
                    }
                ]
            }],
            "queries": [],
            "mutations": []
        }"#;

        let schema: IntermediateSchema = serde_json::from_str(json).unwrap();
        assert_eq!(schema.types.len(), 1);

        let employee = &schema.types[0];
        assert_eq!(employee.name, "Employee");
        assert_eq!(employee.fields.len(), 4);

        // id - no scope required
        assert_eq!(employee.fields[0].name, "id");
        assert!(employee.fields[0].requires_scope.is_none());

        // name - no scope required
        assert_eq!(employee.fields[1].name, "name");
        assert!(employee.fields[1].requires_scope.is_none());

        // salary - requires specific scope
        assert_eq!(employee.fields[2].name, "salary");
        assert_eq!(employee.fields[2].requires_scope, Some("read:Employee.salary".to_string()));

        // ssn - requires admin scope
        assert_eq!(employee.fields[3].name, "ssn");
        assert_eq!(employee.fields[3].requires_scope, Some("admin".to_string()));
    }
}