fastapi-openapi 0.3.0

OpenAPI 3.1 types and schema generation for fastapi_rust
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
//! OpenAPI 3.1 specification types.

use crate::schema::Schema;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// OpenAPI 3.1 document.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenApi {
    /// OpenAPI version.
    pub openapi: String,
    /// API information.
    pub info: Info,
    /// Server list.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub servers: Vec<Server>,
    /// Path items.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub paths: HashMap<String, PathItem>,
    /// Reusable components.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub components: Option<Components>,
    /// API tags.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<Tag>,
}

/// API information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Info {
    /// API title.
    pub title: String,
    /// API version.
    pub version: String,
    /// API description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Terms of service URL.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub terms_of_service: Option<String>,
    /// Contact information.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contact: Option<Contact>,
    /// License information.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub license: Option<License>,
}

/// Contact information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Contact {
    /// Name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// URL.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Email.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
}

/// License information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct License {
    /// License name.
    pub name: String,
    /// License URL.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

/// Server information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Server {
    /// Server URL.
    pub url: String,
    /// Server description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Path item (operations for a path).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PathItem {
    /// GET operation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub get: Option<Operation>,
    /// POST operation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub post: Option<Operation>,
    /// PUT operation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub put: Option<Operation>,
    /// DELETE operation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delete: Option<Operation>,
    /// PATCH operation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub patch: Option<Operation>,
    /// OPTIONS operation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub options: Option<Operation>,
    /// HEAD operation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub head: Option<Operation>,
}

/// API operation.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Operation {
    /// Operation ID.
    #[serde(
        rename = "operationId",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub operation_id: Option<String>,
    /// Summary.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    /// Description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Tags.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    /// Parameters.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub parameters: Vec<Parameter>,
    /// Request body.
    #[serde(
        rename = "requestBody",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub request_body: Option<RequestBody>,
    /// Responses.
    pub responses: HashMap<String, Response>,
    /// Deprecated flag.
    #[serde(default, skip_serializing_if = "is_false")]
    pub deprecated: bool,
}

fn is_false(b: &bool) -> bool {
    !*b
}

/// Create default 200 OK response map.
fn default_responses() -> HashMap<String, Response> {
    let mut responses = HashMap::new();
    responses.insert(
        "200".to_string(),
        Response {
            description: "Successful response".to_string(),
            content: HashMap::new(),
        },
    );
    responses
}

/// Operation parameter.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Parameter {
    /// Parameter name.
    pub name: String,
    /// Parameter location.
    #[serde(rename = "in")]
    pub location: ParameterLocation,
    /// Required flag.
    #[serde(default)]
    pub required: bool,
    /// Parameter schema.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<Schema>,
    /// Title for display in documentation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Whether the parameter is deprecated.
    #[serde(default, skip_serializing_if = "is_false")]
    pub deprecated: bool,
    /// Example value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub example: Option<serde_json::Value>,
    /// Named examples.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub examples: HashMap<String, Example>,
}

/// Example object for OpenAPI.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Example {
    /// Summary of the example.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    /// Long description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Example value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub value: Option<serde_json::Value>,
    /// External URL for the example.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub external_value: Option<String>,
}

/// Parameter metadata for OpenAPI documentation.
///
/// This struct captures metadata attributes that can be specified on
/// struct fields using `#[param(...)]` attributes.
///
/// # Example
///
/// ```ignore
/// #[derive(FromRequest)]
/// struct MyQuery {
///     #[param(description = "Search term", deprecated)]
///     q: Option<String>,
///
///     #[param(title = "Page Number", ge = 1)]
///     page: i32,
/// }
/// ```
#[derive(Debug, Clone, Default)]
pub struct ParamMeta {
    /// Display title for the parameter.
    pub title: Option<String>,
    /// Description of the parameter.
    pub description: Option<String>,
    /// Whether the parameter is deprecated.
    pub deprecated: bool,
    /// Whether to include in OpenAPI schema.
    pub include_in_schema: bool,
    /// Example value.
    pub example: Option<serde_json::Value>,
    /// Named examples.
    pub examples: HashMap<String, Example>,
    /// Minimum value constraint (for numbers).
    pub ge: Option<f64>,
    /// Maximum value constraint (for numbers).
    pub le: Option<f64>,
    /// Exclusive minimum (for numbers).
    pub gt: Option<f64>,
    /// Exclusive maximum (for numbers).
    pub lt: Option<f64>,
    /// Minimum length (for strings).
    pub min_length: Option<usize>,
    /// Maximum length (for strings).
    pub max_length: Option<usize>,
    /// Pattern constraint (regex).
    pub pattern: Option<String>,
}

impl ParamMeta {
    /// Create a new parameter metadata with default values.
    #[must_use]
    pub fn new() -> Self {
        Self {
            include_in_schema: true,
            ..Default::default()
        }
    }

    /// Set the title.
    #[must_use]
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the description.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Mark as deprecated.
    #[must_use]
    pub fn deprecated(mut self) -> Self {
        self.deprecated = true;
        self
    }

    /// Exclude from OpenAPI schema.
    #[must_use]
    pub fn exclude_from_schema(mut self) -> Self {
        self.include_in_schema = false;
        self
    }

    /// Set an example value.
    #[must_use]
    pub fn example(mut self, example: serde_json::Value) -> Self {
        self.example = Some(example);
        self
    }

    /// Set minimum value constraint (>=).
    #[must_use]
    pub fn ge(mut self, value: f64) -> Self {
        self.ge = Some(value);
        self
    }

    /// Set maximum value constraint (<=).
    #[must_use]
    pub fn le(mut self, value: f64) -> Self {
        self.le = Some(value);
        self
    }

    /// Set exclusive minimum constraint (>).
    #[must_use]
    pub fn gt(mut self, value: f64) -> Self {
        self.gt = Some(value);
        self
    }

    /// Set exclusive maximum constraint (<).
    #[must_use]
    pub fn lt(mut self, value: f64) -> Self {
        self.lt = Some(value);
        self
    }

    /// Set minimum length for strings.
    #[must_use]
    pub fn min_length(mut self, len: usize) -> Self {
        self.min_length = Some(len);
        self
    }

    /// Set maximum length for strings.
    #[must_use]
    pub fn max_length(mut self, len: usize) -> Self {
        self.max_length = Some(len);
        self
    }

    /// Set a regex pattern constraint.
    #[must_use]
    pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
        self.pattern = Some(pattern.into());
        self
    }

    /// Convert to an OpenAPI Parameter.
    #[must_use]
    pub fn to_parameter(
        &self,
        name: impl Into<String>,
        location: ParameterLocation,
        required: bool,
        schema: Option<Schema>,
    ) -> Parameter {
        Parameter {
            name: name.into(),
            location,
            required,
            schema,
            title: self.title.clone(),
            description: self.description.clone(),
            deprecated: self.deprecated,
            example: self.example.clone(),
            examples: self.examples.clone(),
        }
    }
}

/// Trait for types that provide parameter metadata.
///
/// Implement this trait to enable automatic OpenAPI parameter documentation.
pub trait HasParamMeta {
    /// Get the parameter metadata for this type.
    fn param_meta() -> ParamMeta {
        ParamMeta::new()
    }
}

/// Parameter location.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ParameterLocation {
    /// Path parameter.
    Path,
    /// Query parameter.
    Query,
    /// Header parameter.
    Header,
    /// Cookie parameter.
    Cookie,
}

/// Request body.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RequestBody {
    /// Required flag.
    #[serde(default)]
    pub required: bool,
    /// Content by media type.
    pub content: HashMap<String, MediaType>,
    /// Description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Media type content.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MediaType {
    /// Schema.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<Schema>,
}

/// Response definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Response {
    /// Description.
    pub description: String,
    /// Content by media type.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub content: HashMap<String, MediaType>,
}

/// Reusable components.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Components {
    /// Schema definitions.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub schemas: HashMap<String, Schema>,
}

/// Schema registry for `#/components/schemas`.
///
/// This owns a schema map and provides `register()` helpers that return `$ref`s.
#[derive(Debug, Default)]
pub struct SchemaRegistry {
    schemas: HashMap<String, Schema>,
}

impl SchemaRegistry {
    /// Create an empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            schemas: HashMap::new(),
        }
    }

    /// Register `schema` under `name` if it doesn't already exist, and return a `$ref`.
    ///
    /// This does **not** overwrite an existing entry, which enables stable deduplication.
    pub fn register(&mut self, name: impl Into<String>, schema: Schema) -> Schema {
        let name = name.into();
        self.schemas.entry(name.clone()).or_insert(schema);
        Schema::reference(&name)
    }

    /// Consume the registry and return the underlying schema map.
    #[must_use]
    pub fn into_schemas(self) -> HashMap<String, Schema> {
        self.schemas
    }
}

/// A mutable view into an existing component schema map.
pub struct SchemaRegistryMut<'a> {
    schemas: &'a mut HashMap<String, Schema>,
}

impl SchemaRegistryMut<'_> {
    /// Register `schema` under `name` if it doesn't already exist, and return a `$ref`.
    pub fn register(&mut self, name: impl Into<String>, schema: Schema) -> Schema {
        let name = name.into();
        self.schemas.entry(name.clone()).or_insert(schema);
        Schema::reference(&name)
    }
}

/// API tag.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tag {
    /// Tag name.
    pub name: String,
    /// Tag description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

// ============================================================================
// Tests for ParamMeta
// ============================================================================

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

    #[test]
    fn new_creates_default_with_include_in_schema_true() {
        let meta = ParamMeta::new();
        assert!(meta.include_in_schema);
        assert!(meta.title.is_none());
        assert!(meta.description.is_none());
        assert!(!meta.deprecated);
    }

    #[test]
    fn title_sets_title() {
        let meta = ParamMeta::new().title("User ID");
        assert_eq!(meta.title.as_deref(), Some("User ID"));
    }

    #[test]
    fn description_sets_description() {
        let meta = ParamMeta::new().description("The unique identifier");
        assert_eq!(meta.description.as_deref(), Some("The unique identifier"));
    }

    #[test]
    fn deprecated_marks_as_deprecated() {
        let meta = ParamMeta::new().deprecated();
        assert!(meta.deprecated);
    }

    #[test]
    fn exclude_from_schema_sets_include_false() {
        let meta = ParamMeta::new().exclude_from_schema();
        assert!(!meta.include_in_schema);
    }

    #[test]
    fn example_sets_example_value() {
        let meta = ParamMeta::new().example(serde_json::json!(42));
        assert_eq!(meta.example, Some(serde_json::json!(42)));
    }

    #[test]
    fn ge_sets_minimum_constraint() {
        let meta = ParamMeta::new().ge(1.0);
        assert_eq!(meta.ge, Some(1.0));
    }

    #[test]
    fn le_sets_maximum_constraint() {
        let meta = ParamMeta::new().le(100.0);
        assert_eq!(meta.le, Some(100.0));
    }

    #[test]
    fn gt_sets_exclusive_minimum() {
        let meta = ParamMeta::new().gt(0.0);
        assert_eq!(meta.gt, Some(0.0));
    }

    #[test]
    fn lt_sets_exclusive_maximum() {
        let meta = ParamMeta::new().lt(1000.0);
        assert_eq!(meta.lt, Some(1000.0));
    }

    #[test]
    fn min_length_sets_minimum_string_length() {
        let meta = ParamMeta::new().min_length(3);
        assert_eq!(meta.min_length, Some(3));
    }

    #[test]
    fn max_length_sets_maximum_string_length() {
        let meta = ParamMeta::new().max_length(255);
        assert_eq!(meta.max_length, Some(255));
    }

    #[test]
    fn pattern_sets_regex_constraint() {
        let meta = ParamMeta::new().pattern(r"^\d{4}-\d{2}-\d{2}$");
        assert_eq!(meta.pattern.as_deref(), Some(r"^\d{4}-\d{2}-\d{2}$"));
    }

    #[test]
    fn builder_methods_chain() {
        let meta = ParamMeta::new()
            .title("Page")
            .description("Page number for pagination")
            .ge(1.0)
            .le(1000.0)
            .example(serde_json::json!(1));

        assert_eq!(meta.title.as_deref(), Some("Page"));
        assert_eq!(
            meta.description.as_deref(),
            Some("Page number for pagination")
        );
        assert_eq!(meta.ge, Some(1.0));
        assert_eq!(meta.le, Some(1000.0));
        assert_eq!(meta.example, Some(serde_json::json!(1)));
    }

    #[test]
    fn to_parameter_creates_parameter_with_metadata() {
        let meta = ParamMeta::new()
            .title("User ID")
            .description("Unique user identifier")
            .deprecated()
            .example(serde_json::json!(42));

        let param = meta.to_parameter("user_id", ParameterLocation::Path, true, None);

        assert_eq!(param.name, "user_id");
        assert!(matches!(param.location, ParameterLocation::Path));
        assert!(param.required);
        assert_eq!(param.title.as_deref(), Some("User ID"));
        assert_eq!(param.description.as_deref(), Some("Unique user identifier"));
        assert!(param.deprecated);
        assert_eq!(param.example, Some(serde_json::json!(42)));
    }

    #[test]
    fn to_parameter_with_query_location() {
        let meta = ParamMeta::new().description("Search query");
        let param = meta.to_parameter("q", ParameterLocation::Query, false, None);

        assert_eq!(param.name, "q");
        assert!(matches!(param.location, ParameterLocation::Query));
        assert!(!param.required);
    }

    #[test]
    fn to_parameter_with_header_location() {
        let meta = ParamMeta::new().description("API key");
        let param = meta.to_parameter("X-API-Key", ParameterLocation::Header, true, None);

        assert_eq!(param.name, "X-API-Key");
        assert!(matches!(param.location, ParameterLocation::Header));
    }

    #[test]
    fn to_parameter_with_cookie_location() {
        let meta = ParamMeta::new().description("Session cookie");
        let param = meta.to_parameter("session", ParameterLocation::Cookie, false, None);

        assert_eq!(param.name, "session");
        assert!(matches!(param.location, ParameterLocation::Cookie));
    }

    #[test]
    fn default_param_meta_is_empty() {
        let meta = ParamMeta::default();
        assert!(meta.title.is_none());
        assert!(meta.description.is_none());
        assert!(!meta.deprecated);
        assert!(!meta.include_in_schema); // Default::default() sets to false
        assert!(meta.example.is_none());
        assert!(meta.ge.is_none());
        assert!(meta.le.is_none());
        assert!(meta.gt.is_none());
        assert!(meta.lt.is_none());
        assert!(meta.min_length.is_none());
        assert!(meta.max_length.is_none());
        assert!(meta.pattern.is_none());
    }

    #[test]
    fn string_constraints_together() {
        let meta = ParamMeta::new()
            .min_length(1)
            .max_length(100)
            .pattern(r"^[a-zA-Z]+$");

        assert_eq!(meta.min_length, Some(1));
        assert_eq!(meta.max_length, Some(100));
        assert_eq!(meta.pattern.as_deref(), Some(r"^[a-zA-Z]+$"));
    }

    #[test]
    fn numeric_constraints_together() {
        let meta = ParamMeta::new().gt(0.0).lt(100.0).ge(1.0).le(99.0);

        assert_eq!(meta.gt, Some(0.0));
        assert_eq!(meta.lt, Some(100.0));
        assert_eq!(meta.ge, Some(1.0));
        assert_eq!(meta.le, Some(99.0));
    }
}

// ============================================================================
// Tests for OpenAPI types serialization
// ============================================================================

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

    #[test]
    fn parameter_serializes_location_as_in() {
        let param = Parameter {
            name: "id".to_string(),
            location: ParameterLocation::Path,
            required: true,
            schema: None,
            title: None,
            description: None,
            deprecated: false,
            example: None,
            examples: HashMap::new(),
        };

        let json = serde_json::to_string(&param).unwrap();
        assert!(json.contains(r#""in":"path""#));
    }

    #[test]
    fn parameter_location_serializes_lowercase() {
        let path_json = serde_json::to_string(&ParameterLocation::Path).unwrap();
        assert_eq!(path_json, r#""path""#);

        let query_json = serde_json::to_string(&ParameterLocation::Query).unwrap();
        assert_eq!(query_json, r#""query""#);

        let header_json = serde_json::to_string(&ParameterLocation::Header).unwrap();
        assert_eq!(header_json, r#""header""#);

        let cookie_json = serde_json::to_string(&ParameterLocation::Cookie).unwrap();
        assert_eq!(cookie_json, r#""cookie""#);
    }

    #[test]
    fn parameter_skips_false_deprecated() {
        let param = Parameter {
            name: "id".to_string(),
            location: ParameterLocation::Path,
            required: true,
            schema: None,
            title: None,
            description: None,
            deprecated: false,
            example: None,
            examples: HashMap::new(),
        };

        let json = serde_json::to_string(&param).unwrap();
        assert!(!json.contains("deprecated"));
    }

    #[test]
    fn parameter_includes_true_deprecated() {
        let param = Parameter {
            name: "old_id".to_string(),
            location: ParameterLocation::Path,
            required: true,
            schema: None,
            title: None,
            description: Some("Deprecated, use new_id instead".to_string()),
            deprecated: true,
            example: None,
            examples: HashMap::new(),
        };

        let json = serde_json::to_string(&param).unwrap();
        assert!(json.contains(r#""deprecated":true"#));
    }

    #[test]
    fn openapi_builder_creates_valid_document() {
        let doc = OpenApiBuilder::new("Test API", "1.0.0")
            .description("A test API")
            .server("https://api.example.com", Some("Production".to_string()))
            .tag("users", Some("User operations".to_string()))
            .build();

        assert_eq!(doc.openapi, "3.1.0");
        assert_eq!(doc.info.title, "Test API");
        assert_eq!(doc.info.version, "1.0.0");
        assert_eq!(doc.info.description.as_deref(), Some("A test API"));
        assert_eq!(doc.servers.len(), 1);
        assert_eq!(doc.servers[0].url, "https://api.example.com");
        assert_eq!(doc.tags.len(), 1);
        assert_eq!(doc.tags[0].name, "users");
    }

    #[test]
    fn openapi_serializes_to_valid_json() {
        let doc = OpenApiBuilder::new("Test API", "1.0.0").build();
        let json = serde_json::to_string_pretty(&doc).unwrap();

        assert!(json.contains(r#""openapi": "3.1.0""#));
        assert!(json.contains(r#""title": "Test API""#));
        assert!(json.contains(r#""version": "1.0.0""#));
    }

    #[test]
    fn example_serializes_all_fields() {
        let example = Example {
            summary: Some("Example summary".to_string()),
            description: Some("Example description".to_string()),
            value: Some(serde_json::json!({"key": "value"})),
            external_value: None,
        };

        let json = serde_json::to_string(&example).unwrap();
        assert!(json.contains(r#""summary":"Example summary""#));
        assert!(json.contains(r#""description":"Example description""#));
        assert!(json.contains(r#""value""#));
    }
}

/// OpenAPI document builder.
pub struct OpenApiBuilder {
    info: Info,
    servers: Vec<Server>,
    paths: HashMap<String, PathItem>,
    components: Components,
    tags: Vec<Tag>,
}

impl OpenApiBuilder {
    /// Create a new builder.
    #[must_use]
    pub fn new(title: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            info: Info {
                title: title.into(),
                version: version.into(),
                description: None,
                terms_of_service: None,
                contact: None,
                license: None,
            },
            servers: Vec::new(),
            paths: HashMap::new(),
            components: Components::default(),
            tags: Vec::new(),
        }
    }

    /// Add a description.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.info.description = Some(description.into());
        self
    }

    /// Add a server.
    #[must_use]
    pub fn server(mut self, url: impl Into<String>, description: Option<String>) -> Self {
        self.servers.push(Server {
            url: url.into(),
            description,
        });
        self
    }

    /// Add a tag.
    #[must_use]
    pub fn tag(mut self, name: impl Into<String>, description: Option<String>) -> Self {
        self.tags.push(Tag {
            name: name.into(),
            description,
        });
        self
    }

    /// Add a schema component.
    #[must_use]
    pub fn schema(mut self, name: impl Into<String>, schema: Schema) -> Self {
        self.components.schemas.insert(name.into(), schema);
        self
    }

    /// Access the component schema registry for in-place registration.
    pub fn registry(&mut self) -> SchemaRegistryMut<'_> {
        SchemaRegistryMut {
            schemas: &mut self.components.schemas,
        }
    }

    /// Add a metadata-rich route (from `fastapi-router`) as an OpenAPI operation.
    ///
    /// This is a convenience bridge used by integration tests and by higher-level crates.
    #[allow(clippy::too_many_lines)]
    pub fn add_route(&mut self, route: &fastapi_router::Route) {
        use fastapi_router::Converter as RouteConverter;

        fn param_schema(conv: RouteConverter) -> Schema {
            match conv {
                RouteConverter::Str | RouteConverter::Path => Schema::string(),
                RouteConverter::Int => Schema::integer(Some("int64")),
                RouteConverter::Float => Schema::number(Some("double")),
                RouteConverter::Uuid => Schema::Primitive(crate::schema::PrimitiveSchema {
                    schema_type: crate::schema::SchemaType::String,
                    format: Some("uuid".to_string()),
                    nullable: false,
                }),
            }
        }

        let mut op = Operation {
            operation_id: if route.operation_id.is_empty() {
                None
            } else {
                Some(route.operation_id.clone())
            },
            summary: route.summary.clone(),
            description: route.description.clone(),
            tags: route.tags.clone(),
            deprecated: route.deprecated,
            ..Default::default()
        };

        // Path parameters.
        for p in &route.path_params {
            let mut examples = HashMap::new();
            for (name, value) in &p.examples {
                examples.insert(
                    name.clone(),
                    Example {
                        summary: None,
                        description: None,
                        value: Some(value.clone()),
                        external_value: None,
                    },
                );
            }

            op.parameters.push(Parameter {
                name: p.name.clone(),
                location: ParameterLocation::Path,
                required: true,
                schema: Some(param_schema(p.converter)),
                title: p.title.clone(),
                description: p.description.clone(),
                deprecated: p.deprecated,
                example: p.example.clone(),
                examples,
            });
        }

        // Request body.
        if let Some(schema_name) = &route.request_body_schema {
            let content_type = route
                .request_body_content_type
                .clone()
                .unwrap_or_else(|| "application/json".to_string());
            let mut content = HashMap::new();
            content.insert(
                content_type,
                MediaType {
                    schema: Some(Schema::reference(schema_name)),
                },
            );
            op.request_body = Some(RequestBody {
                required: route.request_body_required,
                content,
                description: None,
            });
        }

        // Responses.
        let mut responses = HashMap::new();
        if route.responses.is_empty() {
            responses = default_responses();
        } else {
            for r in &route.responses {
                let mut content = HashMap::new();
                content.insert(
                    "application/json".to_string(),
                    MediaType {
                        schema: Some(Schema::reference(&r.schema_name)),
                    },
                );
                responses.insert(
                    r.status.to_string(),
                    Response {
                        description: r.description.clone(),
                        content,
                    },
                );
            }
        }
        op.responses = responses;

        let path_item = self.paths.entry(route.path.clone()).or_default();
        match route.method.as_str() {
            "GET" => path_item.get = Some(op),
            "POST" => path_item.post = Some(op),
            "PUT" => path_item.put = Some(op),
            "DELETE" => path_item.delete = Some(op),
            "PATCH" => path_item.patch = Some(op),
            "OPTIONS" => path_item.options = Some(op),
            "HEAD" => path_item.head = Some(op),
            _ => {}
        }
    }

    /// Add multiple routes.
    pub fn add_routes<'a, I>(&mut self, routes: I)
    where
        I: IntoIterator<Item = &'a fastapi_router::Route>,
    {
        for r in routes {
            self.add_route(r);
        }
    }

    /// Add a path operation (GET, POST, etc.).
    ///
    /// This is the primary method for registering routes with OpenAPI.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let builder = OpenApiBuilder::new("My API", "1.0.0")
    ///     .operation("GET", "/users", Operation {
    ///         operation_id: Some("get_users".to_string()),
    ///         summary: Some("List all users".to_string()),
    ///         responses: HashMap::from([
    ///             ("200".to_string(), Response {
    ///                 description: "Success".to_string(),
    ///                 content: HashMap::new(),
    ///             })
    ///         ]),
    ///         ..Default::default()
    ///     });
    /// ```
    #[must_use]
    pub fn operation(
        mut self,
        method: &str,
        path: impl Into<String>,
        operation: Operation,
    ) -> Self {
        let path = path.into();
        let path_item = self.paths.entry(path).or_default();

        match method.to_uppercase().as_str() {
            "GET" => path_item.get = Some(operation),
            "POST" => path_item.post = Some(operation),
            "PUT" => path_item.put = Some(operation),
            "DELETE" => path_item.delete = Some(operation),
            "PATCH" => path_item.patch = Some(operation),
            "OPTIONS" => path_item.options = Some(operation),
            "HEAD" => path_item.head = Some(operation),
            _ => {} // Ignore unknown methods
        }

        self
    }

    /// Add a simple GET endpoint with default 200 response.
    #[must_use]
    pub fn get(self, path: impl Into<String>, operation_id: impl Into<String>) -> Self {
        let operation_id = operation_id.into();
        self.operation(
            "GET",
            path,
            Operation {
                operation_id: if operation_id.is_empty() {
                    None
                } else {
                    Some(operation_id)
                },
                responses: default_responses(),
                ..Default::default()
            },
        )
    }

    /// Add a simple POST endpoint with default 200 response.
    #[must_use]
    pub fn post(self, path: impl Into<String>, operation_id: impl Into<String>) -> Self {
        let operation_id = operation_id.into();
        self.operation(
            "POST",
            path,
            Operation {
                operation_id: if operation_id.is_empty() {
                    None
                } else {
                    Some(operation_id)
                },
                responses: default_responses(),
                ..Default::default()
            },
        )
    }

    /// Add a simple PUT endpoint with default 200 response.
    #[must_use]
    pub fn put(self, path: impl Into<String>, operation_id: impl Into<String>) -> Self {
        let operation_id = operation_id.into();
        self.operation(
            "PUT",
            path,
            Operation {
                operation_id: if operation_id.is_empty() {
                    None
                } else {
                    Some(operation_id)
                },
                responses: default_responses(),
                ..Default::default()
            },
        )
    }

    /// Add a simple DELETE endpoint with default 200 response.
    #[must_use]
    pub fn delete(self, path: impl Into<String>, operation_id: impl Into<String>) -> Self {
        let operation_id = operation_id.into();
        self.operation(
            "DELETE",
            path,
            Operation {
                operation_id: if operation_id.is_empty() {
                    None
                } else {
                    Some(operation_id)
                },
                responses: default_responses(),
                ..Default::default()
            },
        )
    }

    /// Add a simple PATCH endpoint with default 200 response.
    #[must_use]
    pub fn patch(self, path: impl Into<String>, operation_id: impl Into<String>) -> Self {
        let operation_id = operation_id.into();
        self.operation(
            "PATCH",
            path,
            Operation {
                operation_id: if operation_id.is_empty() {
                    None
                } else {
                    Some(operation_id)
                },
                responses: default_responses(),
                ..Default::default()
            },
        )
    }

    /// Build the OpenAPI document.
    #[must_use]
    pub fn build(self) -> OpenApi {
        OpenApi {
            openapi: "3.1.0".to_string(),
            info: self.info,
            servers: self.servers,
            paths: self.paths,
            components: if self.components.schemas.is_empty() {
                None
            } else {
                Some(self.components)
            },
            tags: self.tags,
        }
    }
}