openapi-to-rust 0.5.2

Generate strongly-typed Rust structs, HTTP clients, and SSE streaming clients from OpenAPI 3.1 specifications
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
use crate::extensions::Extensions;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct OpenApiSpec {
    pub openapi: String,
    pub info: Info,
    #[serde(rename = "jsonSchemaDialect", default)]
    pub json_schema_dialect: Option<String>,
    #[serde(default)]
    pub servers: Option<Vec<Server>>,
    #[serde(default)]
    pub paths: Option<BTreeMap<String, PathItem>>,
    #[serde(default)]
    pub webhooks: Option<BTreeMap<String, PathItem>>,
    #[serde(default)]
    pub components: Option<Components>,
    #[serde(default)]
    pub security: Option<Vec<BTreeMap<String, Vec<String>>>>,
    #[serde(default)]
    pub tags: Option<Vec<Tag>>,
    #[serde(rename = "externalDocs", default)]
    pub external_docs: Option<ExternalDocs>,
    /// 3.2 ยง"$self" โ€” see Appendix F base-URI rules. Captured but not yet used.
    #[serde(rename = "$self", default)]
    pub self_uri: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Info {
    pub title: String,
    #[serde(default)]
    pub summary: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(rename = "termsOfService", default)]
    pub terms_of_service: Option<String>,
    #[serde(default)]
    pub contact: Option<Value>,
    #[serde(default)]
    pub license: Option<Value>,
    #[serde(default)]
    pub version: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Components {
    #[serde(default)]
    pub schemas: Option<BTreeMap<String, Schema>>,
    #[serde(default)]
    pub responses: Option<BTreeMap<String, Response>>,
    #[serde(default)]
    pub parameters: Option<BTreeMap<String, Parameter>>,
    #[serde(default)]
    pub examples: Option<BTreeMap<String, Example>>,
    #[serde(rename = "requestBodies", default)]
    pub request_bodies: Option<BTreeMap<String, RequestBody>>,
    #[serde(default)]
    pub headers: Option<BTreeMap<String, Header>>,
    #[serde(rename = "securitySchemes", default)]
    pub security_schemes: Option<BTreeMap<String, SecurityScheme>>,
    #[serde(default)]
    pub links: Option<BTreeMap<String, Link>>,
    #[serde(default)]
    pub callbacks: Option<BTreeMap<String, Callback>>,
    /// 3.1+ ยงComponents โ€” reusable Path Items.
    #[serde(rename = "pathItems", default)]
    pub path_items: Option<BTreeMap<String, PathItem>>,
    /// 3.2 ยงComponents โ€” reusable Media Types.
    #[serde(rename = "mediaTypes", default)]
    pub media_types: Option<BTreeMap<String, MediaType>>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum Schema {
    /// Schema reference
    Reference {
        #[serde(rename = "$ref")]
        reference: String,
        #[serde(flatten)]
        extra: BTreeMap<String, Value>,
    },
    /// Recursive reference (older draft, kept for OAS 3.0 compatibility)
    RecursiveRef {
        #[serde(rename = "$recursiveRef")]
        recursive_ref: String,
        #[serde(flatten)]
        extra: BTreeMap<String, Value>,
    },
    /// Dynamic reference per JSON Schema 2020-12 (OAS 3.1+).
    /// `$dynamicRef` resolves against the nearest enclosing `$dynamicAnchor`.
    /// J1: modeled today; full dynamic resolution at analysis time is a
    /// follow-up. Self-references via `$dynamicRef: "#x"` are treated as
    /// recursive references to the schema bearing `$dynamicAnchor: "x"`.
    DynamicRef {
        #[serde(rename = "$dynamicRef")]
        dynamic_ref: String,
        #[serde(flatten)]
        extra: BTreeMap<String, Value>,
    },
    /// OneOf union
    OneOf {
        #[serde(rename = "oneOf")]
        one_of: Vec<Schema>,
        discriminator: Option<Discriminator>,
        #[serde(flatten)]
        details: SchemaDetails,
    },
    /// AnyOf union (must come before Typed to handle type + anyOf patterns)
    AnyOf {
        #[serde(rename = "type")]
        schema_type: Option<SchemaType>,
        #[serde(rename = "anyOf")]
        any_of: Vec<Schema>,
        discriminator: Option<Discriminator>,
        #[serde(flatten)]
        details: SchemaDetails,
    },
    /// Schema with `type` as an array (OpenAPI 3.1 / JSON Schema 2020-12).
    /// The canonical 3.1 way to express a nullable type is
    /// `type: ["string", "null"]`. Listed before `Typed` so the array form
    /// matches first.
    TypedMulti {
        #[serde(rename = "type")]
        schema_types: Vec<SchemaType>,
        #[serde(flatten)]
        details: SchemaDetails,
    },
    /// Schema with a single explicit type
    Typed {
        #[serde(rename = "type")]
        schema_type: SchemaType,
        #[serde(flatten)]
        details: SchemaDetails,
    },
    /// AllOf composition
    AllOf {
        #[serde(rename = "allOf")]
        all_of: Vec<Schema>,
        #[serde(flatten)]
        details: SchemaDetails,
    },
    /// Schema without explicit type (inferred from other fields)
    Untyped {
        #[serde(flatten)]
        details: SchemaDetails,
    },
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SchemaType {
    String,
    Integer,
    Number,
    Boolean,
    Array,
    Object,
    #[serde(rename = "null")]
    Null,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct SchemaDetails {
    pub description: Option<String>,
    pub nullable: Option<bool>,

    // OpenAPI 3.0 recursive support (obsoleted by JSON Schema 2020-12).
    #[serde(rename = "$recursiveAnchor")]
    pub recursive_anchor: Option<bool>,

    // JSON Schema 2020-12 dynamic anchors (J1).
    #[serde(rename = "$dynamicAnchor")]
    pub dynamic_anchor: Option<String>,
    #[serde(rename = "$id")]
    pub schema_id: Option<String>,

    // String-specific
    #[serde(rename = "enum")]
    pub enum_values: Option<Vec<Value>>,
    pub format: Option<String>,
    pub default: Option<Value>,
    #[serde(rename = "const")]
    pub const_value: Option<Value>,

    // Object-specific
    pub properties: Option<BTreeMap<String, Schema>>,
    pub required: Option<Vec<String>>,
    #[serde(rename = "additionalProperties")]
    pub additional_properties: Option<AdditionalProperties>,

    // Array-specific
    pub items: Option<Box<Schema>>,

    // Number-specific
    pub minimum: Option<f64>,
    pub maximum: Option<f64>,

    // Validation
    #[serde(rename = "minLength")]
    pub min_length: Option<u64>,
    #[serde(rename = "maxLength")]
    pub max_length: Option<u64>,
    pub pattern: Option<String>,
    /// In 3.0/Swagger this was a `bool` flag relative to `minimum`; in 3.1
    /// (JSON Schema 2020-12) it's a number. Accept either to round-trip
    /// real-world specs. (Tracked under J3 โ€” proper validation lowering.)
    #[serde(rename = "exclusiveMinimum")]
    pub exclusive_minimum: Option<ExclusiveBound>,
    #[serde(rename = "exclusiveMaximum")]
    pub exclusive_maximum: Option<ExclusiveBound>,
    #[serde(rename = "multipleOf")]
    pub multiple_of: Option<f64>,
    #[serde(rename = "minItems")]
    pub min_items: Option<u64>,
    #[serde(rename = "maxItems")]
    pub max_items: Option<u64>,
    #[serde(rename = "uniqueItems")]
    pub unique_items: Option<bool>,
    #[serde(rename = "minProperties")]
    pub min_properties: Option<u64>,
    #[serde(rename = "maxProperties")]
    pub max_properties: Option<u64>,

    // JSON Schema 2020-12 array keywords (J4, J8).
    #[serde(rename = "prefixItems")]
    pub prefix_items: Option<Vec<Schema>>,
    pub contains: Option<Box<Schema>>,
    #[serde(rename = "minContains")]
    pub min_contains: Option<u64>,
    #[serde(rename = "maxContains")]
    pub max_contains: Option<u64>,

    // JSON Schema 2020-12 object keywords (J5, J6, J7).
    #[serde(rename = "patternProperties")]
    pub pattern_properties: Option<BTreeMap<String, Schema>>,
    #[serde(rename = "propertyNames")]
    pub property_names: Option<Box<Schema>>,
    #[serde(rename = "unevaluatedProperties")]
    pub unevaluated_properties: Option<AdditionalProperties>,
    #[serde(rename = "unevaluatedItems")]
    pub unevaluated_items: Option<AdditionalProperties>,
    #[serde(rename = "dependentRequired")]
    pub dependent_required: Option<BTreeMap<String, Vec<String>>>,
    #[serde(rename = "dependentSchemas")]
    pub dependent_schemas: Option<BTreeMap<String, Schema>>,

    // JSON Schema 2020-12 content keywords (J8).
    #[serde(rename = "contentEncoding")]
    pub content_encoding: Option<String>,
    #[serde(rename = "contentMediaType")]
    pub content_media_type: Option<String>,
    #[serde(rename = "contentSchema")]
    pub content_schema: Option<Box<Schema>>,

    // JSON Schema 2020-12 conditional keywords.
    #[serde(rename = "if")]
    pub if_schema: Option<Box<Schema>>,
    #[serde(rename = "then")]
    pub then_schema: Option<Box<Schema>>,
    #[serde(rename = "else")]
    pub else_schema: Option<Box<Schema>>,
    pub not: Option<Box<Schema>>,

    // 3.0 deprecated annotations now first-class (kept since openai-responses fixture is OAS 3.0).
    pub title: Option<String>,
    pub deprecated: Option<bool>,
    #[serde(rename = "readOnly")]
    pub read_only: Option<bool>,
    #[serde(rename = "writeOnly")]
    pub write_only: Option<bool>,
    pub examples: Option<Vec<Value>>,
    pub example: Option<Value>,
    /// JSON Schema annotation `$comment`.
    #[serde(rename = "$comment")]
    pub comment: Option<String>,
    #[serde(rename = "$schema")]
    pub schema_keyword: Option<String>,
    #[serde(rename = "$defs")]
    pub defs: Option<BTreeMap<String, Schema>>,

    // Extensions and unknown fields. After J5โ€“J8 above this should be x-*-only
    // for well-formed OAS 3.1+ specs.
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// 3.0 used `exclusiveMinimum: true` as a bool flag against `minimum`;
/// 3.1 (JSON Schema 2020-12) uses `exclusiveMinimum: <number>`.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ExclusiveBound {
    Bool(bool),
    Number(f64),
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum AdditionalProperties {
    Boolean(bool),
    Schema(Box<Schema>),
}

/// OpenAPI Example Object (H6).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Example {
    #[serde(default)]
    pub summary: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    /// Singular embedded value. Mutually exclusive with `external_value`.
    #[serde(default)]
    pub value: Option<Value>,
    #[serde(rename = "externalValue", default)]
    pub external_value: Option<String>,
    /// 3.2 ยง"Example Object" โ€” typed pre-serialization data.
    #[serde(rename = "dataValue", default)]
    pub data_value: Option<Value>,
    /// 3.2 ยง"Example Object" โ€” already-serialized form.
    #[serde(rename = "serializedValue", default)]
    pub serialized_value: Option<String>,
    #[serde(rename = "$ref", default)]
    pub reference: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

/// OpenAPI Link Object (H7).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Link {
    #[serde(rename = "operationRef", default)]
    pub operation_ref: Option<String>,
    #[serde(rename = "operationId", default)]
    pub operation_id: Option<String>,
    #[serde(default)]
    pub parameters: Option<BTreeMap<String, Value>>,
    #[serde(rename = "requestBody", default)]
    pub request_body: Option<Value>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub server: Option<Server>,
    #[serde(rename = "$ref", default)]
    pub reference: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

/// OpenAPI Callback Object (H8). A map keyed by runtime-expression URL
/// templates, with Path Item values.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(transparent)]
pub struct Callback(pub BTreeMap<String, PathItem>);

/// OpenAPI Encoding Object (H4). Used inside `multipart/form-data` and
/// `application/x-www-form-urlencoded` Media Type bodies.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Encoding {
    #[serde(rename = "contentType", default)]
    pub content_type: Option<String>,
    #[serde(default)]
    pub headers: Option<BTreeMap<String, Header>>,
    #[serde(default)]
    pub style: Option<String>,
    #[serde(default)]
    pub explode: Option<bool>,
    #[serde(rename = "allowReserved", default)]
    pub allow_reserved: Option<bool>,
    /// 3.2 ยง"Encoding Object" โ€” nested encoding for arrays of items.
    #[serde(rename = "itemEncoding", default)]
    pub item_encoding: Option<Box<Encoding>>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

/// OpenAPI Header Object (H5). Structurally a Parameter minus the `name`
/// and `in` fields. Used in Response.headers, Encoding.headers, and
/// Components.headers.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Header {
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub required: Option<bool>,
    #[serde(default)]
    pub deprecated: Option<bool>,
    #[serde(rename = "allowEmptyValue", default)]
    pub allow_empty_value: Option<bool>,
    #[serde(default)]
    pub style: Option<String>,
    #[serde(default)]
    pub explode: Option<bool>,
    #[serde(rename = "allowReserved", default)]
    pub allow_reserved: Option<bool>,
    #[serde(default)]
    pub schema: Option<Schema>,
    #[serde(default)]
    pub content: Option<BTreeMap<String, MediaType>>,
    #[serde(default)]
    pub example: Option<Value>,
    #[serde(default)]
    pub examples: Option<Value>,
    #[serde(rename = "$ref", default)]
    pub reference: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

/// OpenAPI Security Scheme Object (H2). Covers all 3.x scheme types:
/// apiKey, http (basic/bearer/digest), oauth2 (with flows), openIdConnect,
/// and 3.1+ mutualTLS.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "type")]
pub enum SecurityScheme {
    #[serde(rename = "apiKey")]
    ApiKey {
        name: String,
        #[serde(rename = "in")]
        location: String, // "query" | "header" | "cookie"
        #[serde(default)]
        description: Option<String>,
        /// 3.2 ยง"Security Scheme Object" โ€” D10.
        #[serde(default)]
        deprecated: Option<bool>,
        #[serde(flatten, default)]
        extensions: Extensions,
    },
    #[serde(rename = "http")]
    Http {
        scheme: String, // "basic" | "bearer" | "digest" | โ€ฆ
        #[serde(rename = "bearerFormat", default)]
        bearer_format: Option<String>,
        #[serde(default)]
        description: Option<String>,
        #[serde(default)]
        deprecated: Option<bool>,
        #[serde(flatten, default)]
        extensions: Extensions,
    },
    #[serde(rename = "mutualTLS")]
    MutualTls {
        #[serde(default)]
        description: Option<String>,
        #[serde(default)]
        deprecated: Option<bool>,
        #[serde(flatten, default)]
        extensions: Extensions,
    },
    #[serde(rename = "oauth2")]
    OAuth2 {
        // Boxed to keep the SecurityScheme enum's variants similarly sized
        // (the OAuthFlows tree is ~800 bytes; clippy::large_enum_variant
        // flagged the disparity).
        flows: Box<OAuthFlows>,
        #[serde(default)]
        description: Option<String>,
        /// 3.2 ยง"Security Scheme Object" โ€” well-known metadata URL (D4).
        #[serde(rename = "oauth2MetadataUrl", default)]
        oauth2_metadata_url: Option<String>,
        #[serde(default)]
        deprecated: Option<bool>,
        #[serde(flatten, default)]
        extensions: Extensions,
    },
    #[serde(rename = "openIdConnect")]
    OpenIdConnect {
        #[serde(rename = "openIdConnectUrl")]
        open_id_connect_url: String,
        #[serde(default)]
        description: Option<String>,
        #[serde(default)]
        deprecated: Option<bool>,
        #[serde(flatten, default)]
        extensions: Extensions,
    },
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct OAuthFlows {
    #[serde(default)]
    pub implicit: Option<OAuthFlow>,
    #[serde(default)]
    pub password: Option<OAuthFlow>,
    #[serde(rename = "clientCredentials", default)]
    pub client_credentials: Option<OAuthFlow>,
    #[serde(rename = "authorizationCode", default)]
    pub authorization_code: Option<OAuthFlow>,
    /// 3.2 ยง"OAuth Flows Object" โ€” device authorization flow (D4).
    #[serde(rename = "deviceAuthorization", default)]
    pub device_authorization: Option<OAuthFlow>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct OAuthFlow {
    #[serde(rename = "authorizationUrl", default)]
    pub authorization_url: Option<String>,
    #[serde(rename = "tokenUrl", default)]
    pub token_url: Option<String>,
    #[serde(rename = "refreshUrl", default)]
    pub refresh_url: Option<String>,
    /// 3.2 ยง"OAuth Flow Object" โ€” required for `deviceAuthorization` (D4).
    #[serde(rename = "deviceAuthorizationUrl", default)]
    pub device_authorization_url: Option<String>,
    pub scopes: BTreeMap<String, String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

/// OpenAPI External Documentation Object (H10).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ExternalDocs {
    pub url: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

/// OpenAPI Tag Object (H9 + D5 โ€” 3.2 added summary/parent/kind).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Tag {
    pub name: String,
    /// 3.2 ยง"Tag Object" โ€” short summary of the tag.
    #[serde(default)]
    pub summary: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    /// 3.2 ยง"Tag Object" โ€” name of a parent tag for hierarchical organisation.
    #[serde(default)]
    pub parent: Option<String>,
    /// 3.2 ยง"Tag Object" โ€” categorisation hint (e.g. "feature", "audience",
    /// "compliance"). Free-form string; consumers MAY define their own
    /// vocabulary.
    #[serde(default)]
    pub kind: Option<String>,
    #[serde(rename = "externalDocs", default)]
    pub external_docs: Option<ExternalDocs>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

/// OpenAPI Server Object (H1). Multiple servers, server variables, and
/// 3.2's `name` field are all modeled.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Server {
    pub url: String,
    /// 3.2 ยง"Server Object" โ€” server identifier for runtime selection (D8).
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub variables: Option<BTreeMap<String, ServerVariable>>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ServerVariable {
    /// REQUIRED in 3.0/3.1. In 3.2 this MAY be omitted when `enum` is present.
    #[serde(default)]
    pub default: Option<String>,
    #[serde(rename = "enum", default)]
    pub enum_values: Option<Vec<String>>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Discriminator {
    #[serde(rename = "propertyName")]
    pub property_name: String,
    #[serde(default)]
    pub mapping: Option<BTreeMap<String, String>>,
    /// 3.2 ยง"Discriminator Object" โ€” fallback mapping target when the
    /// discriminator value is unknown (D9). Captured today; a future bead
    /// will emit a `_Other(Value)` enum variant when this is set.
    #[serde(rename = "defaultMapping", default)]
    pub default_mapping: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

impl Schema {
    /// Get the schema type if explicitly set. For `Schema::TypedMulti` the
    /// "primary" non-null type is returned; if the array contained only `null`
    /// then `Some(&SchemaType::Null)` is returned.
    pub fn schema_type(&self) -> Option<&SchemaType> {
        match self {
            Schema::Typed { schema_type, .. } => Some(schema_type),
            Schema::TypedMulti { schema_types, .. } => schema_types
                .iter()
                .find(|t| **t != SchemaType::Null)
                .or_else(|| schema_types.first()),
            _ => None,
        }
    }

    /// True when the schema's type set explicitly contains `null`.
    /// (3.1 canonical nullability via `type: ["X", "null"]`.)
    pub fn type_array_contains_null(&self) -> bool {
        match self {
            Schema::TypedMulti { schema_types, .. } => schema_types.contains(&SchemaType::Null),
            _ => false,
        }
    }

    /// Get schema details
    pub fn details(&self) -> &SchemaDetails {
        static EMPTY_DETAILS: Lazy<SchemaDetails> = Lazy::new(SchemaDetails::default);
        match self {
            Schema::Typed { details, .. } => details,
            Schema::TypedMulti { details, .. } => details,
            Schema::Reference { .. } | Schema::RecursiveRef { .. } | Schema::DynamicRef { .. } => {
                &EMPTY_DETAILS
            }
            Schema::OneOf { details, .. } => details,
            Schema::AnyOf { details, .. } => details,
            Schema::AllOf { details, .. } => details,
            Schema::Untyped { details } => details,
        }
    }

    /// Get mutable schema details
    pub fn details_mut(&mut self) -> &mut SchemaDetails {
        match self {
            Schema::Typed { details, .. } => details,
            Schema::TypedMulti { details, .. } => details,
            Schema::Reference { .. } => {
                panic!("Cannot get mutable details for reference schema")
            }
            Schema::RecursiveRef { .. } => {
                panic!("Cannot get mutable details for recursive reference schema")
            }
            Schema::DynamicRef { .. } => {
                panic!("Cannot get mutable details for dynamic reference schema")
            }
            Schema::OneOf { details, .. } => details,
            Schema::AnyOf { details, .. } => details,
            Schema::AllOf { details, .. } => details,
            Schema::Untyped { details } => details,
        }
    }

    /// Check if this is any kind of reference (regular or recursive)
    pub fn is_reference(&self) -> bool {
        matches!(self, Schema::Reference { .. } | Schema::RecursiveRef { .. })
    }

    /// Get reference string if this is a reference
    pub fn reference(&self) -> Option<&str> {
        match self {
            Schema::Reference { reference, .. } => Some(reference),
            _ => None,
        }
    }

    /// Get recursive reference string if this is a recursive reference
    pub fn recursive_reference(&self) -> Option<&str> {
        match self {
            Schema::RecursiveRef { recursive_ref, .. } => Some(recursive_ref),
            _ => None,
        }
    }

    /// Check if this is a discriminated union
    pub fn is_discriminated_union(&self) -> bool {
        match self {
            Schema::OneOf { discriminator, .. } => discriminator.is_some(),
            Schema::AnyOf { discriminator, .. } => discriminator.is_some(),
            _ => false,
        }
    }

    /// Get discriminator if this is a discriminated union
    pub fn discriminator(&self) -> Option<&Discriminator> {
        match self {
            Schema::OneOf { discriminator, .. } => discriminator.as_ref(),
            Schema::AnyOf { discriminator, .. } => discriminator.as_ref(),
            _ => None,
        }
    }

    /// Get union variants
    pub fn union_variants(&self) -> Option<&[Schema]> {
        match self {
            Schema::OneOf { one_of, .. } => Some(one_of),
            Schema::AnyOf { any_of, .. } => Some(any_of),
            _ => None,
        }
    }

    /// Check if this appears to be a nullable pattern (anyOf or oneOf with null)
    pub fn is_nullable_pattern(&self) -> bool {
        let variants = match self {
            Schema::AnyOf { any_of, .. } => any_of,
            Schema::OneOf { one_of, .. } => one_of,
            _ => return false,
        };
        variants.len() == 2
            && variants
                .iter()
                .any(|s| matches!(s.schema_type(), Some(SchemaType::Null)))
    }

    /// Get the non-null variant from a nullable pattern
    pub fn non_null_variant(&self) -> Option<&Schema> {
        if !self.is_nullable_pattern() {
            return None;
        }
        let variants = match self {
            Schema::AnyOf { any_of, .. } => any_of,
            Schema::OneOf { one_of, .. } => one_of,
            _ => return None,
        };
        variants
            .iter()
            .find(|s| !matches!(s.schema_type(), Some(SchemaType::Null)))
    }

    /// Infer schema type from structure if not explicitly set
    pub fn inferred_type(&self) -> Option<SchemaType> {
        match self {
            Schema::Typed { schema_type, .. } => Some(schema_type.clone()),
            Schema::TypedMulti { .. } => self.schema_type().cloned(),
            Schema::Untyped { details } => {
                // Infer from structure
                if details.properties.is_some() {
                    Some(SchemaType::Object)
                } else if details.items.is_some() {
                    Some(SchemaType::Array)
                } else if details.enum_values.is_some() {
                    Some(SchemaType::String) // Assume string enum
                } else {
                    None
                }
            }
            _ => None,
        }
    }
}

impl SchemaDetails {
    /// Check if this schema is nullable
    pub fn is_nullable(&self) -> bool {
        self.nullable.unwrap_or(false)
    }

    /// Check if this is a string enum
    ///
    /// A standalone string `const` (no `enum` array) is treated as a
    /// degenerate single-value enum so the generator emits a tightly-typed
    /// single-variant enum instead of a bare `String`. See issue #10.
    pub fn is_string_enum(&self) -> bool {
        self.enum_values.is_some() || self.const_string_value().is_some()
    }

    /// Get enum values as strings if this is a string enum.
    ///
    /// Falls back to `[const_value]` when `enum` is absent but `const` is a
    /// string, so a property like `{ "type": "string", "const": "X" }`
    /// produces a single-variant enum.
    pub fn string_enum_values(&self) -> Option<Vec<String>> {
        if let Some(values) = self.enum_values.as_ref() {
            // Tolerate non-string scalars in `enum` for `type: string` schemas
            // (gitpod has `enum: [2000, 5000, ...]` on a string-typed field).
            // Without this, `filter_map(.as_str())` produced an empty Vec
            // and we emitted an empty enum that fails to compile.
            return Some(
                values
                    .iter()
                    .map(|v| match v {
                        Value::String(s) => s.clone(),
                        Value::Number(n) => n.to_string(),
                        Value::Bool(b) => b.to_string(),
                        Value::Null => "null".to_string(),
                        _ => v.to_string(),
                    })
                    .collect(),
            );
        }
        self.const_string_value().map(|s| vec![s])
    }

    fn const_string_value(&self) -> Option<String> {
        self.const_value
            .as_ref()
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
    }

    /// Check if a field is required
    pub fn is_field_required(&self, field_name: &str) -> bool {
        self.required
            .as_ref()
            .map(|req| req.contains(&field_name.to_string()))
            .unwrap_or(false)
    }
}

/// OpenAPI Path Item Object
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PathItem {
    #[serde(default)]
    pub summary: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    pub get: Option<Operation>,
    pub put: Option<Operation>,
    pub post: Option<Operation>,
    pub delete: Option<Operation>,
    pub options: Option<Operation>,
    pub head: Option<Operation>,
    pub patch: Option<Operation>,
    pub trace: Option<Operation>,
    /// 3.2 ยง"Path Item Object" โ€” `QUERY` HTTP method (D1). Originally
    /// proposed for safe, idempotent reads with a body.
    pub query: Option<Operation>,
    /// 3.2 ยง"Path Item Object" โ€” extension map for HTTP methods beyond the
    /// well-known ones (e.g. WebDAV's PROPFIND, SEARCH; LINK/UNLINK). Keys
    /// are uppercase method names (D1).
    #[serde(rename = "additionalOperations", default)]
    pub additional_operations: Option<BTreeMap<String, Operation>>,
    pub parameters: Option<Vec<Parameter>>,
    #[serde(default)]
    pub servers: Option<Vec<Server>>,
    #[serde(rename = "$ref", default)]
    pub reference: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

impl PathItem {
    /// Get all operations in this path item, including 3.2's `query`
    /// (D1) and any custom verbs declared in `additionalOperations`.
    pub fn operations(&self) -> Vec<(&str, &Operation)> {
        let mut ops = Vec::new();
        if let Some(ref op) = self.get {
            ops.push(("get", op));
        }
        if let Some(ref op) = self.put {
            ops.push(("put", op));
        }
        if let Some(ref op) = self.post {
            ops.push(("post", op));
        }
        if let Some(ref op) = self.delete {
            ops.push(("delete", op));
        }
        if let Some(ref op) = self.options {
            ops.push(("options", op));
        }
        if let Some(ref op) = self.head {
            ops.push(("head", op));
        }
        if let Some(ref op) = self.patch {
            ops.push(("patch", op));
        }
        if let Some(ref op) = self.trace {
            ops.push(("trace", op));
        }
        if let Some(ref op) = self.query {
            ops.push(("query", op));
        }
        if let Some(map) = &self.additional_operations {
            for (verb, op) in map {
                ops.push((verb.as_str(), op));
            }
        }
        ops
    }
}

/// OpenAPI Operation Object
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Operation {
    #[serde(rename = "operationId", default)]
    pub operation_id: Option<String>,
    #[serde(default)]
    pub summary: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub tags: Option<Vec<String>>,
    #[serde(default)]
    pub deprecated: Option<bool>,
    pub parameters: Option<Vec<Parameter>>,
    #[serde(rename = "requestBody")]
    pub request_body: Option<RequestBody>,
    pub responses: Option<BTreeMap<String, Response>>,
    #[serde(default)]
    pub callbacks: Option<BTreeMap<String, Callback>>,
    #[serde(default)]
    pub security: Option<Vec<BTreeMap<String, Vec<String>>>>,
    #[serde(default)]
    pub servers: Option<Vec<Server>>,
    #[serde(rename = "externalDocs", default)]
    pub external_docs: Option<ExternalDocs>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

/// OpenAPI Parameter Object
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Parameter {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(rename = "in", default)]
    pub location: Option<String>,
    #[serde(default)]
    pub required: Option<bool>,
    #[serde(default)]
    pub deprecated: Option<bool>,
    #[serde(rename = "allowEmptyValue", default)]
    pub allow_empty_value: Option<bool>,
    #[serde(default)]
    pub style: Option<String>,
    #[serde(default)]
    pub explode: Option<bool>,
    #[serde(rename = "allowReserved", default)]
    pub allow_reserved: Option<bool>,
    #[serde(default)]
    pub schema: Option<Schema>,
    #[serde(default)]
    pub content: Option<BTreeMap<String, MediaType>>,
    #[serde(default)]
    pub example: Option<Value>,
    #[serde(default)]
    pub examples: Option<BTreeMap<String, Example>>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(rename = "$ref", default)]
    pub reference: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

/// OpenAPI Request Body Object
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RequestBody {
    pub content: Option<BTreeMap<String, MediaType>>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub required: Option<bool>,
    #[serde(rename = "$ref", default)]
    pub reference: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

/// Returns true for media types whose payload is JSON.
///
/// Matches `application/json` exactly, plus any RFC 6839 structured-syntax
/// suffix variant of the form `application/<subtype>+json`
/// (e.g. `application/vnd.api+json`, `application/hal+json`,
/// `application/problem+json`). Trailing parameters such as
/// `; charset=utf-8` are tolerated.
pub fn is_json_media_type(ct: &str) -> bool {
    let essence = ct
        .split(';')
        .next()
        .unwrap_or(ct)
        .trim()
        .to_ascii_lowercase();
    if essence == "application/json" {
        return true;
    }
    if let Some(subtype) = essence.strip_prefix("application/") {
        return subtype.ends_with("+json");
    }
    false
}

/// Returns true for `application/x-www-form-urlencoded` (with optional
/// parameters).
pub fn is_form_urlencoded_media_type(ct: &str) -> bool {
    let essence = ct
        .split(';')
        .next()
        .unwrap_or(ct)
        .trim()
        .to_ascii_lowercase();
    essence == "application/x-www-form-urlencoded"
}

fn find_json_content(content: &BTreeMap<String, MediaType>) -> Option<(&str, &MediaType)> {
    if let Some(mt) = content.get("application/json") {
        return Some(("application/json", mt));
    }
    content
        .iter()
        .find(|(ct, _)| is_json_media_type(ct))
        .map(|(ct, mt)| (ct.as_str(), mt))
}

impl RequestBody {
    /// Get schema for any JSON content type
    ///
    /// Prefers the canonical `application/json` entry, then falls back to
    /// any `application/*+json` variant (RFC 6839) such as
    /// `application/vnd.api+json` or `application/hal+json`.
    pub fn json_schema(&self) -> Option<&Schema> {
        self.content
            .as_ref()
            .and_then(find_json_content)
            .and_then(|(_, media_type)| media_type.schema.as_ref())
    }

    /// Get the best content type and its schema, preferring JSON over others
    pub fn best_content(&self) -> Option<(&str, Option<&Schema>)> {
        let content = self.content.as_ref()?;

        if let Some((ct, media_type)) = find_json_content(content) {
            return Some((ct, media_type.schema.as_ref()));
        }

        const PRIORITY: &[&str] = &[
            "application/x-www-form-urlencoded",
            "multipart/form-data",
            "application/octet-stream",
            "text/plain",
        ];
        for ct in PRIORITY {
            if let Some(media_type) = content.get(*ct) {
                return Some((*ct, media_type.schema.as_ref()));
            }
        }
        None
    }
}

/// OpenAPI Response Object
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Response {
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub headers: Option<BTreeMap<String, Header>>,
    #[serde(default)]
    pub content: Option<BTreeMap<String, MediaType>>,
    #[serde(default)]
    pub links: Option<Value>,
    #[serde(rename = "$ref", default)]
    pub reference: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

impl Response {
    /// Get schema for any JSON content type
    ///
    /// Prefers the canonical `application/json` entry, then falls back to
    /// any `application/*+json` variant (RFC 6839) such as
    /// `application/vnd.api+json`, `application/hal+json`, or
    /// `application/problem+json`.
    pub fn json_schema(&self) -> Option<&Schema> {
        self.content
            .as_ref()
            .and_then(find_json_content)
            .and_then(|(_, media_type)| media_type.schema.as_ref())
    }
}

/// OpenAPI Media Type Object
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MediaType {
    #[serde(default)]
    pub schema: Option<Schema>,
    #[serde(default)]
    pub example: Option<Value>,
    #[serde(default)]
    pub examples: Option<BTreeMap<String, Example>>,
    #[serde(default)]
    pub encoding: Option<BTreeMap<String, Encoding>>,
    /// 3.2 ยง"Media Type Object" โ€” schema for each item when streaming
    /// (D3). Common in `text/event-stream` and JSON-lines payloads.
    #[serde(rename = "itemSchema", default)]
    pub item_schema: Option<Schema>,
    /// 3.2 ยง"Media Type Object" โ€” encoding for the leading prefix of a
    /// streamed body (D3).
    #[serde(rename = "prefixEncoding", default)]
    pub prefix_encoding: Option<Vec<Encoding>>,
    /// 3.2 ยง"Media Type Object" โ€” encoding applied to each streamed item
    /// (D3).
    #[serde(rename = "itemEncoding", default)]
    pub item_encoding: Option<Encoding>,
    #[serde(rename = "$ref", default)]
    pub reference: Option<String>,
    #[serde(flatten, default)]
    pub extensions: Extensions,
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_parse_simple_object_schema() {
        let schema_json = json!({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "User name"
                },
                "age": {
                    "type": "integer"
                }
            },
            "required": ["name"]
        });

        let schema: Schema = serde_json::from_value(schema_json).unwrap();

        match schema {
            Schema::Typed {
                schema_type: SchemaType::Object,
                details,
            } => {
                assert!(details.properties.is_some());
                assert_eq!(details.required, Some(vec!["name".to_string()]));
                assert!(details.is_field_required("name"));
                assert!(!details.is_field_required("age"));
            }
            _ => panic!("Expected object schema"),
        }
    }

    #[test]
    fn test_parse_string_enum() {
        let schema_json = json!({
            "type": "string",
            "enum": ["active", "inactive", "pending"],
            "description": "User status"
        });

        let schema: Schema = serde_json::from_value(schema_json).unwrap();

        match schema {
            Schema::Typed {
                schema_type: SchemaType::String,
                details,
            } => {
                assert!(details.is_string_enum());
                let values = details.string_enum_values().unwrap();
                assert_eq!(values, vec!["active", "inactive", "pending"]);
            }
            _ => panic!("Expected string enum schema"),
        }
    }

    #[test]
    fn test_parse_reference_schema() {
        let schema_json = json!({
            "$ref": "#/components/schemas/User"
        });

        let schema: Schema = serde_json::from_value(schema_json).unwrap();

        assert!(schema.is_reference());
        assert_eq!(schema.reference(), Some("#/components/schemas/User"));
    }

    #[test]
    fn test_parse_discriminated_union() {
        let schema_json = json!({
            "oneOf": [
                {"$ref": "#/components/schemas/Dog"},
                {"$ref": "#/components/schemas/Cat"}
            ],
            "discriminator": {
                "propertyName": "petType"
            }
        });

        let schema: Schema = serde_json::from_value(schema_json).unwrap();

        assert!(schema.is_discriminated_union());
        let discriminator = schema.discriminator().unwrap();
        assert_eq!(discriminator.property_name, "petType");
    }

    #[test]
    fn test_parse_nullable_pattern() {
        let schema_json = json!({
            "anyOf": [
                {"$ref": "#/components/schemas/User"},
                {"type": "null"}
            ]
        });

        let schema: Schema = serde_json::from_value(schema_json).unwrap();

        assert!(schema.is_nullable_pattern());
        let non_null = schema.non_null_variant().unwrap();
        assert!(non_null.is_reference());
    }

    #[test]
    fn is_json_media_type_accepts_canonical_and_structured_suffix() {
        // Canonical
        assert!(is_json_media_type("application/json"));
        // Parameters tolerated (RFC 7231 ยง3.1.1.1)
        assert!(is_json_media_type("application/json; charset=utf-8"));
        assert!(is_json_media_type("APPLICATION/JSON"));
        // RFC 6839 +json structured-syntax suffix
        assert!(is_json_media_type("application/vnd.api+json"));
        assert!(is_json_media_type("application/hal+json"));
        assert!(is_json_media_type("application/problem+json"));
        assert!(is_json_media_type("application/ld+json"));
        assert!(is_json_media_type(
            "application/vnd.api+json; charset=utf-8"
        ));
        // Negatives
        assert!(!is_json_media_type("application/xml"));
        assert!(!is_json_media_type("application/x-www-form-urlencoded"));
        assert!(!is_json_media_type("text/plain"));
        assert!(!is_json_media_type("application/jsonbutnotreally"));
        // +json suffix only applies to application/* per RFC 6839
        assert!(!is_json_media_type("text/something+json"));
    }

    #[test]
    fn request_body_json_schema_finds_vnd_api_plus_json() {
        // Mirrors Latitude.sh: request body declared under
        // application/vnd.api+json without a sibling application/json.
        let body_json = json!({
            "required": true,
            "content": {
                "application/vnd.api+json": {
                    "schema": {"$ref": "#/components/schemas/create_api_key"}
                }
            }
        });

        let body: RequestBody = serde_json::from_value(body_json).unwrap();
        let schema = body.json_schema().expect("expected +json schema match");
        assert!(schema.is_reference());
    }

    #[test]
    fn request_body_best_content_prefers_canonical_json_over_plus_json() {
        // When both are present (e.g. Latitude.sh's POST /auth/api_keys),
        // best_content should still pick application/json for backwards
        // compatibility with the existing snapshot suite.
        let body_json = json!({
            "required": true,
            "content": {
                "application/json": {
                    "schema": {"$ref": "#/components/schemas/A"}
                },
                "application/vnd.api+json": {
                    "schema": {"$ref": "#/components/schemas/B"}
                }
            }
        });

        let body: RequestBody = serde_json::from_value(body_json).unwrap();
        let (ct, _) = body.best_content().expect("expected best_content");
        assert_eq!(ct, "application/json");
    }

    #[test]
    fn request_body_best_content_falls_back_to_plus_json() {
        // When only the +json variant is declared, best_content returns
        // it instead of skipping straight to form-urlencoded.
        let body_json = json!({
            "required": true,
            "content": {
                "application/vnd.api+json": {
                    "schema": {"$ref": "#/components/schemas/B"}
                }
            }
        });

        let body: RequestBody = serde_json::from_value(body_json).unwrap();
        let (ct, _) = body.best_content().expect("expected best_content");
        assert_eq!(ct, "application/vnd.api+json");
    }

    #[test]
    fn response_json_schema_finds_vnd_api_plus_json() {
        // Mirrors every Latitude.sh response: schema lives under
        // application/vnd.api+json only.
        let resp_json = json!({
            "description": "OK",
            "content": {
                "application/vnd.api+json": {
                    "schema": {"$ref": "#/components/schemas/api_keys"}
                }
            }
        });

        let resp: Response = serde_json::from_value(resp_json).unwrap();
        let schema = resp.json_schema().expect("expected +json schema match");
        assert!(schema.is_reference());
    }
}