vespera_macro 0.1.42

Procedural macros for Vespera - automatic route discovery and OpenAPI generation
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
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
//! Enum to JSON Schema conversion for `OpenAPI` generation.
//!
//! This module handles the conversion of Rust enums (as parsed by syn)
//! into OpenAPI-compatible JSON Schema definitions.
//!
//! ## Supported Serde Enum Representations
//!
//! Vespera supports all four serde enum representations:
//!
//! 1. **Externally Tagged** (default): `{"VariantName": {...}}`
//! 2. **Internally Tagged** (`#[serde(tag = "type")]`): `{"type": "VariantName", ...fields...}`
//! 3. **Adjacently Tagged** (`#[serde(tag = "type", content = "data")]`): `{"type": "VariantName", "data": {...}}`
//! 4. **Untagged** (`#[serde(untagged)]`): `{...fields...}` (no tag)
//!
//! Each representation maps to a different `OpenAPI` schema pattern using `oneOf` and optionally `discriminator`.

use std::collections::{BTreeMap, HashMap, HashSet};

use syn::Type;
use vespera_core::schema::{Discriminator, Schema, SchemaRef, SchemaType};

use super::{
    serde_attrs::{
        SerdeEnumRepr, extract_doc_comment, extract_enum_repr, extract_field_rename,
        extract_rename_all, rename_field, strip_raw_prefix_owned,
    },
    type_schema::parse_type_to_schema_ref,
};

/// Parses a Rust enum into an `OpenAPI` Schema.
///
/// Supports all four serde enum representations:
/// - Externally tagged (default): `{"VariantName": {...}}`
/// - Internally tagged (`#[serde(tag = "type")]`): `{"type": "VariantName", ...fields...}`
/// - Adjacently tagged (`#[serde(tag = "type", content = "data")]`): `{"type": "VariantName", "data": {...}}`
/// - Untagged (`#[serde(untagged)]`): `{...fields...}` (no tag)
///
/// # Arguments
/// * `enum_item` - The parsed enum from syn
/// * `known_schemas` - Map of known schema names for reference resolution
/// * `struct_definitions` - Map of struct names to their source code (for generics)
pub fn parse_enum_to_schema(
    enum_item: &syn::ItemEnum,
    known_schemas: &HashSet<String>,
    struct_definitions: &HashMap<String, String>,
) -> Schema {
    // Extract enum-level doc comment for schema description
    let enum_description = extract_doc_comment(&enum_item.attrs);

    // Extract rename_all attribute from enum
    let rename_all = extract_rename_all(&enum_item.attrs);

    // Detect the serde enum representation
    let repr = extract_enum_repr(&enum_item.attrs);

    // Check if all variants are unit variants
    let all_unit = enum_item
        .variants
        .iter()
        .all(|v| matches!(v.fields, syn::Fields::Unit));

    // For simple enums (all unit variants) with externally tagged representation (default),
    // they serialize to just the variant name as a string.
    // However, internally/adjacently tagged enums serialize unit variants as objects with tag.
    if all_unit && matches!(repr, SerdeEnumRepr::ExternallyTagged) {
        return parse_unit_enum_to_schema(enum_item, enum_description, rename_all.as_deref());
    }

    match repr {
        SerdeEnumRepr::ExternallyTagged => parse_externally_tagged_enum(
            enum_item,
            enum_description,
            rename_all.as_deref(),
            known_schemas,
            struct_definitions,
        ),
        SerdeEnumRepr::InternallyTagged { tag } => parse_internally_tagged_enum(
            enum_item,
            enum_description,
            rename_all.as_deref(),
            &tag,
            known_schemas,
            struct_definitions,
        ),
        SerdeEnumRepr::AdjacentlyTagged { tag, content } => parse_adjacently_tagged_enum(
            enum_item,
            enum_description,
            rename_all.as_deref(),
            &tag,
            &content,
            known_schemas,
            struct_definitions,
        ),
        SerdeEnumRepr::Untagged => parse_untagged_enum(
            enum_item,
            enum_description,
            rename_all.as_deref(),
            known_schemas,
            struct_definitions,
        ),
    }
}

/// Parse a simple enum (all unit variants) to a string schema with enum values.
fn parse_unit_enum_to_schema(
    enum_item: &syn::ItemEnum,
    description: Option<String>,
    rename_all: Option<&str>,
) -> Schema {
    let mut enum_values = Vec::with_capacity(enum_item.variants.len());

    for variant in &enum_item.variants {
        let variant_name = strip_raw_prefix_owned(variant.ident.to_string());

        // Check for variant-level rename attribute first (takes precedence)
        let enum_value = extract_field_rename(&variant.attrs)
            .unwrap_or_else(|| rename_field(&variant_name, rename_all));

        enum_values.push(serde_json::Value::String(enum_value));
    }

    Schema {
        schema_type: Some(SchemaType::String),
        description,
        r#enum: if enum_values.is_empty() {
            None
        } else {
            Some(enum_values)
        },
        ..Schema::string()
    }
}

/// Get the variant key (name after rename transformations)
fn get_variant_key(variant: &syn::Variant, rename_all: Option<&str>) -> String {
    let variant_name = strip_raw_prefix_owned(variant.ident.to_string());

    extract_field_rename(&variant.attrs).unwrap_or_else(|| rename_field(&variant_name, rename_all))
}

/// Build properties for a struct variant's fields
fn build_struct_variant_properties(
    fields_named: &syn::FieldsNamed,
    enum_rename_all: Option<&str>,
    variant_attrs: &[syn::Attribute],
    known_schemas: &HashSet<String>,
    struct_definitions: &HashMap<String, String>,
) -> (BTreeMap<String, SchemaRef>, Vec<String>) {
    let mut variant_properties = BTreeMap::new();
    let mut variant_required = Vec::with_capacity(fields_named.named.len());
    let variant_rename_all = extract_rename_all(variant_attrs);

    for field in &fields_named.named {
        let rust_field_name = field.ident.as_ref().map_or_else(
            || "unknown".to_string(),
            |i| strip_raw_prefix_owned(i.to_string()),
        );

        // Check for field-level rename attribute first (takes precedence)
        let field_name = extract_field_rename(&field.attrs).unwrap_or_else(|| {
            rename_field(
                &rust_field_name,
                variant_rename_all.as_deref().or(enum_rename_all),
            )
        });

        let field_type = &field.ty;
        let mut schema_ref =
            parse_type_to_schema_ref(field_type, known_schemas, struct_definitions);

        // Extract doc comment from field and set as description
        if let Some(doc) = extract_doc_comment(&field.attrs) {
            match &mut schema_ref {
                SchemaRef::Inline(schema) => {
                    schema.description = Some(doc);
                }
                SchemaRef::Ref(_) => {
                    let ref_schema = std::mem::replace(
                        &mut schema_ref,
                        SchemaRef::Inline(Box::new(Schema::object())),
                    );
                    if let SchemaRef::Ref(reference) = ref_schema {
                        schema_ref = SchemaRef::Inline(Box::new(Schema {
                            description: Some(doc),
                            all_of: Some(vec![SchemaRef::Ref(reference)]),
                            ..Default::default()
                        }));
                    }
                }
            }
        }

        variant_properties.insert(field_name.clone(), schema_ref);

        // Check if field is Option<T>
        let is_optional = matches!(
            field_type,
            Type::Path(type_path)
                if type_path
                    .path
                    .segments
                    .first()
                    .is_some_and(|s| s.ident == "Option")
        );

        if !is_optional {
            variant_required.push(field_name);
        }
    }

    (variant_properties, variant_required)
}

/// Build a schema for a variant's data (tuple or struct fields)
fn build_variant_data_schema(
    variant: &syn::Variant,
    enum_rename_all: Option<&str>,
    known_schemas: &HashSet<String>,
    struct_definitions: &HashMap<String, String>,
) -> Option<SchemaRef> {
    match &variant.fields {
        syn::Fields::Unit => None,
        syn::Fields::Unnamed(fields_unnamed) => {
            if fields_unnamed.unnamed.len() == 1 {
                // Single field tuple variant - just the inner type
                let inner_type = &fields_unnamed.unnamed[0].ty;
                Some(parse_type_to_schema_ref(
                    inner_type,
                    known_schemas,
                    struct_definitions,
                ))
            } else {
                // Multiple fields tuple variant - array with prefixItems
                let mut tuple_item_schemas = Vec::with_capacity(fields_unnamed.unnamed.len());
                for field in &fields_unnamed.unnamed {
                    let field_schema =
                        parse_type_to_schema_ref(&field.ty, known_schemas, struct_definitions);
                    tuple_item_schemas.push(field_schema);
                }

                let tuple_len = tuple_item_schemas.len();
                Some(SchemaRef::Inline(Box::new(Schema {
                    prefix_items: Some(tuple_item_schemas),
                    min_items: Some(tuple_len),
                    max_items: Some(tuple_len),
                    items: None,
                    ..Schema::new(SchemaType::Array)
                })))
            }
        }
        syn::Fields::Named(fields_named) => {
            let (properties, required) = build_struct_variant_properties(
                fields_named,
                enum_rename_all,
                &variant.attrs,
                known_schemas,
                struct_definitions,
            );

            Some(SchemaRef::Inline(Box::new(Schema {
                properties: if properties.is_empty() {
                    None
                } else {
                    Some(properties)
                },
                required: if required.is_empty() {
                    None
                } else {
                    Some(required)
                },
                ..Schema::object()
            })))
        }
    }
}

/// Parse externally tagged enum: `{"VariantName": {...}}`
/// This is serde's default representation.
fn parse_externally_tagged_enum(
    enum_item: &syn::ItemEnum,
    description: Option<String>,
    rename_all: Option<&str>,
    known_schemas: &HashSet<String>,
    struct_definitions: &HashMap<String, String>,
) -> Schema {
    let mut one_of_schemas = Vec::with_capacity(enum_item.variants.len());

    for variant in &enum_item.variants {
        let variant_key = get_variant_key(variant, rename_all);
        let variant_description = extract_doc_comment(&variant.attrs);

        let variant_schema = match &variant.fields {
            syn::Fields::Unit => {
                // Unit variant in mixed enum: string with const value
                Schema {
                    description: variant_description,
                    r#enum: Some(vec![serde_json::Value::String(variant_key)]),
                    ..Schema::string()
                }
            }
            syn::Fields::Unnamed(fields_unnamed) => {
                // Tuple variant: {"VariantName": <data>}
                let data_schema = if fields_unnamed.unnamed.len() == 1 {
                    let inner_type = &fields_unnamed.unnamed[0].ty;
                    parse_type_to_schema_ref(inner_type, known_schemas, struct_definitions)
                } else {
                    // Multiple fields - array with prefixItems
                    let mut tuple_item_schemas = Vec::with_capacity(fields_unnamed.unnamed.len());
                    for field in &fields_unnamed.unnamed {
                        let field_schema =
                            parse_type_to_schema_ref(&field.ty, known_schemas, struct_definitions);
                        tuple_item_schemas.push(field_schema);
                    }
                    let tuple_len = tuple_item_schemas.len();
                    SchemaRef::Inline(Box::new(Schema {
                        prefix_items: Some(tuple_item_schemas),
                        min_items: Some(tuple_len),
                        max_items: Some(tuple_len),
                        items: None,
                        ..Schema::new(SchemaType::Array)
                    }))
                };

                let mut properties = BTreeMap::new();
                properties.insert(variant_key.clone(), data_schema);

                Schema {
                    description: variant_description,
                    properties: Some(properties),
                    required: Some(vec![variant_key]),
                    ..Schema::object()
                }
            }
            syn::Fields::Named(fields_named) => {
                // Struct variant: {"VariantName": {field1: type1, ...}}
                let (inner_properties, inner_required) = build_struct_variant_properties(
                    fields_named,
                    rename_all,
                    &variant.attrs,
                    known_schemas,
                    struct_definitions,
                );

                let inner_struct_schema = Schema {
                    properties: if inner_properties.is_empty() {
                        None
                    } else {
                        Some(inner_properties)
                    },
                    required: if inner_required.is_empty() {
                        None
                    } else {
                        Some(inner_required)
                    },
                    ..Schema::object()
                };

                let mut properties = BTreeMap::new();
                properties.insert(
                    variant_key.clone(),
                    SchemaRef::Inline(Box::new(inner_struct_schema)),
                );

                Schema {
                    description: variant_description,
                    properties: Some(properties),
                    required: Some(vec![variant_key]),
                    ..Schema::object()
                }
            }
        };

        one_of_schemas.push(SchemaRef::Inline(Box::new(variant_schema)));
    }

    Schema {
        schema_type: None,
        description,
        one_of: if one_of_schemas.is_empty() {
            None
        } else {
            Some(one_of_schemas)
        },
        ..Schema::new(SchemaType::Object)
    }
}

/// Parse internally tagged enum: `{"tag": "VariantName", ...fields...}`
/// Uses `OpenAPI` discriminator for the tag field.
/// Note: serde only allows struct and unit variants for internally tagged enums.
fn parse_internally_tagged_enum(
    enum_item: &syn::ItemEnum,
    description: Option<String>,
    rename_all: Option<&str>,
    tag: &str,
    known_schemas: &HashSet<String>,
    struct_definitions: &HashMap<String, String>,
) -> Schema {
    let mut one_of_schemas = Vec::with_capacity(enum_item.variants.len());

    let tag_string = tag.to_string();

    for variant in &enum_item.variants {
        let variant_key = get_variant_key(variant, rename_all);
        let variant_description = extract_doc_comment(&variant.attrs);

        let variant_schema = match &variant.fields {
            syn::Fields::Unit => {
                // Unit variant: {"tag": "VariantName"}
                let mut properties = BTreeMap::new();
                properties.insert(
                    tag_string.clone(),
                    SchemaRef::Inline(Box::new(Schema {
                        r#enum: Some(vec![serde_json::Value::String(variant_key.clone())]),
                        ..Schema::string()
                    })),
                );

                Schema {
                    description: variant_description,
                    properties: Some(properties),
                    required: Some(vec![tag_string.clone()]),
                    ..Schema::object()
                }
            }
            syn::Fields::Named(fields_named) => {
                // Struct variant: {"tag": "VariantName", field1: type1, ...}
                let (mut properties, mut required) = build_struct_variant_properties(
                    fields_named,
                    rename_all,
                    &variant.attrs,
                    known_schemas,
                    struct_definitions,
                );

                // Add the tag field
                properties.insert(
                    tag_string.clone(),
                    SchemaRef::Inline(Box::new(Schema {
                        r#enum: Some(vec![serde_json::Value::String(variant_key.clone())]),
                        ..Schema::string()
                    })),
                );
                required.insert(0, tag_string.clone());

                Schema {
                    description: variant_description,
                    properties: Some(properties),
                    required: Some(required),
                    ..Schema::object()
                }
            }
            syn::Fields::Unnamed(_) => {
                // Tuple/newtype variants are not supported with internally tagged enums in serde
                // Generate a warning schema or skip
                continue;
            }
        };

        one_of_schemas.push(SchemaRef::Inline(Box::new(variant_schema)));
    }

    Schema {
        schema_type: None,
        description,
        one_of: if one_of_schemas.is_empty() {
            None
        } else {
            Some(one_of_schemas)
        },
        discriminator: Some(Discriminator {
            property_name: tag_string,
            mapping: None, // Mapping not needed for inline schemas
        }),
        ..Default::default()
    }
}

/// Parse adjacently tagged enum: `{"tag": "VariantName", "content": {...}}`
/// Uses `OpenAPI` discriminator for the tag field.
fn parse_adjacently_tagged_enum(
    enum_item: &syn::ItemEnum,
    description: Option<String>,
    rename_all: Option<&str>,
    tag: &str,
    content: &str,
    known_schemas: &HashSet<String>,
    struct_definitions: &HashMap<String, String>,
) -> Schema {
    let mut one_of_schemas = Vec::with_capacity(enum_item.variants.len());

    let tag_string = tag.to_string();
    let content_string = content.to_string();

    for variant in &enum_item.variants {
        let variant_key = get_variant_key(variant, rename_all);
        let variant_description = extract_doc_comment(&variant.attrs);

        let mut properties = BTreeMap::new();
        let mut required = vec![tag_string.clone()];

        // Add the tag field
        properties.insert(
            tag_string.clone(),
            SchemaRef::Inline(Box::new(Schema {
                r#enum: Some(vec![serde_json::Value::String(variant_key.clone())]),
                ..Schema::string()
            })),
        );

        // Add the content field if variant has data
        if let Some(data_schema) =
            build_variant_data_schema(variant, rename_all, known_schemas, struct_definitions)
        {
            properties.insert(content_string.clone(), data_schema);
            required.push(content_string.clone());
        }

        let variant_schema = Schema {
            description: variant_description,
            properties: Some(properties),
            required: Some(required),
            ..Schema::object()
        };

        one_of_schemas.push(SchemaRef::Inline(Box::new(variant_schema)));
    }

    Schema {
        schema_type: None,
        description,
        one_of: if one_of_schemas.is_empty() {
            None
        } else {
            Some(one_of_schemas)
        },
        discriminator: Some(Discriminator {
            property_name: tag_string,
            mapping: None,
        }),
        ..Default::default()
    }
}

/// Parse untagged enum: variant data only, no tag.
/// Uses oneOf without discriminator - validation relies on schema structure matching.
fn parse_untagged_enum(
    enum_item: &syn::ItemEnum,
    description: Option<String>,
    rename_all: Option<&str>,
    known_schemas: &HashSet<String>,
    struct_definitions: &HashMap<String, String>,
) -> Schema {
    let mut one_of_schemas = Vec::with_capacity(enum_item.variants.len());

    for variant in &enum_item.variants {
        let variant_description = extract_doc_comment(&variant.attrs);

        let variant_schema = match &variant.fields {
            syn::Fields::Unit => {
                // Unit variant in untagged enum: null
                Schema {
                    description: variant_description,
                    schema_type: Some(SchemaType::Null),
                    ..Default::default()
                }
            }
            syn::Fields::Unnamed(fields_unnamed) => {
                if fields_unnamed.unnamed.len() == 1 {
                    // Single field tuple variant - just the inner type
                    let inner_type = &fields_unnamed.unnamed[0].ty;
                    let mut schema = match parse_type_to_schema_ref(
                        inner_type,
                        known_schemas,
                        struct_definitions,
                    ) {
                        SchemaRef::Inline(s) => *s,
                        SchemaRef::Ref(r) => Schema {
                            all_of: Some(vec![SchemaRef::Ref(r)]),
                            ..Default::default()
                        },
                    };
                    schema.description = variant_description.or(schema.description);
                    schema
                } else {
                    // Multiple fields - array with prefixItems
                    let mut tuple_item_schemas = Vec::with_capacity(fields_unnamed.unnamed.len());
                    for field in &fields_unnamed.unnamed {
                        let field_schema =
                            parse_type_to_schema_ref(&field.ty, known_schemas, struct_definitions);
                        tuple_item_schemas.push(field_schema);
                    }
                    let tuple_len = tuple_item_schemas.len();
                    Schema {
                        description: variant_description,
                        prefix_items: Some(tuple_item_schemas),
                        min_items: Some(tuple_len),
                        max_items: Some(tuple_len),
                        items: None,
                        ..Schema::new(SchemaType::Array)
                    }
                }
            }
            syn::Fields::Named(fields_named) => {
                // Struct variant - just the object with fields
                let (properties, required) = build_struct_variant_properties(
                    fields_named,
                    rename_all,
                    &variant.attrs,
                    known_schemas,
                    struct_definitions,
                );

                Schema {
                    description: variant_description,
                    properties: if properties.is_empty() {
                        None
                    } else {
                        Some(properties)
                    },
                    required: if required.is_empty() {
                        None
                    } else {
                        Some(required)
                    },
                    ..Schema::object()
                }
            }
        };

        one_of_schemas.push(SchemaRef::Inline(Box::new(variant_schema)));
    }

    Schema {
        schema_type: None,
        description,
        one_of: if one_of_schemas.is_empty() {
            None
        } else {
            Some(one_of_schemas)
        },
        ..Default::default()
    }
}

#[cfg(test)]
mod tests {
    use insta::{assert_debug_snapshot, with_settings};
    use rstest::rstest;

    use super::*;

    #[rstest]
    #[case(
        r#"
        #[serde(rename_all = "kebab-case")]
        enum Status {
            #[serde(rename = "ok-status")]
            Ok,
            ErrorCode,
        }
        "#,
        SchemaType::String,
        vec!["ok-status", "error-code"],
        "status"
    )]
    #[case(
        r"
        enum Simple {
            First,
            Second,
        }
        ",
        SchemaType::String,
        vec!["First", "Second"],
        "simple"
    )]
    #[case(
        r#"
        #[serde(rename_all = "snake_case")]
        enum Simple {
            FirstItem,
            SecondItem,
        }
        "#,
        SchemaType::String,
        vec!["first_item", "second_item"],
        "simple_snake"
    )]
    fn test_parse_enum_to_schema_unit_variants(
        #[case] enum_src: &str,
        #[case] expected_type: SchemaType,
        #[case] expected_enum: Vec<&str>,
        #[case] suffix: &str,
    ) {
        let enum_item: syn::ItemEnum = syn::parse_str(enum_src).unwrap();
        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        assert_eq!(schema.schema_type, Some(expected_type));
        let got = schema
            .clone()
            .r#enum
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap().to_string())
            .collect::<Vec<_>>();
        assert_eq!(got, expected_enum);
        with_settings!({ snapshot_suffix => format!("unit_{}", suffix) }, {
            assert_debug_snapshot!(schema);
        });
    }

    #[rstest]
    #[case(
        r"
        enum Event {
            Data(String),
        }
        ",
        1,
        Some(SchemaType::String),
        0, // single-field tuple variant stored as object with inline schema
        "tuple_single"
    )]
    #[case(
        r"
        enum Pair {
            Values(i32, String),
        }
        ",
        1,
        Some(SchemaType::Array),
        2, // tuple array prefix_items length
        "tuple_multi"
    )]
    #[case(
        r"
        enum Msg {
            Detail { id: i32, note: Option<String> },
        }
        ",
        1,
        Some(SchemaType::Object),
        0, // not an array; ignore prefix_items length
        "named_object"
    )]
    fn test_parse_enum_to_schema_tuple_and_named_variants(
        #[case] enum_src: &str,
        #[case] expected_one_of_len: usize,
        #[case] expected_inner_type: Option<SchemaType>,
        #[case] expected_prefix_items_len: usize,
        #[case] suffix: &str,
    ) {
        let enum_item: syn::ItemEnum = syn::parse_str(enum_src).unwrap();
        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        let one_of = schema.clone().one_of.expect("one_of missing");
        assert_eq!(one_of.len(), expected_one_of_len);

        if let Some(inner_expected) = expected_inner_type.clone() {
            if let SchemaRef::Inline(obj) = &one_of[0] {
                let props = obj.properties.as_ref().expect("props missing");
                // take first property value
                let inner_schema = props.values().next().expect("no property value");
                match inner_expected {
                    SchemaType::Array => {
                        if let SchemaRef::Inline(array_schema) = inner_schema {
                            assert_eq!(array_schema.schema_type, Some(SchemaType::Array));
                            if expected_prefix_items_len > 0 {
                                assert_eq!(
                                    array_schema.prefix_items.as_ref().unwrap().len(),
                                    expected_prefix_items_len
                                );
                            }
                        } else {
                            panic!("Expected inline array schema");
                        }
                    }
                    SchemaType::Object => {
                        if let SchemaRef::Inline(inner_obj) = inner_schema {
                            assert_eq!(inner_obj.schema_type, Some(SchemaType::Object));
                            let inner_props = inner_obj.properties.as_ref().unwrap();
                            assert!(inner_props.contains_key("id"));
                            assert!(inner_props.contains_key("note"));
                            assert!(
                                inner_obj
                                    .required
                                    .as_ref()
                                    .unwrap()
                                    .contains(&"id".to_string())
                            );
                        } else {
                            panic!("Expected inline object schema");
                        }
                    }
                    _ => {}
                }
            } else {
                panic!("Expected inline schema in one_of");
            }
        }

        with_settings!({ snapshot_suffix => format!("tuple_named_{}", suffix) }, {
            assert_debug_snapshot!(schema);
        });
    }

    #[rstest]
    #[case(
        r"
        enum Mixed {
            Ready,
            Data(String),
        }
        ",
        2,
        SchemaType::String,
        "Ready"
    )]
    fn test_parse_enum_to_schema_mixed_unit_variant(
        #[case] enum_src: &str,
        #[case] expected_one_of_len: usize,
        #[case] expected_unit_type: SchemaType,
        #[case] expected_unit_value: &str,
    ) {
        let enum_item: syn::ItemEnum = syn::parse_str(enum_src).unwrap();

        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        let one_of = schema.one_of.expect("one_of missing for mixed enum");
        assert_eq!(one_of.len(), expected_one_of_len);

        let SchemaRef::Inline(unit_schema) = &one_of[0] else {
            panic!("Expected inline schema for unit variant")
        };
        assert_eq!(unit_schema.schema_type, Some(expected_unit_type));
        let unit_enum = unit_schema.r#enum.as_ref().expect("enum values missing");
        assert_eq!(unit_enum[0].as_str().unwrap(), expected_unit_value);
    }

    #[test]
    fn test_parse_enum_to_schema_rename_all_for_data_variant() {
        let enum_item: syn::ItemEnum = syn::parse_str(
            r#"
            #[serde(rename_all = "kebab-case")]
            enum Payload {
                DataItem(String),
            }
        "#,
        )
        .unwrap();

        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        let one_of = schema.one_of.expect("one_of missing");
        let SchemaRef::Inline(variant_obj) = &one_of[0] else {
            panic!("Expected inline schema")
        };
        let props = variant_obj
            .properties
            .as_ref()
            .expect("variant props missing");
        assert!(props.contains_key("data-item"));
    }

    #[test]
    fn test_parse_enum_to_schema_field_uses_enum_rename_all() {
        let enum_item: syn::ItemEnum = syn::parse_str(
            r#"
            #[serde(rename_all = "snake_case")]
            enum Event {
                Detail { UserId: i32 },
            }
        "#,
        )
        .unwrap();

        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        let one_of = schema.one_of.expect("one_of missing");
        let SchemaRef::Inline(variant_obj) = &one_of[0] else {
            panic!("Expected inline schema")
        };
        let props = variant_obj
            .properties
            .as_ref()
            .expect("variant props missing");
        let SchemaRef::Inline(inner) = props.get("detail").expect("variant key missing") else {
            panic!("Expected inline inner schema")
        };
        let inner_props = inner.properties.as_ref().expect("inner props missing");
        assert!(inner_props.contains_key("user_id"));
        assert!(!inner_props.contains_key("UserId"));
    }

    #[test]
    fn test_parse_enum_to_schema_variant_rename_overrides_rename_all() {
        let enum_item: syn::ItemEnum = syn::parse_str(
            r#"
            #[serde(rename_all = "snake_case")]
            enum Payload {
                #[serde(rename = "Explicit")]
                DataItem(i32),
            }
        "#,
        )
        .unwrap();

        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        let one_of = schema.one_of.expect("one_of missing");
        let SchemaRef::Inline(variant_obj) = &one_of[0] else {
            panic!("Expected inline schema")
        };
        let props = variant_obj
            .properties
            .as_ref()
            .expect("variant props missing");
        assert!(props.contains_key("Explicit"));
        assert!(!props.contains_key("data_item"));
    }

    #[test]
    fn test_parse_enum_to_schema_field_rename_overrides_variant_rename_all() {
        let enum_item: syn::ItemEnum = syn::parse_str(
            r#"
            #[serde(rename_all = "snake_case")]
            enum Payload {
                #[serde(rename_all = "kebab-case")]
                Detail { #[serde(rename = "ID")] user_id: i32 },
            }
        "#,
        )
        .unwrap();

        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        let one_of = schema.one_of.expect("one_of missing");
        let SchemaRef::Inline(variant_obj) = &one_of[0] else {
            panic!("Expected inline schema")
        };
        let props = variant_obj
            .properties
            .as_ref()
            .expect("variant props missing");
        let SchemaRef::Inline(inner) = props
            .get("detail")
            .or_else(|| props.get("Detail"))
            .expect("variant key missing")
        else {
            panic!("Expected inline inner schema")
        };
        let inner_props = inner.properties.as_ref().expect("inner props missing");
        assert!(inner_props.contains_key("ID")); // field-level rename wins
        assert!(!inner_props.contains_key("user-id")); // variant rename_all ignored for this field
    }

    #[test]
    fn test_parse_enum_to_schema_rename_all_with_other_attrs_unit() {
        // Test rename_all combined with other serde attributes for unit variants
        let enum_item: syn::ItemEnum = syn::parse_str(
            r#"
            #[serde(rename_all = "kebab-case", default)]
            enum Status {
                ActiveUser,
                InactiveUser,
            }
        "#,
        )
        .unwrap();

        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        let enum_values = schema.r#enum.expect("enum values missing");
        assert_eq!(enum_values[0].as_str().unwrap(), "active-user");
        assert_eq!(enum_values[1].as_str().unwrap(), "inactive-user");
    }

    #[test]
    fn test_parse_enum_to_schema_rename_all_with_other_attrs_data() {
        // Test rename_all combined with other serde attributes for data variants
        let enum_item: syn::ItemEnum = syn::parse_str(
            r#"
            #[serde(rename_all = "camelCase", deny_unknown_fields)]
            enum Event {
                UserCreated { user_name: String, created_at: i64 },
                UserDeleted(i32),
            }
        "#,
        )
        .unwrap();

        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        let one_of = schema.one_of.expect("one_of missing");

        // Check UserCreated variant key is camelCase
        let SchemaRef::Inline(variant_obj) = &one_of[0] else {
            panic!("Expected inline schema")
        };
        let props = variant_obj
            .properties
            .as_ref()
            .expect("variant props missing");
        assert!(props.contains_key("userCreated"));
        assert!(!props.contains_key("UserCreated"));
        assert!(!props.contains_key("user_created"));

        // Check UserDeleted variant key is camelCase
        let SchemaRef::Inline(variant_obj2) = &one_of[1] else {
            panic!("Expected inline schema")
        };
        let props2 = variant_obj2
            .properties
            .as_ref()
            .expect("variant props missing");
        assert!(props2.contains_key("userDeleted"));
    }

    #[test]
    fn test_parse_enum_to_schema_rename_all_not_first_attr() {
        // Test rename_all when it's not the first attribute
        let enum_item: syn::ItemEnum = syn::parse_str(
            r#"
            #[serde(default, rename_all = "SCREAMING_SNAKE_CASE")]
            enum Priority {
                HighPriority,
                LowPriority,
            }
        "#,
        )
        .unwrap();

        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        let enum_values = schema.r#enum.expect("enum values missing");
        assert_eq!(enum_values[0].as_str().unwrap(), "HIGH_PRIORITY");
        assert_eq!(enum_values[1].as_str().unwrap(), "LOW_PRIORITY");
    }

    // Test enum with empty variants (edge case)
    #[test]
    fn test_parse_enum_to_schema_empty_enum() {
        let enum_item: syn::ItemEnum = syn::parse_str(
            r"
            enum Empty {}
        ",
        )
        .unwrap();
        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        // Empty enum should have no enum values
        assert!(schema.r#enum.is_none() || schema.r#enum.as_ref().unwrap().is_empty());
    }

    // Test enum with all struct variants having empty properties
    #[test]
    fn test_parse_enum_to_schema_struct_variant_no_fields() {
        let enum_item: syn::ItemEnum = syn::parse_str(
            r"
            enum Event {
                Empty {},
            }
        ",
        )
        .unwrap();
        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        let one_of = schema.one_of.expect("one_of missing");
        assert_eq!(one_of.len(), 1);
    }

    // Tests for enum with doc comments on variants
    #[test]
    fn test_parse_enum_to_schema_with_variant_descriptions() {
        let enum_src = r"
            /// Enum description
            enum Status {
                /// Active variant
                Active,
                /// Inactive variant
                Inactive,
            }
        ";
        let enum_item: syn::ItemEnum = syn::parse_str(enum_src).unwrap();
        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        assert_eq!(schema.description, Some("Enum description".to_string()));
    }

    #[test]
    fn test_parse_enum_to_schema_data_variant_with_description() {
        let enum_src = r"
            /// Data enum
            enum Event {
                /// Text event description
                Text(String),
                /// Number event description
                Number(i32),
            }
        ";
        let enum_item: syn::ItemEnum = syn::parse_str(enum_src).unwrap();
        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        assert_eq!(schema.description, Some("Data enum".to_string()));
        assert!(schema.one_of.is_some());
        let one_of = schema.one_of.unwrap();
        assert_eq!(one_of.len(), 2);
        // Check first variant has description
        if let SchemaRef::Inline(variant_schema) = &one_of[0] {
            assert_eq!(
                variant_schema.description,
                Some("Text event description".to_string())
            );
        }
    }

    #[test]
    fn test_parse_enum_to_schema_struct_variant_with_field_docs() {
        let enum_src = r"
            enum Event {
                /// Record variant
                Record {
                    /// The value field
                    value: i32,
                    /// The name field
                    name: String,
                },
            }
        ";
        let enum_item: syn::ItemEnum = syn::parse_str(enum_src).unwrap();
        let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
        assert!(schema.one_of.is_some());
        let one_of = schema.one_of.unwrap();
        if let SchemaRef::Inline(variant_schema) = &one_of[0] {
            assert_eq!(
                variant_schema.description,
                Some("Record variant".to_string())
            );
        }
    }

    #[test]
    fn test_parse_enum_to_schema_variant_field_with_doc_comment_and_ref() {
        // Test that doc comment on field with SchemaRef::Ref wraps in allOf
        let enum_item: syn::ItemEnum = syn::parse_str(
            r"
            enum Message {
                Data {
                    /// The user associated with this message
                    user: User,
                },
            }
        ",
        )
        .unwrap();

        // Register User as a known schema to get SchemaRef::Ref
        let mut known_schemas = HashSet::new();
        known_schemas.insert("User".to_string());

        let schema = parse_enum_to_schema(&enum_item, &known_schemas, &HashMap::new());
        let one_of = schema.one_of.expect("one_of missing");

        // Get the Data variant schema
        let SchemaRef::Inline(variant_obj) = &one_of[0] else {
            panic!("Expected inline schema")
        };
        let props = variant_obj
            .properties
            .as_ref()
            .expect("variant props missing");
        let SchemaRef::Inline(inner) = props.get("Data").expect("variant key missing") else {
            panic!("Expected inline inner schema")
        };
        let inner_props = inner.properties.as_ref().expect("inner props missing");

        // The user field should have been wrapped in allOf with description
        let user_field = inner_props.get("user").expect("user field missing");
        match user_field {
            SchemaRef::Inline(schema) => {
                // Should have description from doc comment
                assert_eq!(
                    schema.description.as_deref(),
                    Some("The user associated with this message")
                );
                // Should have allOf with the original $ref
                let all_of = schema.all_of.as_ref().expect("allOf missing");
                assert_eq!(all_of.len(), 1);
                let SchemaRef::Ref(reference) = &all_of[0] else {
                    panic!("Expected $ref in allOf")
                };
                assert_eq!(reference.ref_path, "#/components/schemas/User");
            }
            SchemaRef::Ref(_) => panic!("Expected inline schema with allOf, not direct $ref"),
        }
    }

    // Tests for serde enum representation support
    mod enum_repr_tests {
        use super::*;

        // Internally tagged enum tests
        #[test]
        fn test_internally_tagged_enum_unit_variants() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r#"
                #[serde(tag = "type")]
                enum Message {
                    Ping,
                    Pong,
                }
                "#,
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            // Should have discriminator
            let discriminator = schema
                .discriminator
                .as_ref()
                .expect("discriminator missing");
            assert_eq!(discriminator.property_name, "type");

            // Should have oneOf
            let one_of = schema.one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 2);

            // Each variant should be an object with "type" property
            if let SchemaRef::Inline(ping) = &one_of[0] {
                let props = ping.properties.as_ref().expect("properties missing");
                assert!(props.contains_key("type"));
                let required = ping.required.as_ref().expect("required missing");
                assert!(required.contains(&"type".to_string()));
            } else {
                panic!("Expected inline schema");
            }
        }

        #[test]
        fn test_internally_tagged_enum_struct_variants() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r#"
                #[serde(tag = "kind")]
                enum Event {
                    Created { id: i32, name: String },
                    Updated { id: i32 },
                }
                "#,
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            // Should have discriminator with custom tag name
            let discriminator = schema
                .discriminator
                .as_ref()
                .expect("discriminator missing");
            assert_eq!(discriminator.property_name, "kind");

            let one_of = schema.one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 2);

            // Created variant should have kind, id, and name
            if let SchemaRef::Inline(created) = &one_of[0] {
                let props = created.properties.as_ref().expect("properties missing");
                assert!(props.contains_key("kind"));
                assert!(props.contains_key("id"));
                assert!(props.contains_key("name"));
            } else {
                panic!("Expected inline schema");
            }
        }

        #[test]
        fn test_internally_tagged_enum_with_rename_all() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r#"
                #[serde(tag = "type", rename_all = "snake_case")]
                enum Status {
                    ActiveUser,
                    InactiveUser,
                }
                "#,
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            let one_of = schema.one_of.expect("one_of missing");
            if let SchemaRef::Inline(active) = &one_of[0] {
                let props = active.properties.as_ref().expect("properties missing");
                if let SchemaRef::Inline(type_schema) = props.get("type").expect("type missing") {
                    let enum_vals = type_schema.r#enum.as_ref().expect("enum values missing");
                    assert_eq!(enum_vals[0].as_str().unwrap(), "active_user");
                }
            }
        }

        // Adjacently tagged enum tests
        #[test]
        fn test_adjacently_tagged_enum_basic() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r#"
                #[serde(tag = "type", content = "data")]
                enum Response {
                    Success { result: String },
                    Error { message: String },
                }
                "#,
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            // Should have discriminator
            let discriminator = schema
                .discriminator
                .as_ref()
                .expect("discriminator missing");
            assert_eq!(discriminator.property_name, "type");

            let one_of = schema.one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 2);

            // Each variant should have "type" and "data" properties
            if let SchemaRef::Inline(success) = &one_of[0] {
                let props = success.properties.as_ref().expect("properties missing");
                assert!(props.contains_key("type"));
                assert!(props.contains_key("data"));

                let required = success.required.as_ref().expect("required missing");
                assert!(required.contains(&"type".to_string()));
                assert!(required.contains(&"data".to_string()));
            } else {
                panic!("Expected inline schema");
            }
        }

        #[test]
        fn test_adjacently_tagged_enum_with_unit_variant() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r#"
                #[serde(tag = "type", content = "payload")]
                enum Command {
                    Ping,
                    Message { text: String },
                }
                "#,
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            let one_of = schema.one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 2);

            // Ping (unit variant) should only have "type", no "payload"
            if let SchemaRef::Inline(ping) = &one_of[0] {
                let props = ping.properties.as_ref().expect("properties missing");
                assert!(props.contains_key("type"));
                assert!(!props.contains_key("payload")); // Unit variant has no content

                let required = ping.required.as_ref().expect("required missing");
                assert_eq!(required.len(), 1); // Only "type" is required
                assert!(required.contains(&"type".to_string()));
            }

            // Message should have both "type" and "payload"
            if let SchemaRef::Inline(message) = &one_of[1] {
                let props = message.properties.as_ref().expect("properties missing");
                assert!(props.contains_key("type"));
                assert!(props.contains_key("payload"));
            }
        }

        #[test]
        fn test_adjacently_tagged_enum_tuple_variant() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r#"
                #[serde(tag = "t", content = "c")]
                enum Value {
                    Int(i32),
                    Pair(i32, String),
                }
                "#,
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            let one_of = schema.one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 2);

            // Int variant - content should be integer schema
            if let SchemaRef::Inline(int_variant) = &one_of[0] {
                let props = int_variant.properties.as_ref().expect("properties missing");
                let content = props.get("c").expect("content missing");
                if let SchemaRef::Inline(content_schema) = content {
                    assert_eq!(content_schema.schema_type, Some(SchemaType::Integer));
                }
            }

            // Pair variant - content should be array with prefixItems
            if let SchemaRef::Inline(pair_variant) = &one_of[1] {
                let props = pair_variant
                    .properties
                    .as_ref()
                    .expect("properties missing");
                let content = props.get("c").expect("content missing");
                if let SchemaRef::Inline(content_schema) = content {
                    assert_eq!(content_schema.schema_type, Some(SchemaType::Array));
                    assert!(content_schema.prefix_items.is_some());
                }
            }
        }

        // Untagged enum tests
        #[test]
        fn test_untagged_enum_basic() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r"
                #[serde(untagged)]
                enum StringOrInt {
                    String(String),
                    Int(i32),
                }
                ",
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            // Should NOT have discriminator
            assert!(schema.discriminator.is_none());

            let one_of = schema.one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 2);

            // First variant should be string schema directly (not wrapped in object)
            if let SchemaRef::Inline(string_variant) = &one_of[0] {
                assert_eq!(string_variant.schema_type, Some(SchemaType::String));
            } else {
                panic!("Expected inline schema");
            }

            // Second variant should be integer schema directly
            if let SchemaRef::Inline(int_variant) = &one_of[1] {
                assert_eq!(int_variant.schema_type, Some(SchemaType::Integer));
            } else {
                panic!("Expected inline schema");
            }
        }

        #[test]
        fn test_untagged_enum_struct_variants() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r"
                #[serde(untagged)]
                enum Data {
                    User { name: String, age: i32 },
                    Product { title: String, price: f64 },
                }
                ",
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            assert!(schema.discriminator.is_none());

            let one_of = schema.one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 2);

            // User variant should be object with name and age (no wrapper)
            if let SchemaRef::Inline(user) = &one_of[0] {
                assert_eq!(user.schema_type, Some(SchemaType::Object));
                let props = user.properties.as_ref().expect("properties missing");
                assert!(props.contains_key("name"));
                assert!(props.contains_key("age"));
            }
        }

        #[test]
        fn test_untagged_enum_unit_variant() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r"
                #[serde(untagged)]
                enum MaybeValue {
                    Nothing,
                    Something(i32),
                }
                ",
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            let one_of = schema.one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 2);

            // Unit variant in untagged enum should be null
            if let SchemaRef::Inline(nothing) = &one_of[0] {
                assert_eq!(nothing.schema_type, Some(SchemaType::Null));
            }
        }

        // Snapshot tests for new representations
        #[test]
        fn test_internally_tagged_snapshot() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r#"
                #[serde(tag = "type")]
                enum Message {
                    Request { id: i32, method: String },
                    Response { id: i32, result: Option<String> },
                    Notification,
                }
                "#,
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
            with_settings!({ snapshot_suffix => "internally_tagged" }, {
                assert_debug_snapshot!(schema);
            });
        }

        #[test]
        fn test_adjacently_tagged_snapshot() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r#"
                #[serde(tag = "type", content = "data")]
                enum ApiResponse {
                    Success { items: Vec<String> },
                    Error { code: i32, message: String },
                    Empty,
                }
                "#,
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
            with_settings!({ snapshot_suffix => "adjacently_tagged" }, {
                assert_debug_snapshot!(schema);
            });
        }

        #[test]
        fn test_untagged_snapshot() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r"
                #[serde(untagged)]
                enum Value {
                    Null,
                    Bool(bool),
                    Number(f64),
                    Text(String),
                    Object { key: String, value: String },
                }
                ",
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());
            with_settings!({ snapshot_suffix => "untagged" }, {
                assert_debug_snapshot!(schema);
            });
        }

        // Edge case: Empty struct variant (empty properties/required)
        #[test]
        fn test_externally_tagged_empty_struct_variant() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r"
                enum Event {
                    /// Empty struct variant
                    Empty {},
                    Data { value: i32 },
                }
                ",
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            let one_of = schema.clone().one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 2);

            // Empty variant should have properties with Empty key pointing to object with no properties
            if let SchemaRef::Inline(empty_variant) = &one_of[0] {
                let props = empty_variant
                    .properties
                    .as_ref()
                    .expect("variant props missing");
                let SchemaRef::Inline(inner) = props.get("Empty").expect("Empty key missing")
                else {
                    panic!("Expected inline schema")
                };
                // Empty struct should have properties: None and required: None
                assert!(inner.properties.is_none());
                assert!(inner.required.is_none());
            }

            with_settings!({ snapshot_suffix => "externally_tagged_empty_struct" }, {
                assert_debug_snapshot!(schema);
            });
        }

        // Edge case: Internally tagged enum with tuple variant
        #[test]
        fn test_internally_tagged_skips_tuple_variant() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r#"
                #[serde(tag = "type")]
                enum Message {
                    Text { content: String },
                    Number(i32),
                    Empty,
                }
                "#,
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            // Tuple variant `Number(i32)` should be skipped, only 2 variants should remain
            let one_of = schema.clone().one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 2); // Text and Empty only

            // Verify discriminator is present
            let discriminator = schema
                .discriminator
                .as_ref()
                .expect("discriminator missing");
            assert_eq!(discriminator.property_name, "type");

            with_settings!({ snapshot_suffix => "internally_tagged_skip_tuple" }, {
                assert_debug_snapshot!(schema);
            });
        }

        // Edge case: Untagged enum with tuple variant referencing a known schema
        #[test]
        fn test_untagged_tuple_variant_with_known_schema_ref() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r"
                #[serde(untagged)]
                enum Payload {
                    User(UserData),
                    Simple(String),
                }
                ",
            )
            .unwrap();

            // Provide UserData as a known schema so it returns SchemaRef::Ref
            let mut known_schemas = HashSet::new();
            known_schemas.insert("UserData".to_string());

            let schema = parse_enum_to_schema(&enum_item, &known_schemas, &HashMap::new());

            assert!(schema.discriminator.is_none());

            let one_of = schema.one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 2);

            // First variant (UserData) should have all_of with a $ref since it's a known schema
            if let SchemaRef::Inline(user_variant) = &one_of[0] {
                // The schema should have all_of containing the reference
                let all_of = user_variant
                    .all_of
                    .as_ref()
                    .expect("all_of missing for known schema ref");
                assert_eq!(all_of.len(), 1);
                if let SchemaRef::Ref(reference) = &all_of[0] {
                    assert!(reference.ref_path.contains("UserData"));
                } else {
                    panic!("Expected SchemaRef::Ref inside all_of");
                }
            } else {
                panic!("Expected inline schema");
            }

            // Second variant (String) should be inline string schema directly
            if let SchemaRef::Inline(simple_variant) = &one_of[1] {
                assert_eq!(simple_variant.schema_type, Some(SchemaType::String));
            } else {
                panic!("Expected inline schema");
            }
        }

        // Edge case: Untagged enum with multi-field tuple variant
        #[test]
        fn test_untagged_multi_field_tuple_variant() {
            let enum_item: syn::ItemEnum = syn::parse_str(
                r"
                #[serde(untagged)]
                enum Message {
                    Text(String),
                    Pair(i32, String),
                    Triple(i32, String, bool),
                }
                ",
            )
            .unwrap();

            let schema = parse_enum_to_schema(&enum_item, &HashSet::new(), &HashMap::new());

            assert!(schema.discriminator.is_none());

            let one_of = schema.clone().one_of.expect("one_of missing");
            assert_eq!(one_of.len(), 3);

            // Single-field tuple should be string schema directly
            if let SchemaRef::Inline(text_variant) = &one_of[0] {
                assert_eq!(text_variant.schema_type, Some(SchemaType::String));
            }

            // Multi-field tuple (Pair) should be array with prefixItems
            if let SchemaRef::Inline(pair_variant) = &one_of[1] {
                assert_eq!(pair_variant.schema_type, Some(SchemaType::Array));
                let prefix_items = pair_variant
                    .prefix_items
                    .as_ref()
                    .expect("prefix_items missing for Pair");
                assert_eq!(prefix_items.len(), 2);
                assert_eq!(pair_variant.min_items, Some(2));
                assert_eq!(pair_variant.max_items, Some(2));
            }

            // Multi-field tuple (Triple) should be array with 3 prefixItems
            if let SchemaRef::Inline(triple_variant) = &one_of[2] {
                assert_eq!(triple_variant.schema_type, Some(SchemaType::Array));
                let prefix_items = triple_variant
                    .prefix_items
                    .as_ref()
                    .expect("prefix_items missing for Triple");
                assert_eq!(prefix_items.len(), 3);
                assert_eq!(triple_variant.min_items, Some(3));
                assert_eq!(triple_variant.max_items, Some(3));
            }

            with_settings!({ snapshot_suffix => "untagged_multi_field_tuple" }, {
                assert_debug_snapshot!(schema);
            });
        }
    }
}