iac-forge 0.1.6

Platform-independent infrastructure-as-code generator from OpenAPI specs
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
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

/// Platform-independent type representation.
///
/// Richer than any single platform's type system -- preserves Object structure
/// and Enum values needed by Pulumi schemas, Crossplane CRDs, etc.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum IacType {
    String,
    Integer,
    Float,
    /// Platform-independent numeric type.
    ///
    /// Terraform's `number` type accepts both integers and floats. This variant
    /// preserves that ambiguity rather than forcing a choice between `Integer`
    /// and `Float` at schema-import time.
    Numeric,
    Boolean,
    List(Box<IacType>),
    Set(Box<IacType>),
    Map(Box<IacType>),
    Object {
        name: String,
        fields: Vec<IacAttribute>,
    },
    /// Enum constraint wrapping an underlying type.
    ///
    /// `values` lists the allowed enum variants. `underlying` is the base type
    /// (typically `IacType::String`).
    Enum {
        values: Vec<String>,
        underlying: Box<IacType>,
    },
    Any,
}

impl IacType {
    /// Whether this type is a scalar (String, Integer, Float, Numeric, Boolean).
    #[must_use]
    pub fn is_scalar(&self) -> bool {
        matches!(
            self,
            Self::String | Self::Integer | Self::Float | Self::Numeric | Self::Boolean
        )
    }

    /// Whether this type is a composite (List, Set, Map, Object).
    #[must_use]
    pub fn is_composite(&self) -> bool {
        matches!(
            self,
            Self::List(_) | Self::Set(_) | Self::Map(_) | Self::Object { .. }
        )
    }

    /// Returns the inner (element) type for container types.
    ///
    /// - `List(T)` → `Some(&T)`
    /// - `Set(T)` → `Some(&T)`
    /// - `Map(T)` → `Some(&T)` (value type; keys are always strings)
    /// - `Enum { underlying, .. }` → `Some(&underlying)`
    /// - All others → `None`
    #[must_use]
    pub fn inner_type(&self) -> Option<&IacType> {
        match self {
            Self::List(inner) | Self::Set(inner) | Self::Map(inner) => Some(inner),
            Self::Enum { underlying, .. } => Some(underlying),
            _ => None,
        }
    }
}

impl std::fmt::Display for IacType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::String => write!(f, "string"),
            Self::Integer => write!(f, "integer"),
            Self::Float => write!(f, "float"),
            Self::Numeric => write!(f, "numeric"),
            Self::Boolean => write!(f, "boolean"),
            Self::List(inner) => write!(f, "list<{inner}>"),
            Self::Set(inner) => write!(f, "set<{inner}>"),
            Self::Map(inner) => write!(f, "map<string, {inner}>"),
            Self::Object { name, .. } => write!(f, "object<{name}>"),
            Self::Enum { underlying, .. } => write!(f, "enum<{underlying}>"),
            Self::Any => write!(f, "any"),
        }
    }
}

/// A resolved attribute in the platform-independent IR.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct IacAttribute {
    /// Original API field name (e.g., "bound-aws-account-id").
    pub api_name: String,
    /// Normalized name with underscores (e.g., `bound_aws_account_id`).
    pub canonical_name: String,
    /// Human-readable description.
    pub description: String,
    /// Platform-independent type.
    pub iac_type: IacType,
    /// Whether the field is required on create.
    pub required: bool,
    /// Whether the field is optional (user can set it, but it is not required).
    ///
    /// In Terraform schema terms:
    /// - `optional: true, computed: false` — user can set, no server default
    /// - `optional: true, computed: true`  — user can set, server has default
    /// - `optional: false, computed: true` — purely server-generated
    #[serde(default)]
    pub optional: bool,
    /// Whether the field is computed (server-side generated).
    pub computed: bool,
    /// Whether the field contains sensitive data.
    pub sensitive: bool,
    /// Whether the field value is a JSON-encoded string.
    ///
    /// When `true`, the underlying Terraform type is still `String`, but the
    /// value carries structured JSON (e.g., IAM policy documents). Code
    /// generators can use this to accept both `String` and `Hash` inputs.
    #[serde(default)]
    pub json_encoded: bool,
    /// Whether changing this field forces resource replacement.
    pub immutable: bool,
    /// Default value, if any.
    pub default_value: Option<serde_json::Value>,
    /// Enum constraint values, if any.
    pub enum_values: Option<Vec<String>>,
    /// JSON path in API response for reading this field back
    /// (e.g., `item_name` maps to the API response key).
    pub read_path: Option<String>,
    /// Whether this field exists only in the update schema (not in create).
    pub update_only: bool,
}

impl Default for IacAttribute {
    fn default() -> Self {
        Self {
            api_name: String::new(),
            canonical_name: String::new(),
            description: String::new(),
            iac_type: IacType::String,
            required: false,
            optional: false,
            computed: false,
            sensitive: false,
            json_encoded: false,
            immutable: false,
            default_value: None,
            enum_values: None,
            read_path: None,
            update_only: false,
        }
    }
}

impl IacAttribute {
    /// Whether this attribute is a user-provided input.
    ///
    /// An attribute is an input if it is required, optional, or not computed.
    /// Purely computed attributes (computed=true, optional=false, required=false)
    /// are excluded.
    #[must_use]
    pub fn is_input(&self) -> bool {
        self.required || self.optional || !self.computed
    }

    /// Whether this attribute appears in the output/state.
    ///
    /// An attribute is an output if it is computed or required.
    #[must_use]
    pub fn is_output(&self) -> bool {
        self.computed || self.required
    }
}

impl std::fmt::Display for IacAttribute {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}: {} ({})",
            self.canonical_name,
            self.iac_type,
            if self.required {
                "required"
            } else {
                "optional"
            }
        )
    }
}

/// CRUD endpoint information for a resource.
///
/// Each field maps to an API endpoint path and its corresponding `OpenAPI` schema
/// name used for request/response serialization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrudInfo {
    /// API path for the create operation (e.g., "/create-secret").
    pub create_endpoint: String,
    /// `OpenAPI` schema name for the create request body.
    pub create_schema: String,
    /// API path for the update operation, if separate from create.
    pub update_endpoint: Option<String>,
    /// `OpenAPI` schema name for the update request body.
    pub update_schema: Option<String>,
    /// API path for the read operation.
    pub read_endpoint: String,
    /// `OpenAPI` schema name for the read request body.
    pub read_schema: String,
    /// `OpenAPI` schema name for the read response, if different from the request.
    pub read_response_schema: Option<String>,
    /// API path for the delete operation.
    pub delete_endpoint: String,
    /// `OpenAPI` schema name for the delete request body.
    pub delete_schema: String,
}

impl From<&crate::spec::CrudMapping> for CrudInfo {
    fn from(crud: &crate::spec::CrudMapping) -> Self {
        Self {
            create_endpoint: crud.create_endpoint.clone(),
            create_schema: crud.create_schema.clone(),
            update_endpoint: crud.update_endpoint.clone(),
            update_schema: crud.update_schema.clone(),
            read_endpoint: crud.read_endpoint.clone(),
            read_schema: crud.read_schema.clone(),
            read_response_schema: crud.read_response_schema.clone(),
            delete_endpoint: crud.delete_endpoint.clone(),
            delete_schema: crud.delete_schema.clone(),
        }
    }
}

/// Identity and import configuration for a resource.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IdentityInfo {
    /// Primary identifier field name (e.g., "name" or "id").
    pub id_field: String,
    /// Field used for Terraform import (defaults to `id_field`).
    pub import_field: String,
    /// Fields that force resource replacement when changed.
    pub force_replace_fields: Vec<String>,
}

impl From<&crate::spec::IdentityConfig> for IdentityInfo {
    fn from(config: &crate::spec::IdentityConfig) -> Self {
        Self {
            id_field: config.id_field.clone(),
            import_field: config
                .import_field
                .clone()
                .unwrap_or_else(|| config.id_field.clone()),
            force_replace_fields: config.force_new_fields.clone(),
        }
    }
}

/// Common attribute queries shared by both resources and data sources.
///
/// Provides default implementations for filtering attributes by various
/// properties. Implementors only need to supply `attributes()`.
pub trait HasAttributes {
    /// The full list of attributes on this IR type.
    fn attributes(&self) -> &[IacAttribute];

    /// Attributes that are user-provided inputs (not purely computed).
    ///
    /// Includes required, optional, and optional+computed attributes.
    /// Excludes purely computed attributes (computed=true, optional=false, required=false).
    #[must_use]
    fn input_attributes(&self) -> Vec<&IacAttribute> {
        self.attributes().iter().filter(|a| a.is_input()).collect()
    }

    /// Attributes that appear in the output/state (computed or required).
    #[must_use]
    fn output_attributes(&self) -> Vec<&IacAttribute> {
        self.attributes().iter().filter(|a| a.is_output()).collect()
    }

    /// Required attribute canonical names.
    #[must_use]
    fn required_attribute_names(&self) -> Vec<&str> {
        self.attributes()
            .iter()
            .filter(|a| a.required)
            .map(|a| a.canonical_name.as_str())
            .collect()
    }

    /// Sensitive attribute canonical names.
    #[must_use]
    fn sensitive_attribute_names(&self) -> Vec<&str> {
        self.attributes()
            .iter()
            .filter(|a| a.sensitive)
            .map(|a| a.canonical_name.as_str())
            .collect()
    }
}

/// A fully resolved resource in the platform-independent IR.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IacResource {
    pub name: String,
    pub description: String,
    pub category: String,
    pub crud: CrudInfo,
    pub attributes: Vec<IacAttribute>,
    pub identity: IdentityInfo,
    /// Mapping from API response JSON paths to canonical field names.
    ///
    /// Direction matches the TOML source: `json_response_key -> canonical_param_name`.
    /// Used by backends to render an honest diff during update against a read response.
    #[serde(default)]
    pub read_mapping: std::collections::BTreeMap<String, String>,
}

impl std::fmt::Display for IacResource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "resource<{}> ({} attrs)",
            self.name,
            self.attributes.len()
        )
    }
}

impl HasAttributes for IacResource {
    fn attributes(&self) -> &[IacAttribute] {
        &self.attributes
    }
}

impl IacResource {
    /// Immutable attribute canonical names.
    #[must_use]
    pub fn immutable_attribute_names(&self) -> Vec<&str> {
        self.attributes
            .iter()
            .filter(|a| a.immutable)
            .map(|a| a.canonical_name.as_str())
            .collect()
    }
}

/// A fully resolved RPC-style action in the platform-independent IR.
///
/// Actions are one-shot calls without create/read/update/delete semantics —
/// e.g. `/uid-generate-token`, `/encrypt`, `/revoke-certificate`. Each
/// action carries enough metadata for backends to emit an Ansible action
/// module, a Terraform `*_action` resource, or any other one-shot wrapper.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IacAction {
    /// Action identifier (e.g., `akeyless_uid_generate_token`).
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// Category grouping (e.g., `"uid"`, `"crypto"`).
    pub category: String,
    /// API path (e.g., `/uid-generate-token`).
    pub endpoint: String,
    /// Request `OpenAPI` schema name (camelCase form).
    pub schema: String,
    /// Optional response schema name.
    pub response_schema: Option<String>,
    /// Whether the action mutates server state.
    ///
    /// Used by backends to decide whether to flag `changed=true` (Ansible)
    /// or run the call inside a transaction (Terraform). Defaults to
    /// `true` when the spec leaves it unspecified.
    pub mutating: bool,
    /// Response fields whose values should be masked (`***`) before being
    /// echoed back to the user.
    pub sensitive_response_fields: Vec<String>,
    /// Resolved input attributes (request body fields).
    pub attributes: Vec<IacAttribute>,
    /// Optional SDK method-name override.
    ///
    /// When `None`, backends derive the method from `schema`. When
    /// `Some(name)`, they should use `name` verbatim. Used for batch
    /// endpoints where the request body schema (e.g.
    /// `BatchEncryptionRequestLine`) doesn't match the SDK method
    /// (e.g. `encrypt_batch`).
    #[serde(default)]
    pub sdk_method: Option<String>,
}

impl std::fmt::Display for IacAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "action<{}> {} ({} attrs)",
            self.name,
            self.endpoint,
            self.attributes.len()
        )
    }
}

impl HasAttributes for IacAction {
    fn attributes(&self) -> &[IacAttribute] {
        &self.attributes
    }
}

/// A fully resolved data source in the platform-independent IR.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IacDataSource {
    pub name: String,
    pub description: String,
    pub read_endpoint: String,
    pub read_schema: String,
    pub read_response_schema: Option<String>,
    pub attributes: Vec<IacAttribute>,
    /// Mapping from API response JSON paths to canonical field names.
    ///
    /// Direction matches the TOML source: `json_response_key -> canonical_param_name`.
    #[serde(default)]
    pub read_mapping: std::collections::BTreeMap<String, String>,
}

impl std::fmt::Display for IacDataSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "data_source<{}> ({} attrs)",
            self.name,
            self.attributes.len()
        )
    }
}

impl HasAttributes for IacDataSource {
    fn attributes(&self) -> &[IacAttribute] {
        &self.attributes
    }
}

impl IacDataSource {
    /// Computed attribute names.
    #[must_use]
    pub fn computed_attribute_names(&self) -> Vec<&str> {
        self.attributes
            .iter()
            .filter(|a| a.computed)
            .map(|a| a.canonical_name.as_str())
            .collect()
    }
}

/// Provider-level configuration in the platform-independent IR.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IacProvider {
    pub name: String,
    pub description: String,
    pub version: String,
    pub auth: AuthInfo,
    pub skip_fields: Vec<String>,
    pub platform_config: BTreeMap<String, toml::Value>,
}

/// Authentication configuration for a provider.
///
/// Empty strings mean "not configured". Use the `has_token()` and
/// `has_gateway()` helpers to check.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuthInfo {
    /// API field name for the authentication token (e.g., "token").
    pub token_field: String,
    /// Environment variable that supplies the token (e.g., `AKEYLESS_ACCESS_TOKEN`).
    pub env_var: String,
    /// API field name for the gateway URL (e.g., `api_gateway_address`).
    pub gateway_url_field: String,
    /// Environment variable that supplies the gateway URL (e.g., `AKEYLESS_GATEWAY`).
    pub gateway_env_var: String,
}

impl From<&crate::spec::AuthConfig> for AuthInfo {
    fn from(auth: &crate::spec::AuthConfig) -> Self {
        Self {
            token_field: auth.token_field.clone(),
            env_var: auth.env_var.clone(),
            gateway_url_field: auth.gateway_url_field.clone(),
            gateway_env_var: auth.gateway_env_var.clone(),
        }
    }
}

impl AuthInfo {
    /// Returns `true` if a token field is configured.
    #[must_use]
    pub fn has_token(&self) -> bool {
        !self.token_field.is_empty()
    }

    /// Returns `true` if a gateway URL field is configured.
    #[must_use]
    pub fn has_gateway(&self) -> bool {
        !self.gateway_url_field.is_empty()
    }
}

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

    #[test]
    fn attribute_is_input_required() {
        let attr = TestAttributeBuilder::new("name", IacType::String)
            .required()
            .build();
        assert!(attr.is_input());
    }

    #[test]
    fn attribute_is_input_optional() {
        let attr = TestAttributeBuilder::new("tag", IacType::String)
            .optional()
            .build();
        assert!(attr.is_input());
    }

    #[test]
    fn attribute_is_input_optional_computed() {
        let attr = TestAttributeBuilder::new("default_val", IacType::String)
            .optional()
            .computed()
            .build();
        assert!(attr.is_input());
    }

    #[test]
    fn attribute_is_not_input_purely_computed() {
        let attr = TestAttributeBuilder::new("id", IacType::String)
            .computed()
            .build();
        assert!(!attr.is_input());
    }

    #[test]
    fn attribute_is_output_computed() {
        let attr = TestAttributeBuilder::new("id", IacType::String)
            .computed()
            .build();
        assert!(attr.is_output());
    }

    #[test]
    fn attribute_is_output_required() {
        let attr = TestAttributeBuilder::new("name", IacType::String)
            .required()
            .build();
        assert!(attr.is_output());
    }

    #[test]
    fn attribute_is_not_output_plain_optional() {
        let attr = TestAttributeBuilder::new("tag", IacType::String).build();
        assert!(!attr.is_output());
    }

    #[test]
    fn iac_type_display() {
        assert_eq!(IacType::String.to_string(), "string");
        assert_eq!(IacType::Integer.to_string(), "integer");
        assert_eq!(IacType::Float.to_string(), "float");
        assert_eq!(IacType::Numeric.to_string(), "numeric");
        assert_eq!(IacType::Boolean.to_string(), "boolean");
        assert_eq!(
            IacType::List(Box::new(IacType::String)).to_string(),
            "list<string>"
        );
        assert_eq!(
            IacType::Set(Box::new(IacType::Integer)).to_string(),
            "set<integer>"
        );
        assert_eq!(
            IacType::Map(Box::new(IacType::Boolean)).to_string(),
            "map<string, boolean>"
        );
        assert_eq!(
            IacType::Object {
                name: "User".to_string(),
                fields: vec![]
            }
            .to_string(),
            "object<User>"
        );
        assert_eq!(
            IacType::Enum {
                values: vec!["a".into()],
                underlying: Box::new(IacType::String)
            }
            .to_string(),
            "enum<string>"
        );
        assert_eq!(IacType::Any.to_string(), "any");
    }

    #[test]
    fn iac_type_equality() {
        assert_eq!(IacType::String, IacType::String);
        assert_ne!(IacType::String, IacType::Integer);
        assert_eq!(
            IacType::List(Box::new(IacType::String)),
            IacType::List(Box::new(IacType::String))
        );
        assert_ne!(
            IacType::List(Box::new(IacType::String)),
            IacType::List(Box::new(IacType::Integer))
        );
    }

    #[test]
    fn iac_type_hash() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(IacType::String);
        set.insert(IacType::Integer);
        set.insert(IacType::String);
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn iac_attribute_display() {
        let attr = IacAttribute {
            api_name: "name".to_string(),
            canonical_name: "name".to_string(),
            description: String::new(),
            iac_type: IacType::String,
            required: true,
            optional: false,
            computed: false,
            sensitive: false,
            json_encoded: false,
            immutable: false,
            default_value: None,
            enum_values: None,
            read_path: None,
            update_only: false,
        };
        assert_eq!(attr.to_string(), "name: string (required)");

        let optional = IacAttribute {
            required: false,
            optional: true,
            ..attr
        };
        assert_eq!(optional.to_string(), "name: string (optional)");
    }

    #[test]
    fn auth_info_helpers() {
        let empty = AuthInfo::default();
        assert!(!empty.has_token());
        assert!(!empty.has_gateway());

        let configured = AuthInfo {
            token_field: "token".to_string(),
            env_var: "TOKEN".to_string(),
            gateway_url_field: "gateway".to_string(),
            gateway_env_var: "GW".to_string(),
        };
        assert!(configured.has_token());
        assert!(configured.has_gateway());
    }

    #[test]
    fn iac_resource_serialize_roundtrip() {
        let resource = IacResource {
            name: "test_resource".to_string(),
            description: "A test".to_string(),
            category: "test".to_string(),
            crud: CrudInfo {
                create_endpoint: "/create".to_string(),
                create_schema: "Create".to_string(),
                update_endpoint: None,
                update_schema: None,
                read_endpoint: "/read".to_string(),
                read_schema: "Read".to_string(),
                read_response_schema: None,
                delete_endpoint: "/delete".to_string(),
                delete_schema: "Delete".to_string(),
            },
            attributes: vec![IacAttribute {
                api_name: "name".to_string(),
                canonical_name: "name".to_string(),
                description: "The name".to_string(),
                iac_type: IacType::String,
                required: true,
                optional: false,
                computed: false,
                sensitive: false,
                json_encoded: false,
                immutable: true,
                default_value: None,
                enum_values: None,
                read_path: None,
                update_only: false,
            }],
            identity: IdentityInfo {
                id_field: "name".to_string(),
                import_field: "name".to_string(),
                force_replace_fields: vec!["name".to_string()],
            },
            read_mapping: BTreeMap::new(),
        };

        let json = serde_json::to_string(&resource).expect("serialize");
        let deserialized: IacResource = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(deserialized.name, resource.name);
        assert_eq!(deserialized.attributes.len(), 1);
        assert_eq!(deserialized.attributes[0].iac_type, IacType::String);
    }

    /// Helper to build a resource with mixed attribute flags for filter tests.
    fn resource_with_mixed_attrs() -> IacResource {
        IacResource {
            name: "mixed".to_string(),
            description: String::new(),
            category: "test".to_string(),
            crud: CrudInfo {
                create_endpoint: "/create".to_string(),
                create_schema: "Create".to_string(),
                update_endpoint: None,
                update_schema: None,
                read_endpoint: "/read".to_string(),
                read_schema: "Read".to_string(),
                read_response_schema: None,
                delete_endpoint: "/delete".to_string(),
                delete_schema: "Delete".to_string(),
            },
            attributes: vec![
                TestAttributeBuilder::new("name", IacType::String)
                    .required()
                    .immutable()
                    .build(),
                TestAttributeBuilder::new("secret", IacType::String)
                    .required()
                    .sensitive()
                    .build(),
                TestAttributeBuilder::new("computed_id", IacType::String)
                    .computed()
                    .build(),
                TestAttributeBuilder::new("tags", IacType::List(Box::new(IacType::String))).build(),
            ],
            identity: IdentityInfo {
                id_field: "name".to_string(),
                import_field: "name".to_string(),
                force_replace_fields: vec!["name".to_string()],
            },
            read_mapping: BTreeMap::new(),
        }
    }

    #[test]
    fn input_attributes_excludes_purely_computed() {
        let r = resource_with_mixed_attrs();
        let inputs = r.input_attributes();
        // "name" (required), "secret" (required), "tags" (not computed) = 3
        // "computed_id" is computed and not required, so excluded
        assert_eq!(inputs.len(), 3);
        assert!(inputs.iter().all(|a| a.canonical_name != "computed_id"));
    }

    #[test]
    fn output_attributes_includes_computed_and_required() {
        let r = resource_with_mixed_attrs();
        let outputs = r.output_attributes();
        // "name" (required), "secret" (required), "computed_id" (computed) = 3
        // "tags" is neither computed nor required
        assert_eq!(outputs.len(), 3);
        assert!(outputs.iter().all(|a| a.canonical_name != "tags"));
    }

    #[test]
    fn required_attribute_names_returns_correct_set() {
        let r = resource_with_mixed_attrs();
        let names = r.required_attribute_names();
        assert_eq!(names, vec!["name", "secret"]);
    }

    #[test]
    fn sensitive_attribute_names_returns_correct_set() {
        let r = resource_with_mixed_attrs();
        let names = r.sensitive_attribute_names();
        assert_eq!(names, vec!["secret"]);
    }

    #[test]
    fn immutable_attribute_names_returns_correct_set() {
        let r = resource_with_mixed_attrs();
        let names = r.immutable_attribute_names();
        assert_eq!(names, vec!["name"]);
    }

    #[test]
    fn data_source_input_and_output_attributes() {
        let ds = crate::testing::test_data_source("cfg");
        // "name" is required (not computed) -> input
        // "value" is computed -> output
        let inputs = ds.input_attributes();
        assert_eq!(inputs.len(), 1);
        assert_eq!(inputs[0].canonical_name, "name");

        let outputs = ds.output_attributes();
        assert_eq!(outputs.len(), 2);

        let computed = ds.computed_attribute_names();
        assert_eq!(computed, vec!["value"]);
    }

    #[test]
    fn data_source_required_and_sensitive() {
        let ds = IacDataSource {
            name: "test".to_string(),
            description: String::new(),
            read_endpoint: "/read".to_string(),
            read_schema: "Read".to_string(),
            read_response_schema: None,
            attributes: vec![
                TestAttributeBuilder::new("id", IacType::String)
                    .required()
                    .build(),
                TestAttributeBuilder::new("password", IacType::String)
                    .sensitive()
                    .computed()
                    .build(),
            ],
            read_mapping: BTreeMap::new(),
        };
        assert_eq!(ds.required_attribute_names(), vec!["id"]);
        assert_eq!(ds.sensitive_attribute_names(), vec!["password"]);
    }

    #[test]
    fn resource_input_attributes_mix() {
        let r = IacResource {
            name: "mix".to_string(),
            description: String::new(),
            category: "test".to_string(),
            crud: CrudInfo {
                create_endpoint: "/create".to_string(),
                create_schema: "Create".to_string(),
                update_endpoint: None,
                update_schema: None,
                read_endpoint: "/read".to_string(),
                read_schema: "Read".to_string(),
                read_response_schema: None,
                delete_endpoint: "/delete".to_string(),
                delete_schema: "Delete".to_string(),
            },
            attributes: vec![
                TestAttributeBuilder::new("req_only", IacType::String)
                    .required()
                    .build(),
                TestAttributeBuilder::new("comp_only", IacType::String)
                    .computed()
                    .build(),
                TestAttributeBuilder::new("comp_and_req", IacType::String)
                    .computed()
                    .required()
                    .build(),
                TestAttributeBuilder::new("optional", IacType::String).build(),
            ],
            identity: IdentityInfo {
                id_field: "req_only".to_string(),
                import_field: "req_only".to_string(),
                force_replace_fields: vec![],
            },
            read_mapping: BTreeMap::new(),
        };

        let inputs = r.input_attributes();
        let input_names: Vec<&str> = inputs.iter().map(|a| a.canonical_name.as_str()).collect();
        // Input: not computed OR required
        // req_only: not computed -> yes
        // comp_only: computed and not required -> no
        // comp_and_req: computed but required -> yes
        // optional: not computed -> yes
        assert_eq!(input_names, vec!["req_only", "comp_and_req", "optional"]);

        let outputs = r.output_attributes();
        let output_names: Vec<&str> = outputs.iter().map(|a| a.canonical_name.as_str()).collect();
        // Output: computed OR required
        // req_only: required -> yes
        // comp_only: computed -> yes
        // comp_and_req: both -> yes
        // optional: neither -> no
        assert_eq!(output_names, vec!["req_only", "comp_only", "comp_and_req"]);
    }

    #[test]
    fn data_source_input_and_output_full() {
        let ds = IacDataSource {
            name: "full_ds".to_string(),
            description: String::new(),
            read_endpoint: "/read".to_string(),
            read_schema: "Read".to_string(),
            read_response_schema: None,
            attributes: vec![
                TestAttributeBuilder::new("input_key", IacType::String)
                    .required()
                    .build(),
                TestAttributeBuilder::new("output_val", IacType::String)
                    .computed()
                    .build(),
                TestAttributeBuilder::new("both", IacType::String)
                    .required()
                    .computed()
                    .build(),
                TestAttributeBuilder::new("neither", IacType::String).build(),
            ],
            read_mapping: BTreeMap::new(),
        };

        let inputs = ds.input_attributes();
        let input_names: Vec<&str> = inputs.iter().map(|a| a.canonical_name.as_str()).collect();
        // Input: not computed OR required
        assert_eq!(input_names, vec!["input_key", "both", "neither"]);

        let outputs = ds.output_attributes();
        let output_names: Vec<&str> = outputs.iter().map(|a| a.canonical_name.as_str()).collect();
        // Output: computed OR required
        assert_eq!(output_names, vec!["input_key", "output_val", "both"]);

        let computed = ds.computed_attribute_names();
        assert_eq!(computed, vec!["output_val", "both"]);
    }

    #[test]
    fn auth_info_has_token_only() {
        let auth = AuthInfo {
            token_field: "token".to_string(),
            env_var: "TOKEN".to_string(),
            gateway_url_field: String::new(),
            gateway_env_var: String::new(),
        };
        assert!(auth.has_token());
        assert!(!auth.has_gateway());
    }

    #[test]
    fn auth_info_has_gateway_only() {
        let auth = AuthInfo {
            token_field: String::new(),
            env_var: String::new(),
            gateway_url_field: "gateway".to_string(),
            gateway_env_var: "GW".to_string(),
        };
        assert!(!auth.has_token());
        assert!(auth.has_gateway());
    }

    #[test]
    fn resource_no_attributes() {
        let r = IacResource {
            name: "empty".to_string(),
            description: String::new(),
            category: "test".to_string(),
            crud: CrudInfo {
                create_endpoint: "/create".to_string(),
                create_schema: "Create".to_string(),
                update_endpoint: None,
                update_schema: None,
                read_endpoint: "/read".to_string(),
                read_schema: "Read".to_string(),
                read_response_schema: None,
                delete_endpoint: "/delete".to_string(),
                delete_schema: "Delete".to_string(),
            },
            attributes: vec![],
            identity: IdentityInfo {
                id_field: "id".to_string(),
                import_field: "id".to_string(),
                force_replace_fields: vec![],
            },
            read_mapping: BTreeMap::new(),
        };

        assert!(r.input_attributes().is_empty());
        assert!(r.output_attributes().is_empty());
        assert!(r.required_attribute_names().is_empty());
        assert!(r.sensitive_attribute_names().is_empty());
        assert!(r.immutable_attribute_names().is_empty());
    }

    #[test]
    fn data_source_no_attributes() {
        let ds = IacDataSource {
            name: "empty".to_string(),
            description: String::new(),
            read_endpoint: "/read".to_string(),
            read_schema: "Read".to_string(),
            read_response_schema: None,
            attributes: vec![],
            read_mapping: BTreeMap::new(),
        };

        assert!(ds.input_attributes().is_empty());
        assert!(ds.output_attributes().is_empty());
        assert!(ds.required_attribute_names().is_empty());
        assert!(ds.sensitive_attribute_names().is_empty());
        assert!(ds.computed_attribute_names().is_empty());
    }

    #[test]
    fn iac_type_display_nested() {
        assert_eq!(
            IacType::List(Box::new(IacType::List(Box::new(IacType::String)))).to_string(),
            "list<list<string>>"
        );
        assert_eq!(
            IacType::Map(Box::new(IacType::List(Box::new(IacType::Integer)))).to_string(),
            "map<string, list<integer>>"
        );
        assert_eq!(
            IacType::Set(Box::new(IacType::Set(Box::new(IacType::Boolean)))).to_string(),
            "set<set<boolean>>"
        );
        assert_eq!(
            IacType::Set(Box::new(IacType::Map(Box::new(IacType::Float)))).to_string(),
            "set<map<string, float>>"
        );
    }

    #[test]
    fn iac_attribute_display_optional() {
        let attr = IacAttribute {
            api_name: "tags".to_string(),
            canonical_name: "tags".to_string(),
            description: String::new(),
            iac_type: IacType::List(Box::new(IacType::String)),
            required: false,
            optional: true,
            computed: false,
            sensitive: false,
            json_encoded: false,
            immutable: false,
            default_value: None,
            enum_values: None,
            read_path: None,
            update_only: false,
        };
        assert_eq!(attr.to_string(), "tags: list<string> (optional)");
    }

    #[test]
    fn iac_type_set_serde_roundtrip() {
        let set_type = IacType::Set(Box::new(IacType::String));
        let json = serde_json::to_string(&set_type).expect("serialize");
        let rt: IacType = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(set_type, rt);
    }

    #[test]
    fn iac_type_set_display() {
        assert_eq!(
            IacType::Set(Box::new(IacType::String)).to_string(),
            "set<string>"
        );
        assert_eq!(
            IacType::Set(Box::new(IacType::Integer)).to_string(),
            "set<integer>"
        );
    }

    #[test]
    fn iac_type_set_equality() {
        let a = IacType::Set(Box::new(IacType::String));
        let b = IacType::Set(Box::new(IacType::String));
        let c = IacType::Set(Box::new(IacType::Integer));
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn iac_type_set_hash() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(IacType::Set(Box::new(IacType::String)));
        set.insert(IacType::Set(Box::new(IacType::String)));
        set.insert(IacType::Set(Box::new(IacType::Integer)));
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn iac_type_serde_roundtrip_all_variants() {
        let types = vec![
            IacType::String,
            IacType::Integer,
            IacType::Float,
            IacType::Numeric,
            IacType::Boolean,
            IacType::Any,
            IacType::List(Box::new(IacType::Integer)),
            IacType::Set(Box::new(IacType::Boolean)),
            IacType::Map(Box::new(IacType::Float)),
            IacType::Object {
                name: "Nested".to_string(),
                fields: vec![],
            },
            IacType::Enum {
                values: vec!["x".into(), "y".into()],
                underlying: Box::new(IacType::String),
            },
        ];
        for t in &types {
            let json = serde_json::to_string(t).expect("serialize");
            let roundtripped: IacType = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(*t, roundtripped, "roundtrip failed for {t}");
        }
    }

    #[test]
    fn iac_type_serde_roundtrip_deeply_nested() {
        let deep = IacType::List(Box::new(IacType::Map(Box::new(IacType::Set(Box::new(
            IacType::Object {
                name: "Inner".to_string(),
                fields: vec![
                    crate::testing::TestAttributeBuilder::new("f", IacType::String)
                        .required()
                        .build(),
                ],
            },
        ))))));
        let json = serde_json::to_string(&deep).expect("serialize");
        let roundtripped: IacType = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(deep, roundtripped);
    }

    #[test]
    fn iac_attribute_serde_with_all_fields_set() {
        let attr = IacAttribute {
            api_name: "my-key".to_string(),
            canonical_name: "my_key".to_string(),
            description: "A key".to_string(),
            iac_type: IacType::String,
            required: true,
            optional: false,
            computed: true,
            sensitive: true,
            json_encoded: true,
            immutable: true,
            default_value: Some(serde_json::json!("default_val")),
            enum_values: Some(vec!["a".into(), "b".into()]),
            read_path: Some("response_key".to_string()),
            update_only: true,
        };
        let json = serde_json::to_string(&attr).expect("serialize");
        let roundtripped: IacAttribute = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(attr, roundtripped);
    }

    #[test]
    fn iac_attribute_json_encoded_default_false() {
        let json_str = r#"{
            "api_name":"f","canonical_name":"f","description":"","iac_type":"String",
            "required":false,"optional":false,"computed":false,"sensitive":false,
            "immutable":false,"default_value":null,"enum_values":null,
            "read_path":null,"update_only":false
        }"#;
        let attr: IacAttribute = serde_json::from_str(json_str).expect("deserialize");
        assert!(!attr.json_encoded, "json_encoded should default to false");
    }

    #[test]
    fn iac_attribute_optional_default_false() {
        let json_str = r#"{
            "api_name":"f","canonical_name":"f","description":"","iac_type":"String",
            "required":false,"computed":false,"sensitive":false,
            "immutable":false,"default_value":null,"enum_values":null,
            "read_path":null,"update_only":false
        }"#;
        let attr: IacAttribute = serde_json::from_str(json_str).expect("deserialize");
        assert!(!attr.optional, "optional should default to false");
    }

    #[test]
    fn resource_optional_computed_is_input() {
        let r = IacResource {
            name: "opt_comp".to_string(),
            description: String::new(),
            category: "test".to_string(),
            crud: CrudInfo {
                create_endpoint: "/create".to_string(),
                create_schema: "Create".to_string(),
                update_endpoint: None,
                update_schema: None,
                read_endpoint: "/read".to_string(),
                read_schema: "Read".to_string(),
                read_response_schema: None,
                delete_endpoint: "/delete".to_string(),
                delete_schema: "Delete".to_string(),
            },
            attributes: vec![
                TestAttributeBuilder::new("opt_comp_field", IacType::String)
                    .optional()
                    .computed()
                    .build(),
            ],
            identity: IdentityInfo {
                id_field: "id".to_string(),
                import_field: "id".to_string(),
                force_replace_fields: vec![],
            },
            read_mapping: BTreeMap::new(),
        };
        let inputs = r.input_attributes();
        assert_eq!(inputs.len(), 1, "optional+computed should be an input");
        assert_eq!(inputs[0].canonical_name, "opt_comp_field");
    }

    #[test]
    fn data_source_optional_computed_is_input() {
        let ds = IacDataSource {
            name: "opt_comp_ds".to_string(),
            description: String::new(),
            read_endpoint: "/read".to_string(),
            read_schema: "Read".to_string(),
            read_response_schema: None,
            attributes: vec![
                TestAttributeBuilder::new("opt_comp_field", IacType::String)
                    .optional()
                    .computed()
                    .build(),
            ],
            read_mapping: BTreeMap::new(),
        };
        let inputs = ds.input_attributes();
        assert_eq!(
            inputs.len(),
            1,
            "optional+computed should be an input for data source"
        );
    }

    #[test]
    fn iac_type_clone_equality() {
        let original = IacType::Object {
            name: "Config".to_string(),
            fields: vec![crate::testing::TestAttributeBuilder::new("k", IacType::String).build()],
        };
        let cloned = original.clone();
        assert_eq!(original, cloned);
    }

    #[test]
    fn crud_info_serde_roundtrip_with_optionals() {
        let crud = CrudInfo {
            create_endpoint: "/create".to_string(),
            create_schema: "Create".to_string(),
            update_endpoint: Some("/update".to_string()),
            update_schema: Some("Update".to_string()),
            read_endpoint: "/read".to_string(),
            read_schema: "Read".to_string(),
            read_response_schema: Some("ReadResp".to_string()),
            delete_endpoint: "/delete".to_string(),
            delete_schema: "Delete".to_string(),
        };
        let json = serde_json::to_string(&crud).expect("serialize");
        let rt: CrudInfo = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(rt.update_endpoint, Some("/update".to_string()));
        assert_eq!(rt.update_schema, Some("Update".to_string()));
        assert_eq!(rt.read_response_schema, Some("ReadResp".to_string()));
    }

    #[test]
    fn identity_info_serde_roundtrip() {
        let id = IdentityInfo {
            id_field: "name".to_string(),
            import_field: "path".to_string(),
            force_replace_fields: vec!["name".to_string(), "region".to_string()],
        };
        let json = serde_json::to_string(&id).expect("serialize");
        let rt: IdentityInfo = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(rt.id_field, "name");
        assert_eq!(rt.import_field, "path");
        assert_eq!(rt.force_replace_fields.len(), 2);
    }

    #[test]
    fn iac_provider_empty_auth_serializes() {
        let provider = IacProvider {
            name: "minimal".to_string(),
            description: String::new(),
            version: "0.1.0".to_string(),
            auth: AuthInfo::default(),
            skip_fields: vec![],
            platform_config: BTreeMap::new(),
        };
        let json = serde_json::to_string(&provider).expect("serialize");
        let rt: IacProvider = serde_json::from_str(&json).expect("deserialize");
        assert!(!rt.auth.has_token());
        assert!(!rt.auth.has_gateway());
        assert!(rt.skip_fields.is_empty());
        assert!(rt.platform_config.is_empty());
    }

    #[test]
    fn iac_provider_serialize_roundtrip() {
        let provider = IacProvider {
            name: "test".to_string(),
            description: "Test provider".to_string(),
            version: "1.0.0".to_string(),
            auth: AuthInfo {
                token_field: "token".to_string(),
                env_var: "TOKEN".to_string(),
                gateway_url_field: "gw".to_string(),
                gateway_env_var: "GW".to_string(),
            },
            skip_fields: vec!["token".to_string()],
            platform_config: {
                let mut m = BTreeMap::new();
                m.insert(
                    "terraform".to_string(),
                    toml::Value::String("sdk".to_string()),
                );
                m
            },
        };
        let json = serde_json::to_string(&provider).expect("serialize");
        let deserialized: IacProvider = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(deserialized.name, "test");
        assert_eq!(deserialized.auth.token_field, "token");
        assert_eq!(deserialized.skip_fields, vec!["token"]);
    }

    #[test]
    fn iac_data_source_serialize_roundtrip() {
        let ds = IacDataSource {
            name: "ds".to_string(),
            description: "A data source".to_string(),
            read_endpoint: "/read".to_string(),
            read_schema: "Read".to_string(),
            read_response_schema: Some("ReadOutput".to_string()),
            attributes: vec![
                TestAttributeBuilder::new("key", IacType::String)
                    .required()
                    .build(),
            ],
            read_mapping: BTreeMap::new(),
        };
        let json = serde_json::to_string(&ds).expect("serialize");
        let deserialized: IacDataSource = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(deserialized.name, "ds");
        assert_eq!(
            deserialized.read_response_schema,
            Some("ReadOutput".to_string())
        );
        assert_eq!(deserialized.attributes.len(), 1);
    }

    #[test]
    fn crud_info_from_crud_mapping() {
        let mapping = crate::spec::CrudMapping {
            create_endpoint: "/create".to_string(),
            create_schema: "Create".to_string(),
            update_endpoint: Some("/update".to_string()),
            update_schema: Some("Update".to_string()),
            read_endpoint: "/read".to_string(),
            read_schema: "Read".to_string(),
            read_response_schema: Some("ReadResp".to_string()),
            delete_endpoint: "/delete".to_string(),
            delete_schema: "Delete".to_string(),
        };
        let info = CrudInfo::from(&mapping);
        assert_eq!(info.create_endpoint, "/create");
        assert_eq!(info.update_endpoint, Some("/update".to_string()));
        assert_eq!(info.read_response_schema, Some("ReadResp".to_string()));
    }

    #[test]
    fn auth_info_from_auth_config() {
        let config = crate::spec::AuthConfig {
            token_field: "token".to_string(),
            env_var: "TOKEN".to_string(),
            gateway_url_field: "gw".to_string(),
            gateway_env_var: "GW".to_string(),
        };
        let info = AuthInfo::from(&config);
        assert_eq!(info.token_field, "token");
        assert_eq!(info.env_var, "TOKEN");
        assert!(info.has_token());
        assert!(info.has_gateway());
    }

    #[test]
    fn auth_info_from_default_auth_config() {
        let config = crate::spec::AuthConfig::default();
        let info = AuthInfo::from(&config);
        assert!(!info.has_token());
        assert!(!info.has_gateway());
    }

    #[test]
    fn iac_resource_display() {
        let r = crate::testing::test_resource("secret");
        assert_eq!(r.to_string(), "resource<secret> (3 attrs)");
    }

    #[test]
    fn iac_data_source_display() {
        let ds = crate::testing::test_data_source("config");
        assert_eq!(ds.to_string(), "data_source<config> (2 attrs)");
    }

    #[test]
    fn identity_info_from_identity_config() {
        let config = crate::spec::IdentityConfig {
            id_field: "name".to_string(),
            import_field: Some("path".to_string()),
            force_new_fields: vec!["name".to_string()],
        };
        let info = IdentityInfo::from(&config);
        assert_eq!(info.id_field, "name");
        assert_eq!(info.import_field, "path");
        assert_eq!(info.force_replace_fields, vec!["name"]);
    }

    #[test]
    fn identity_info_from_config_defaults_import_field() {
        let config = crate::spec::IdentityConfig {
            id_field: "my_id".to_string(),
            import_field: None,
            force_new_fields: vec![],
        };
        let info = IdentityInfo::from(&config);
        assert_eq!(info.import_field, "my_id");
    }

    #[test]
    fn iac_attribute_default() {
        let attr = IacAttribute::default();
        assert!(attr.api_name.is_empty());
        assert!(attr.canonical_name.is_empty());
        assert!(attr.description.is_empty());
        assert_eq!(attr.iac_type, IacType::String);
        assert!(!attr.required);
        assert!(!attr.optional);
        assert!(!attr.computed);
        assert!(!attr.sensitive);
        assert!(!attr.json_encoded);
        assert!(!attr.immutable);
        assert!(attr.default_value.is_none());
        assert!(attr.enum_values.is_none());
        assert!(attr.read_path.is_none());
        assert!(!attr.update_only);
    }

    #[test]
    fn iac_type_is_scalar() {
        assert!(IacType::String.is_scalar());
        assert!(IacType::Integer.is_scalar());
        assert!(IacType::Float.is_scalar());
        assert!(IacType::Numeric.is_scalar());
        assert!(IacType::Boolean.is_scalar());
        assert!(!IacType::List(Box::new(IacType::String)).is_scalar());
        assert!(!IacType::Set(Box::new(IacType::String)).is_scalar());
        assert!(!IacType::Map(Box::new(IacType::String)).is_scalar());
        assert!(
            !IacType::Object {
                name: "X".into(),
                fields: vec![]
            }
            .is_scalar()
        );
        assert!(!IacType::Any.is_scalar());
    }

    #[test]
    fn iac_type_is_composite() {
        assert!(IacType::List(Box::new(IacType::String)).is_composite());
        assert!(IacType::Set(Box::new(IacType::Integer)).is_composite());
        assert!(IacType::Map(Box::new(IacType::Boolean)).is_composite());
        assert!(
            IacType::Object {
                name: "X".into(),
                fields: vec![]
            }
            .is_composite()
        );
        assert!(!IacType::String.is_composite());
        assert!(!IacType::Integer.is_composite());
        assert!(!IacType::Any.is_composite());
    }

    #[test]
    fn iac_type_enum_is_neither_scalar_nor_composite() {
        let enum_type = IacType::Enum {
            values: vec!["a".into()],
            underlying: Box::new(IacType::String),
        };
        assert!(!enum_type.is_scalar());
        assert!(!enum_type.is_composite());
    }

    #[test]
    fn iac_type_inner_type_list() {
        let t = IacType::List(Box::new(IacType::String));
        assert_eq!(t.inner_type(), Some(&IacType::String));
    }

    #[test]
    fn iac_type_inner_type_set() {
        let t = IacType::Set(Box::new(IacType::Integer));
        assert_eq!(t.inner_type(), Some(&IacType::Integer));
    }

    #[test]
    fn iac_type_inner_type_map() {
        let t = IacType::Map(Box::new(IacType::Boolean));
        assert_eq!(t.inner_type(), Some(&IacType::Boolean));
    }

    #[test]
    fn iac_type_inner_type_enum() {
        let t = IacType::Enum {
            values: vec!["a".into()],
            underlying: Box::new(IacType::String),
        };
        assert_eq!(t.inner_type(), Some(&IacType::String));
    }

    #[test]
    fn iac_type_inner_type_scalar_none() {
        assert!(IacType::String.inner_type().is_none());
        assert!(IacType::Integer.inner_type().is_none());
        assert!(IacType::Boolean.inner_type().is_none());
        assert!(IacType::Any.inner_type().is_none());
    }

    #[test]
    fn iac_type_any_is_neither_scalar_nor_composite() {
        assert!(!IacType::Any.is_scalar());
        assert!(!IacType::Any.is_composite());
    }
}