volga-open-api 0.13.1

Volga Open API Integration
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
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
//! Types and utils for OpenAPI route config.

use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use std::collections::BTreeMap;

use mime::{
    APPLICATION_JSON, APPLICATION_OCTET_STREAM, APPLICATION_WWW_FORM_URLENCODED,
    MULTIPART_FORM_DATA, TEXT_EVENT_STREAM, TEXT_PLAIN_UTF_8,
};

use super::{
    op::OpenApiOperation,
    param::OpenApiParameter,
    schema::{FieldConstraint, OpenApiSchema, Probe, Probed, ReadAsMap},
};

/// Converts a value into an HTTP status code.
pub trait IntoStatusCode {
    /// Converts `self` into a `u16` HTTP status code.
    fn into_status_code(self) -> u16;
}

impl IntoStatusCode for u16 {
    #[inline]
    fn into_status_code(self) -> u16 {
        self
    }
}

impl IntoStatusCode for u32 {
    #[inline]
    fn into_status_code(self) -> u16 {
        self as u16
    }
}

impl IntoStatusCode for i32 {
    #[inline]
    fn into_status_code(self) -> u16 {
        self as u16
    }
}

impl IntoStatusCode for http::StatusCode {
    #[inline]
    fn into_status_code(self) -> u16 {
        self.as_u16()
    }
}

#[derive(Clone, Debug)]
enum ResponseBody {
    NoContent,
    Content {
        schema: Box<OpenApiSchema>,
        example: Option<Value>,
        content_type: String,
    },
}

/// What an extractor describes, and therefore what its constraints apply to
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConstraintTarget {
    /// The request body
    RequestBody,
    /// The query parameters this extractor added, which are the ones from
    /// `described_before` onward
    QueryParameter {
        /// How many parameters the operation already described
        described_before: usize,
    },
    /// The path parameters this extractor added; see [`ConstraintTarget::QueryParameter`]
    PathParameter {
        /// How many parameters the operation already described
        described_before: usize,
    },
}

/// A handler input an operation describes without its fields.
///
/// Fields are inferred by driving the type's `Deserialize` impl and recording what it asks
/// for. A struct with a `#[serde(flatten)]` field asks to be read as a map instead - so that
/// the keys it does not name can be collected for the flattened member - and a map does not
/// say which keys it takes, so none of the struct's fields can be inferred, the ones declared
/// beside the flattened member included. Such a request body is described as an object
/// without properties - or as any value, when the struct sits somewhere inside it - and such
/// query parameters are not described at all.
///
/// Describing the input by hand, with [`OpenApiRouteConfig::with_request_schema`] or
/// [`OpenApiRouteConfig::with_query_schema`], takes it off
/// [`OpenApiRouteConfig::undescribed_inputs`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UndescribedInput {
    kind: InputKind,
    type_name: &'static str,
    read_as_map: Option<String>,
}

impl UndescribedInput {
    fn new<T>(kind: InputKind, found: ReadAsMap) -> Self {
        Self {
            kind,
            type_name: std::any::type_name::<T>(),
            read_as_map: (!found.at_root).then_some(found.expecting),
        }
    }

    /// Returns what the input is read into
    pub fn kind(&self) -> InputKind {
        self.kind
    }

    /// Returns the type the extractor reads, as [`std::any::type_name`] spells it
    pub fn type_name(&self) -> &'static str {
        self.type_name
    }

    /// Returns what serde expects of the struct it reads as a map, when that struct sits
    /// inside the type rather than being the type itself: `struct Name`, for a derived one
    pub fn read_as_map(&self) -> Option<&str> {
        self.read_as_map.as_deref()
    }
}

/// What a handler input is read into
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum InputKind {
    /// The request body
    RequestBody,
    /// The query parameters
    QueryParameters,
}

/// Per-route OpenAPI metadata.
#[derive(Clone, Debug, Default)]
pub struct OpenApiRouteConfig {
    tags: Vec<String>,
    docs: Option<Vec<String>>,
    summary: Option<String>,
    description: Option<String>,
    operation_id: Option<String>,
    request_schema: Option<OpenApiSchema>,
    request_example: Option<Value>,
    request_content_type: Option<String>,
    responses: BTreeMap<u16, ResponseBody>,
    extra_parameters: Vec<OpenApiParameter>,
    undescribed: Vec<UndescribedInput>,
}

impl OpenApiRouteConfig {
    /// Returns the handler inputs this operation describes without their fields, because
    /// they cannot be inferred - see [`UndescribedInput`].
    pub fn undescribed_inputs(&self) -> &[UndescribedInput] {
        &self.undescribed
    }

    /// Returns how many parameters this operation already describes.
    ///
    /// Taken before an extractor is described and handed back through [`ConstraintTarget`],
    /// so its constraints reach its own parameters and no others.
    pub fn described_parameters(&self) -> usize {
        self.extra_parameters.len()
    }

    /// Returns a list of docs that this route is assigned to
    pub(crate) fn docs(&self) -> Option<&[String]> {
        self.docs.as_deref()
    }

    /// Adds a tag to the operation.
    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tags.push(tag.into());
        self
    }

    /// Adds multiple tags to the operation.
    pub fn with_tags<I, T>(mut self, tags: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<String>,
    {
        self.tags.extend(tags.into_iter().map(Into::into));
        self
    }

    /// Binds the operation with a document
    pub fn with_doc(mut self, doc: impl Into<String>) -> Self {
        self.docs.get_or_insert_with(Vec::new).push(doc.into());
        self
    }

    /// Binds the operation with documents
    pub fn with_docs<I, S>(mut self, docs: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.docs
            .get_or_insert_with(Vec::new)
            .extend(docs.into_iter().map(Into::into));
        self
    }

    /// Sets the operation summary.
    pub fn with_summary(mut self, summary: impl Into<String>) -> Self {
        self.summary = Some(summary.into());
        self
    }

    /// Sets the operation description.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Sets the operation id.
    pub fn with_operation_id(mut self, operation_id: impl Into<String>) -> Self {
        self.operation_id = Some(operation_id.into());
        self
    }

    /// Sets the request body schema for this operation.
    ///
    /// This is how a body whose fields cannot be inferred is described - see
    /// [`UndescribedInput`].
    pub fn with_request_schema(mut self, schema: OpenApiSchema) -> Self {
        self.request_schema = Some(schema);
        self.undescribed
            .retain(|input| input.kind != InputKind::RequestBody);
        self
    }

    /// Describes the query parameters by hand: one for each property of `schema`, required
    /// when its `required` list names it - the way a `Query<T>` extractor describes the
    /// fields of `T`.
    ///
    /// This is how a query whose fields cannot be inferred is described - see
    /// [`UndescribedInput`]. A parameter this operation already describes under the same
    /// name is replaced.
    pub fn with_query_schema(mut self, schema: OpenApiSchema) -> Self {
        self.undescribed
            .retain(|input| input.kind != InputKind::QueryParameters);
        self.with_query_parameters(schema)
    }

    /// Sets the response schema for this operation.
    pub fn with_response_schema(
        mut self,
        status: impl IntoStatusCode,
        schema: OpenApiSchema,
    ) -> Self {
        let status = status.into_status_code();
        self.responses.insert(
            status,
            ResponseBody::Content {
                schema: Box::new(schema),
                example: None,
                content_type: APPLICATION_JSON.to_string(),
            },
        );
        self
    }

    /// Generates path parameters schema.
    pub fn consumes_named_path<T: DeserializeOwned>(self) -> Self {
        self.with_named_path_parameters_from_deserialize::<T>()
    }

    /// Generates query parameters schema.
    pub fn consumes_query<T: DeserializeOwned>(self) -> Self {
        self.with_query_parameters_from_deserialize::<T>()
    }

    /// Generates JSON request schema and example.
    pub fn consumes_json<T: DeserializeOwned>(self) -> Self {
        self.with_request_type_from_deserialize::<T>(APPLICATION_JSON.as_ref())
    }

    /// Generates form request schema and example.
    pub fn consumes_form<T: DeserializeOwned>(self) -> Self {
        self.with_request_type_from_deserialize::<T>(APPLICATION_WWW_FORM_URLENCODED.as_ref())
    }

    /// Generates multipart request schema.
    pub fn consumes_multipart(self) -> Self {
        self.with_multipart_request()
    }

    /// Generates stream request schema.
    pub fn consumes_stream(self) -> Self {
        self.with_stream_request()
    }

    /// Generates text/plain response schema.
    pub fn produces_text(mut self, status: impl IntoStatusCode) -> Self {
        let status = status.into_status_code();
        self.responses.insert(
            status,
            ResponseBody::Content {
                schema: Box::new(OpenApiSchema::string()),
                example: None,
                content_type: TEXT_PLAIN_UTF_8.to_string(),
            },
        );
        self
    }

    /// Generates a response without a schema.
    pub fn produces_no_schema(mut self, status: impl IntoStatusCode) -> Self {
        let status = status.into_status_code();
        self.responses.insert(status, ResponseBody::NoContent);
        self
    }

    /// Generates JSON response schema and example from `T::default()`.
    pub fn produces_json<T: Serialize + Default>(self, status: impl IntoStatusCode) -> Self {
        self.produces_json_example(status, T::default())
    }

    /// Generates empty JSON response schema.
    pub fn produces_empty_json(mut self, status: impl IntoStatusCode) -> Self {
        let status = status.into_status_code();
        self.responses.insert(
            status,
            ResponseBody::Content {
                schema: Box::new(OpenApiSchema::object()),
                example: None,
                content_type: APPLICATION_JSON.to_string(),
            },
        );
        self
    }

    /// Generates form response schema and example from `T::default()`.
    pub fn produces_form<T: Serialize + Default>(self, status: impl IntoStatusCode) -> Self {
        self.produces_form_example(status, T::default())
    }

    /// Generates empty form response schema.
    pub fn produces_empty_form(mut self, status: impl IntoStatusCode) -> Self {
        let status = status.into_status_code();
        self.responses.insert(
            status,
            ResponseBody::Content {
                schema: Box::new(OpenApiSchema::object()),
                example: None,
                content_type: APPLICATION_WWW_FORM_URLENCODED.to_string(),
            },
        );
        self
    }

    /// Generates default `multipart/form-data` response schema.
    pub fn produces_multipart(mut self, status: impl IntoStatusCode) -> Self {
        let status = status.into_status_code();
        self.responses.insert(
            status,
            ResponseBody::Content {
                schema: Box::new(OpenApiSchema::multipart()),
                example: None,
                content_type: MULTIPART_FORM_DATA.to_string(),
            },
        );
        self
    }

    /// Generates stream response schema.
    pub fn produces_stream(mut self, status: impl IntoStatusCode) -> Self {
        let status = status.into_status_code();
        self.responses.insert(
            status,
            ResponseBody::Content {
                schema: Box::new(OpenApiSchema::binary()),
                example: None,
                content_type: APPLICATION_OCTET_STREAM.to_string(),
            },
        );
        self
    }

    /// Generates SSE stream response schema.
    pub fn produces_sse(mut self, status: impl IntoStatusCode) -> Self {
        let status = status.into_status_code();
        self.responses.insert(
            status,
            ResponseBody::Content {
                schema: Box::new(OpenApiSchema::string().with_title("SSE stream")),
                example: None,
                content_type: TEXT_EVENT_STREAM.to_string(),
            },
        );
        self
    }

    /// Generates JSON response schema and example.
    pub fn produces_json_example<T: Serialize>(
        mut self,
        status: impl IntoStatusCode,
        example: T,
    ) -> Self {
        let status = status.into_status_code();
        let example = serde_json::to_value(example).unwrap_or_else(|_| json!({}));
        self.responses.insert(
            status,
            ResponseBody::Content {
                schema: Box::new(OpenApiSchema::from_example(&example)),
                example: Some(example),
                content_type: APPLICATION_JSON.to_string(),
            },
        );
        self
    }

    /// Generates form response schema and example.
    pub fn produces_form_example<T: Serialize>(
        mut self,
        status: impl IntoStatusCode,
        example: T,
    ) -> Self {
        let status = status.into_status_code();
        let example = serde_json::to_value(example).unwrap_or_else(|_| json!({}));

        let encoded = match &example {
            Value::Object(map) => serde_urlencoded::to_string(map).unwrap_or_default(),
            _ => String::new(),
        };

        self.responses.insert(
            status,
            ResponseBody::Content {
                schema: Box::new(OpenApiSchema::string()),
                example: Some(Value::String(encoded)),
                content_type: APPLICATION_WWW_FORM_URLENCODED.to_string(),
            },
        );
        self
    }

    /// Generates an `application/problem+json` response schema for the given status code (RFC 7807).
    ///
    /// The example is derived from the status code using its canonical reason phrase.
    #[cfg(feature = "problem-details")]
    pub fn produces_problem(mut self, status: impl IntoStatusCode) -> Self {
        let status = status.into_status_code();
        let title = http::StatusCode::from_u16(status)
            .ok()
            .and_then(|s| s.canonical_reason())
            .unwrap_or("Error");
        let example = json!({
            "type": "https://tools.ietf.org/html/rfc9110",
            "title": title,
            "status": status
        });
        self.responses.insert(
            status,
            ResponseBody::Content {
                schema: Box::new(OpenApiSchema::from_example(&example)),
                example: Some(example),
                content_type: "application/problem+json".to_string(),
            },
        );
        self
    }

    /// Generates an `application/problem+json` response schema and example (RFC 7807).
    ///
    /// The schema is inferred from the provided example value.
    #[cfg(feature = "problem-details")]
    pub fn produces_problem_example<T: Serialize>(
        mut self,
        status: impl IntoStatusCode,
        example: T,
    ) -> Self {
        let status = status.into_status_code();
        let example = serde_json::to_value(example).unwrap_or_else(|_| json!({}));
        self.responses.insert(
            status,
            ResponseBody::Content {
                schema: Box::new(OpenApiSchema::from_example(&example)),
                example: Some(example),
                content_type: "application/problem+json".to_string(),
            },
        );
        self
    }

    /// Generates default Multipart request schema
    fn with_multipart_request(mut self) -> Self {
        self.request_schema
            .get_or_insert_with(OpenApiSchema::multipart);
        self.request_content_type = Some(MULTIPART_FORM_DATA.to_string());
        self
    }

    /// Generates default stream request schema
    fn with_stream_request(mut self) -> Self {
        self.request_schema
            .get_or_insert_with(OpenApiSchema::binary);
        self.request_content_type = Some(APPLICATION_OCTET_STREAM.to_string());
        self
    }

    fn with_query_parameter(mut self, name: String, schema: OpenApiSchema, required: bool) -> Self {
        self.extra_parameters.push(OpenApiParameter {
            name,
            location: "query".to_string(),
            required,
            schema,
        });
        self
    }

    fn with_path_parameter(mut self, name: String, schema: OpenApiSchema) -> Self {
        self.extra_parameters.push(OpenApiParameter {
            name,
            location: "path".to_string(),
            required: true,
            schema,
        });
        self
    }

    /// Generates request schema and example from `T`.
    fn with_request_type_from_deserialize<T: DeserializeOwned>(
        mut self,
        content_type: &str,
    ) -> Self {
        match probe::<T>() {
            Probed::Shape(schema, example) => {
                self.request_schema = Some(schema.with_title(type_display_name::<T>()));
                self.request_example = Some(example);
            }
            Probed::ReadAsMap(found) => {
                // What is known is that a body is sent: an object, when the struct read as a
                // map is the body itself, and anything at all when it sits inside it - a
                // `Vec` of them is an array. No example: one without the fields would be
                // an example of a request the server refuses
                let schema = if found.at_root {
                    OpenApiSchema::object()
                } else {
                    OpenApiSchema::empty()
                };
                self.request_schema = Some(schema.with_title(type_display_name::<T>()));
                self.undescribed
                    .push(UndescribedInput::new::<T>(InputKind::RequestBody, found));
            }
            Probed::Nothing => {}
        }
        self.request_content_type = Some(content_type.to_string());
        self
    }

    /// Publishes the constraints of the extractor that declared them, on the one thing in
    /// this operation that extractor describes.
    ///
    /// The target matters: handler arguments are described one after another, so a body and
    /// a query struct sharing a field name would otherwise hand each other their bounds.
    /// A field the target does not describe is ignored.
    pub fn with_constraints(
        mut self,
        target: ConstraintTarget,
        constraints: &[FieldConstraint],
    ) -> Self {
        match target {
            ConstraintTarget::RequestBody => {
                if let Some(schema) = self.request_schema.as_mut() {
                    schema.apply_field_constraints(constraints);
                }
            }
            ConstraintTarget::QueryParameter { described_before } => {
                self.apply_to_parameters("query", described_before, constraints);
            }
            ConstraintTarget::PathParameter { described_before } => {
                self.apply_to_parameters("path", described_before, constraints);
            }
        }
        self
    }

    /// Applies the constraints to the parameters one extractor added, by name.
    ///
    /// Parameters are appended as each handler argument is described, so the ones belonging
    /// to the extractor that declared these constraints are exactly those past
    /// `described_before`. Searching further back would hand an earlier extractor a bound
    /// that is not its own - and an extractor whose schema could not be inferred adds no
    /// parameters at all, so there would be nothing else for the search to find.
    fn apply_to_parameters(
        &mut self,
        location: &str,
        described_before: usize,
        constraints: &[FieldConstraint],
    ) {
        let Some(described) = self.extra_parameters.get_mut(described_before..) else {
            return;
        };

        for parameter in described
            .iter_mut()
            .filter(|parameter| parameter.location == location)
        {
            // A field carries more than one constraint - a minimum and a maximum are two
            for constraint in constraints
                .iter()
                .filter(|constraint| constraint.field == parameter.name)
            {
                parameter.schema.apply_constraint(&constraint.constraint);
            }
        }
    }

    fn with_query_parameters_from_deserialize<T: DeserializeOwned>(mut self) -> Self {
        match probe::<T>() {
            Probed::Shape(schema, _) => self.with_query_parameters(schema),
            Probed::ReadAsMap(found) => {
                self.undescribed.push(UndescribedInput::new::<T>(
                    InputKind::QueryParameters,
                    found,
                ));
                self
            }
            Probed::Nothing => self,
        }
    }

    /// Adds a query parameter for each property of `schema`
    fn with_query_parameters(mut self, schema: OpenApiSchema) -> Self {
        if let Some(properties) = schema.properties {
            let required = schema.required.unwrap_or_default();

            for (name, property_schema) in properties {
                let is_required = required.iter().any(|f| f == &name);
                self = self.with_query_parameter(name, property_schema, is_required);
            }
        }
        self
    }

    /// A struct read as a map is not reported here: the route template names every path
    /// parameter whatever the extractor describes, and types them when it spells a type -
    /// `{id:integer}` - which is all a `Path<T>` gets as well
    fn with_named_path_parameters_from_deserialize<T: DeserializeOwned>(mut self) -> Self {
        if let Probed::Shape(schema, _) = probe::<T>()
            && let Some(properties) = schema.properties
        {
            for (name, property_schema) in properties {
                self = self.with_path_parameter(name, property_schema);
            }
        }
        self
    }

    /// Merges the configuration of an enclosing scope - a route group - into this one.
    ///
    /// Whatever the route describes for itself wins, exactly as in [`merge`](Self::merge);
    /// the difference is the order of the tags, which read outermost first no matter when
    /// the group's configuration was registered.
    pub fn merge_outer(mut self, outer: &Self) -> Self {
        let own_tags = std::mem::take(&mut self.tags);
        let own_parameters = std::mem::take(&mut self.extra_parameters);

        let mut merged = self.merge(outer);

        merged.tags.extend(own_tags);
        // Same-name parameters replace one another in the order they reach the
        // operation, so the route's have to come last to win
        merged.extra_parameters.extend(own_parameters);
        merged
    }

    /// Merges configurations.
    pub fn merge(mut self, other: &Self) -> Self {
        if self.tags.is_empty() {
            self.tags = other.tags.clone();
        } else {
            self.tags.extend(other.tags.clone());
        }
        if self.summary.is_none() {
            self.summary = other.summary.clone();
        }
        if self.description.is_none() {
            self.description = other.description.clone();
        }
        if self.operation_id.is_none() {
            self.operation_id = other.operation_id.clone();
        }

        // An input taken on from `other` comes with what `other` could not describe of it:
        // its query parameters are added to these, and its body is taken where there is none -
        // example included, since an example is one of the body it was made for. A body kept
        // here keeps its own example, or its lack of one
        let inherits_body = self.request_schema.is_none();
        self.undescribed.extend(
            other
                .undescribed
                .iter()
                .filter(|input| match input.kind {
                    InputKind::RequestBody => inherits_body,
                    InputKind::QueryParameters => true,
                })
                .cloned(),
        );

        if inherits_body {
            self.request_schema = other.request_schema.clone();
            if self.request_example.is_none() {
                self.request_example = other.request_example.clone();
            }
        }

        if self.request_content_type.is_none() {
            self.request_content_type = other.request_content_type.clone();
        }

        for (status, body) in &other.responses {
            self.responses
                .entry(*status)
                .or_insert_with(|| body.clone());
        }

        if !other.extra_parameters.is_empty() {
            self.extra_parameters.extend(other.extra_parameters.clone());
        }

        match (&mut self.docs, &other.docs) {
            (None, Some(d)) => self.docs = Some(d.clone()),
            (Some(dst), Some(src)) => {
                for s in src {
                    if !dst.iter().any(|x| x == s) {
                        dst.push(s.clone());
                    }
                }
            }
            _ => {}
        }
        self
    }

    pub(super) fn apply_to_operation(
        &self,
        operation: &mut OpenApiOperation,
        schemas: &mut BTreeMap<String, OpenApiSchema>,
    ) {
        if let Some(summary) = &self.summary {
            operation.summary = Some(summary.clone());
        }
        if let Some(description) = &self.description {
            operation.description = Some(description.clone());
        }
        if let Some(operation_id) = &self.operation_id {
            operation.operation_id = Some(operation_id.clone());
        }

        if !self.tags.is_empty() {
            operation.tags = Some(self.tags.clone());
        }

        if self.request_schema.is_some() || self.request_example.is_some() {
            let mut schema = self
                .request_schema
                .clone()
                .unwrap_or_else(OpenApiSchema::object);
            let example = self.request_example.clone();
            let content_type = self
                .request_content_type
                .as_deref()
                .unwrap_or(APPLICATION_JSON.as_ref());

            schema = intern_schema_if_object_named(schema, schemas);
            operation.set_request_body(schema, example, content_type);
        }

        if !self.responses.is_empty() {
            operation.clear_all_responses();
            for (status, body) in &self.responses {
                match body {
                    ResponseBody::NoContent => {
                        operation.clear_response_body(*status);
                    }
                    ResponseBody::Content {
                        schema,
                        example,
                        content_type,
                    } => {
                        let schema = intern_schema_if_object_named((**schema).clone(), schemas);
                        operation.set_response_body(*status, schema, example.clone(), content_type);
                    }
                }
            }
        }

        if !self.extra_parameters.is_empty() {
            let params = operation.parameters.get_or_insert_with(Vec::new);

            for p in &self.extra_parameters {
                if let Some(existing) = params
                    .iter_mut()
                    .find(|x| x.name == p.name && x.location == p.location)
                {
                    *existing = p.clone();
                } else {
                    params.push(p.clone());
                }
            }
        }
    }
}

fn intern_schema_if_object_named(
    mut schema: OpenApiSchema,
    schemas: &mut BTreeMap<String, OpenApiSchema>,
) -> OpenApiSchema {
    if schema.schema_ref.is_some() {
        return schema;
    }

    let base = match schema.title.clone() {
        Some(t) if !t.is_empty() => t,
        _ => return schema,
    };

    if schema.properties.is_none() {
        return schema;
    }

    let mut name = base.clone();
    if schemas.contains_key(&name) {
        let mut i = 2;
        while schemas.contains_key(&format!("{base}_{i}")) {
            i += 1;
        }
        name = format!("{base}_{i}");
    }

    schema.title = None;

    schemas.entry(name.clone()).or_insert(schema);

    OpenApiSchema::reference(&name)
}

fn probe<T: DeserializeOwned>() -> Probed {
    let mut probe = Probe::new();
    let _ = T::deserialize(&mut probe);
    probe.finish()
}

fn type_display_name<T>() -> String {
    std::any::type_name::<T>()
        .rsplit("::")
        .next()
        .unwrap_or("Model")
        .to_string()
}

#[cfg(test)]
#[allow(unused)]
mod tests {
    use super::{ConstraintTarget, InputKind, IntoStatusCode, OpenApiRouteConfig, ResponseBody};
    use crate::{
        op::OpenApiOperation,
        schema::{FieldConstraint, OpenApiSchema, SchemaConstraint},
    };
    use serde::{Deserialize, Serialize};
    use serde_json::json;
    use std::collections::BTreeMap;

    #[derive(Deserialize)]
    struct Payload {
        name: String,
        age: u64,
    }

    #[derive(Serialize, Default)]
    struct ResponsePayload {
        message: String,
    }

    #[derive(Deserialize)]
    struct OptionalQuery {
        required_name: String,
        optional_age: Option<()>,
    }

    #[derive(Deserialize)]
    #[allow(dead_code)]
    struct Page {
        page: u32,
    }

    #[test]
    fn with_constraints_touches_only_the_parameter_its_extractor_added() {
        // Two extractors describing a query parameter of the same name: each is described
        // in turn, appending its own parameter, and neither may reach into the other's
        let cfg = OpenApiRouteConfig::default();

        let described_before = cfg.described_parameters();
        let cfg = cfg.consumes_query::<Page>().with_constraints(
            ConstraintTarget::QueryParameter { described_before },
            &[FieldConstraint::new(
                "page",
                SchemaConstraint::Minimum(1.into()),
            )],
        );

        let described_before = cfg.described_parameters();
        let cfg = cfg.consumes_query::<Page>().with_constraints(
            ConstraintTarget::QueryParameter { described_before },
            &[FieldConstraint::new(
                "page",
                SchemaConstraint::Minimum(100.into()),
            )],
        );

        let bounds = cfg
            .extra_parameters
            .iter()
            .map(|parameter| parameter.schema.minimum.clone())
            .collect::<Vec<_>>();

        assert_eq!(bounds, vec![Some(1.into()), Some(100.into())]);
    }

    #[test]
    fn with_constraints_of_an_extractor_that_described_nothing_reach_nobody() {
        // A struct whose schema cannot be inferred - an enum field is enough - adds no
        // parameters, so its bounds have no target and must not fall back to someone else's
        let cfg = OpenApiRouteConfig::default();
        let described_before = cfg.described_parameters();
        let cfg = cfg.consumes_query::<Page>().with_constraints(
            ConstraintTarget::QueryParameter { described_before },
            &[FieldConstraint::new(
                "page",
                SchemaConstraint::Minimum(1.into()),
            )],
        );

        let described_before = cfg.described_parameters();
        let cfg = cfg.with_constraints(
            ConstraintTarget::QueryParameter { described_before },
            &[FieldConstraint::new(
                "page",
                SchemaConstraint::Minimum(100.into()),
            )],
        );

        assert_eq!(cfg.extra_parameters.len(), 1);
        assert_eq!(cfg.extra_parameters[0].schema.minimum, Some(1.into()));
    }

    #[test]
    fn with_constraints_intersects_a_bound_declared_twice() {
        // Both rules run at runtime, so the published bound is the one that survives both
        let cfg = OpenApiRouteConfig::default()
            .consumes_query::<Page>()
            .with_constraints(
                ConstraintTarget::QueryParameter {
                    described_before: 0,
                },
                &[
                    FieldConstraint::new("page", SchemaConstraint::Minimum(10.into())),
                    FieldConstraint::new("page", SchemaConstraint::Minimum(1.into())),
                    FieldConstraint::new("page", SchemaConstraint::Maximum(50.into())),
                    FieldConstraint::new("page", SchemaConstraint::Maximum(500.into())),
                ],
            );

        let schema = &cfg.extra_parameters[0].schema;

        assert_eq!(schema.minimum, Some(10.into()));
        assert_eq!(schema.maximum, Some(50.into()));
    }

    #[test]
    fn consumes_query_keeps_parameters_of_a_typed_optional_field() {
        #[derive(serde::Deserialize)]
        #[allow(dead_code)]
        struct OptionalString {
            per_page: u32,
            sort: Option<String>,
        }

        let cfg = OpenApiRouteConfig::default().consumes_query::<OptionalString>();
        let names = cfg
            .extra_parameters
            .iter()
            .map(|p| p.name.as_str())
            .collect::<Vec<_>>();

        // A typed `Option` used to make the whole probe fail, dropping every parameter
        assert_eq!(names, vec!["per_page", "sort"]);
        assert!(!cfg.extra_parameters[1].required);
    }

    #[derive(Deserialize)]
    #[allow(dead_code)]
    struct Inner {
        name: String,
    }

    #[derive(Deserialize)]
    #[allow(dead_code)]
    struct Flat {
        #[serde(flatten)]
        inner: Inner,
        page: u32,
    }

    fn body_schema(cfg: &OpenApiRouteConfig) -> serde_json::Value {
        let mut operation = OpenApiOperation::default();
        let mut schemas = BTreeMap::new();
        cfg.apply_to_operation(&mut operation, &mut schemas);

        let operation = serde_json::to_value(&operation).expect("operation serializes");
        operation["requestBody"]["content"]["application/json"]["schema"].clone()
    }

    #[test]
    fn consumes_json_reports_a_body_read_as_a_map() {
        let cfg = OpenApiRouteConfig::default().consumes_json::<Flat>();

        let [input] = cfg.undescribed_inputs() else {
            panic!("one undescribed input: {:?}", cfg.undescribed_inputs());
        };
        assert_eq!(input.kind(), InputKind::RequestBody);
        assert_eq!(input.type_name(), std::any::type_name::<Flat>());
        assert_eq!(input.read_as_map(), None);

        // An object is all that is known, and an example without the fields would be one
        // the server refuses
        assert_eq!(
            body_schema(&cfg),
            json!({ "type": "object", "title": "Flat" })
        );
        assert!(cfg.request_example.is_none());
    }

    #[test]
    fn consumes_json_reports_a_struct_read_as_a_map_inside_the_body() {
        let cfg = OpenApiRouteConfig::default().consumes_json::<Vec<Flat>>();

        let [input] = cfg.undescribed_inputs() else {
            panic!("one undescribed input: {:?}", cfg.undescribed_inputs());
        };
        assert_eq!(input.kind(), InputKind::RequestBody);
        assert_eq!(input.read_as_map(), Some("struct Flat"));

        // The body is an array here, so publishing the struct's object would be wrong
        assert_eq!(body_schema(&cfg)["type"], serde_json::Value::Null);
    }

    #[test]
    fn consumes_form_reports_a_body_read_as_a_map() {
        let cfg = OpenApiRouteConfig::default().consumes_form::<Flat>();

        let [input] = cfg.undescribed_inputs() else {
            panic!("one undescribed input: {:?}", cfg.undescribed_inputs());
        };
        assert_eq!(input.kind(), InputKind::RequestBody);
        assert_eq!(
            cfg.request_content_type.as_deref(),
            Some("application/x-www-form-urlencoded")
        );
    }

    #[test]
    fn consumes_json_does_not_report_a_map() {
        let cfg =
            OpenApiRouteConfig::default().consumes_json::<std::collections::HashMap<String, u32>>();

        assert!(cfg.undescribed_inputs().is_empty());
        assert!(cfg.request_schema.is_some());
    }

    #[test]
    fn consumes_query_reports_a_query_read_as_a_map() {
        let cfg = OpenApiRouteConfig::default().consumes_query::<Flat>();

        let [input] = cfg.undescribed_inputs() else {
            panic!("one undescribed input: {:?}", cfg.undescribed_inputs());
        };
        assert_eq!(input.kind(), InputKind::QueryParameters);
        assert!(cfg.extra_parameters.is_empty());
    }

    #[test]
    fn consumes_named_path_leaves_a_struct_read_as_a_map_to_the_template() {
        let cfg = OpenApiRouteConfig::default().consumes_named_path::<Flat>();

        assert!(cfg.undescribed_inputs().is_empty());
        assert!(cfg.extra_parameters.is_empty());
    }

    #[test]
    fn with_request_schema_describes_an_undescribed_body() {
        let cfg = OpenApiRouteConfig::default()
            .consumes_query::<Flat>()
            .consumes_json::<Flat>()
            .with_request_schema(
                OpenApiSchema::object()
                    .with_property("name", OpenApiSchema::string())
                    .with_property("page", OpenApiSchema::integer())
                    .with_required(["name", "page"]),
            );

        // The query is still undescribed; only the body was described by hand
        let kinds = cfg
            .undescribed_inputs()
            .iter()
            .map(|input| input.kind())
            .collect::<Vec<_>>();
        assert_eq!(kinds, vec![InputKind::QueryParameters]);
        assert_eq!(
            body_schema(&cfg)["properties"]["page"]["type"],
            json!("integer")
        );
    }

    #[test]
    fn with_query_schema_describes_an_undescribed_query() {
        let cfg = OpenApiRouteConfig::default()
            .consumes_json::<Flat>()
            .consumes_query::<Flat>()
            .with_query_schema(
                OpenApiSchema::object()
                    .with_property("name", OpenApiSchema::string())
                    .with_property("page", OpenApiSchema::integer())
                    .with_required(["page"]),
            );

        let kinds = cfg
            .undescribed_inputs()
            .iter()
            .map(|input| input.kind())
            .collect::<Vec<_>>();
        assert_eq!(kinds, vec![InputKind::RequestBody]);

        let parameters = cfg
            .extra_parameters
            .iter()
            .map(|p| (p.name.as_str(), p.location.as_str(), p.required))
            .collect::<Vec<_>>();
        assert_eq!(
            parameters,
            vec![("name", "query", false), ("page", "query", true)]
        );
    }

    #[test]
    fn with_query_schema_replaces_a_parameter_of_the_same_name() {
        let cfg = OpenApiRouteConfig::default()
            .consumes_query::<Page>()
            .with_query_schema(
                OpenApiSchema::object().with_property("page", OpenApiSchema::string()),
            );

        let mut operation = OpenApiOperation::default();
        cfg.apply_to_operation(&mut operation, &mut BTreeMap::new());

        let parameters = operation.parameters.expect("parameters");
        assert_eq!(parameters.len(), 1);
        assert_eq!(parameters[0].schema.schema_type.as_deref(), Some("string"));
        assert!(!parameters[0].required);
    }

    fn kinds(cfg: &OpenApiRouteConfig) -> Vec<InputKind> {
        cfg.undescribed_inputs()
            .iter()
            .map(|input| input.kind())
            .collect()
    }

    /// A group's inputs reach a route with what could not be described of them: its query
    /// parameters always, since they are added to the route's, and its body only where the
    /// route has none of its own to keep
    #[test]
    fn merge_outer_inherits_the_undescribed_inputs_it_inherits() {
        let group = OpenApiRouteConfig::default()
            .consumes_query::<Flat>()
            .consumes_json::<Flat>();

        let bare = OpenApiRouteConfig::default().merge_outer(&group);
        assert_eq!(
            kinds(&bare),
            [InputKind::QueryParameters, InputKind::RequestBody]
        );

        let own_body = OpenApiRouteConfig::default()
            .consumes_json::<Payload>()
            .merge_outer(&group);
        assert_eq!(kinds(&own_body), [InputKind::QueryParameters]);
        assert!(
            own_body
                .request_schema
                .as_ref()
                .and_then(|schema| schema.properties.as_ref())
                .is_some_and(|properties| properties.contains_key("name")),
            "the route keeps its own body"
        );

        // A route's own undescribed body is the one kept, and reported once
        let own_flat_body = OpenApiRouteConfig::default()
            .consumes_json::<Vec<Flat>>()
            .merge_outer(&group);
        let bodies = own_flat_body
            .undescribed_inputs()
            .iter()
            .filter(|input| input.kind() == InputKind::RequestBody)
            .map(|input| input.type_name())
            .collect::<Vec<_>>();
        assert_eq!(bodies, [std::any::type_name::<Vec<Flat>>()]);
    }

    /// An example is an example of the body it was made for, so it goes with that body: a
    /// route with a body of its own keeps its own example, or its lack of one
    #[test]
    fn merge_outer_takes_an_example_only_with_the_body_it_belongs_to() {
        let group = OpenApiRouteConfig::default().consumes_json::<Payload>();
        assert!(group.request_example.is_some());

        let flat = OpenApiRouteConfig::default()
            .consumes_json::<Flat>()
            .merge_outer(&group);
        assert!(flat.request_example.is_none());

        let by_hand = OpenApiRouteConfig::default()
            .with_request_schema(OpenApiSchema::string())
            .merge_outer(&group);
        assert!(by_hand.request_example.is_none());

        let bare = OpenApiRouteConfig::default().merge_outer(&group);
        assert_eq!(bare.request_example, group.request_example);
    }

    #[test]
    fn merge_outer_inherits_no_input_a_group_describes_by_hand() {
        let group = OpenApiRouteConfig::default()
            .consumes_query::<Flat>()
            .with_query_schema(
                OpenApiSchema::object().with_property("name", OpenApiSchema::string()),
            );

        let merged = OpenApiRouteConfig::default().merge_outer(&group);

        assert!(merged.undescribed_inputs().is_empty());
    }

    #[test]
    fn consumes_query_marks_non_optional_fields_as_required() {
        let cfg = OpenApiRouteConfig::default().consumes_query::<OptionalQuery>();

        let required_name = cfg
            .extra_parameters
            .iter()
            .find(|p| p.name == "required_name")
            .expect("required_name param");
        let optional_age = cfg
            .extra_parameters
            .iter()
            .find(|p| p.name == "optional_age")
            .expect("optional_age param");

        assert!(required_name.required);
        assert!(!optional_age.required);
    }

    #[test]
    fn infer_request_schema_from_deserialize_type() {
        let cfg = OpenApiRouteConfig::default()
            .with_request_type_from_deserialize::<Payload>("application/json");

        let schema = cfg
            .request_schema
            .expect("request schema should be inferred");
        let props = schema.properties.expect("object properties should exist");

        assert!(props.contains_key("name"));
        assert!(props.contains_key("age"));
        assert_eq!(
            cfg.request_content_type.as_deref(),
            Some("application/json")
        );
    }

    #[test]
    fn infer_query_parameters_from_deserialize_type() {
        let cfg = OpenApiRouteConfig::default().with_query_parameters_from_deserialize::<Payload>();

        assert_eq!(cfg.extra_parameters.len(), 2);
        assert!(cfg.extra_parameters.iter().any(|p| p.name == "name"));
        assert!(cfg.extra_parameters.iter().any(|p| p.name == "age"));
        assert!(cfg.extra_parameters.iter().all(|p| p.location == "query"));
    }

    #[test]
    fn merge_outer_keeps_the_route_ahead_of_the_scope_it_is_in() {
        let group = OpenApiRouteConfig::default()
            .with_tag("group")
            .with_summary("group summary")
            .with_query_parameter("id".into(), OpenApiSchema::string(), false);
        let route = OpenApiRouteConfig::default()
            .with_tag("route")
            .with_query_parameter("id".into(), OpenApiSchema::integer(), true);

        let merged = route.merge_outer(&group);

        // The scope reads outermost first, and the route's own values win: a parameter
        // replaces a same-name one applied before it, so the route's has to come last
        assert_eq!(merged.tags, vec!["group".to_string(), "route".to_string()]);
        assert_eq!(merged.summary.as_deref(), Some("group summary"));
        assert_eq!(merged.extra_parameters.len(), 2);
        assert!(merged.extra_parameters[1].required);
    }

    #[test]
    fn merge_combines_docs_and_preserves_existing_values() {
        let base = OpenApiRouteConfig::default()
            .with_tag("base")
            .with_summary("base summary")
            .with_doc("v1");
        let other = OpenApiRouteConfig::default()
            .with_tag("extra")
            .with_summary("other summary")
            .with_doc("v1")
            .with_doc("admin");

        let merged = base.merge(&other);

        assert_eq!(merged.summary.as_deref(), Some("base summary"));
        assert_eq!(merged.tags.as_slice(), ["base", "extra"]);
        assert_eq!(merged.docs.expect("docs"), vec!["v1", "admin"]);
    }

    #[test]
    fn apply_to_operation_adds_content_and_interns_named_schema() {
        let cfg = OpenApiRouteConfig::default()
            .with_request_schema(
                OpenApiSchema::object()
                    .with_title("CreateUser")
                    .with_property("name", OpenApiSchema::string()),
            )
            .with_response_schema(
                200u16,
                OpenApiSchema::object()
                    .with_title("User")
                    .with_property("id", OpenApiSchema::integer()),
            )
            .produces_json_example(
                200u16,
                ResponsePayload {
                    message: "ok".to_string(),
                },
            )
            .with_summary("create user")
            .with_operation_id("createUser");

        let mut op = OpenApiOperation::default();
        let mut schemas = BTreeMap::new();

        cfg.apply_to_operation(&mut op, &mut schemas);

        let op_json = serde_json::to_value(op).expect("serialize operation");
        assert_eq!(op_json["summary"], "create user");
        assert_eq!(op_json["operationId"], "createUser");
        assert!(
            op_json["requestBody"]["content"]
                .get("application/json")
                .is_some()
        );
        assert_eq!(
            op_json["responses"]["200"]["content"]["application/json"]["example"],
            json!({"message":"ok"})
        );

        assert!(schemas.contains_key("CreateUser"));
    }

    #[test]
    fn produces_no_schema_clears_content() {
        let cfg = OpenApiRouteConfig::default()
            .produces_json::<ResponsePayload>(200)
            .produces_no_schema(200);

        let mut op = OpenApiOperation::default();
        cfg.apply_to_operation(&mut op, &mut BTreeMap::new());

        let op_json = serde_json::to_value(op).expect("serialize operation");
        assert!(op_json["responses"]["200"].get("content").is_none());
    }

    #[test]
    fn with_tags_extends_existing_tags() {
        let cfg = OpenApiRouteConfig::default()
            .with_tag("base")
            .with_tags(["one", "two"]);

        assert_eq!(cfg.tags, vec!["base", "one", "two"]);
    }

    #[test]
    fn with_docs_initializes_and_extends_docs() {
        let cfg = OpenApiRouteConfig::default()
            .with_docs(["v1", "admin"])
            .with_doc("internal");

        assert_eq!(cfg.docs.expect("docs"), vec!["v1", "admin", "internal"]);
    }

    #[test]
    fn with_description_sets_operation_description() {
        let cfg = OpenApiRouteConfig::default().with_description("desc");
        assert_eq!(cfg.description.as_deref(), Some("desc"));
    }

    #[test]
    fn consumes_methods_set_request_content_type() {
        let query_cfg = OpenApiRouteConfig::default().consumes_query::<Payload>();
        assert_eq!(query_cfg.extra_parameters.len(), 2);

        let json_cfg = OpenApiRouteConfig::default().consumes_json::<Payload>();
        assert_eq!(
            json_cfg.request_content_type.as_deref(),
            Some("application/json")
        );
        assert!(json_cfg.request_schema.is_some());

        let form_cfg = OpenApiRouteConfig::default().consumes_form::<Payload>();
        assert_eq!(
            form_cfg.request_content_type.as_deref(),
            Some("application/x-www-form-urlencoded")
        );
        assert!(form_cfg.request_schema.is_some());

        let multipart_cfg = OpenApiRouteConfig::default().consumes_multipart();
        assert_eq!(
            multipart_cfg.request_content_type.as_deref(),
            Some("multipart/form-data")
        );

        let stream_cfg = OpenApiRouteConfig::default().consumes_stream();
        assert_eq!(
            stream_cfg.request_content_type.as_deref(),
            Some("application/octet-stream")
        );
        assert_eq!(
            stream_cfg.request_schema.expect("schema").format.as_deref(),
            Some("binary")
        );
    }

    #[test]
    fn produces_helpers_set_expected_response_schema_and_content_type() {
        fn apply(cfg: OpenApiRouteConfig) -> serde_json::Value {
            let mut op = OpenApiOperation::default();
            cfg.apply_to_operation(&mut op, &mut BTreeMap::new());
            serde_json::to_value(op).expect("serialize")
        }

        let text_json = apply(OpenApiRouteConfig::default().produces_text(200));
        assert!(
            text_json["responses"]["200"]["content"]
                .get("text/plain; charset=utf-8")
                .is_some()
        );
        assert_eq!(
            text_json["responses"]["200"]["content"]["text/plain; charset=utf-8"]["schema"]["type"],
            "string"
        );

        let empty_json_json = apply(OpenApiRouteConfig::default().produces_empty_json(200));
        assert!(
            empty_json_json["responses"]["200"]["content"]
                .get("application/json")
                .is_some()
        );
        assert_eq!(
            empty_json_json["responses"]["200"]["content"]["application/json"]["schema"]["type"],
            "object"
        );

        let form_json = apply(OpenApiRouteConfig::default().produces_form::<ResponsePayload>(200));
        assert!(
            form_json["responses"]["200"]["content"]
                .get("application/x-www-form-urlencoded")
                .is_some()
        );
        assert_eq!(
            form_json["responses"]["200"]["content"]["application/x-www-form-urlencoded"]["schema"]
                ["type"],
            "string"
        );

        let empty_form_json = apply(OpenApiRouteConfig::default().produces_empty_form(200));
        assert!(
            empty_form_json["responses"]["200"]["content"]
                .get("application/x-www-form-urlencoded")
                .is_some()
        );
        assert_eq!(
            empty_form_json["responses"]["200"]["content"]["application/x-www-form-urlencoded"]["schema"]
                ["type"],
            "object"
        );

        let stream_json = apply(OpenApiRouteConfig::default().produces_stream(200));
        assert!(
            stream_json["responses"]["200"]["content"]
                .get("application/octet-stream")
                .is_some()
        );
        assert_eq!(
            stream_json["responses"]["200"]["content"]["application/octet-stream"]["schema"]["format"],
            "binary"
        );

        let sse_json = apply(OpenApiRouteConfig::default().produces_sse(200));
        assert!(
            sse_json["responses"]["200"]["content"]
                .get("text/event-stream")
                .is_some()
        );
        assert_eq!(
            sse_json["responses"]["200"]["content"]["text/event-stream"]["schema"]["title"],
            "SSE stream"
        );
    }

    #[test]
    fn produces_form_example_encodes_object_into_string_example() {
        #[derive(Serialize)]
        struct FormOut {
            first: String,
            second: i32,
        }

        let cfg = OpenApiRouteConfig::default().produces_form_example(
            200u16,
            FormOut {
                first: "hello".to_string(),
                second: 7,
            },
        );

        let mut op = OpenApiOperation::default();
        cfg.apply_to_operation(&mut op, &mut BTreeMap::new());
        let op_json = serde_json::to_value(op).expect("serialize");

        assert!(
            op_json["responses"]["200"]["content"]
                .get("application/x-www-form-urlencoded")
                .is_some()
        );
        assert_eq!(
            op_json["responses"]["200"]["content"]["application/x-www-form-urlencoded"]["schema"]["type"],
            "string"
        );
        assert_eq!(
            op_json["responses"]["200"]["content"]["application/x-www-form-urlencoded"]["example"],
            "first=hello&second=7"
        );
    }

    #[test]
    fn produces_multiple_status_codes() {
        #[derive(Serialize, Default)]
        struct UserDto {
            id: u64,
        }
        #[derive(Serialize, Default)]
        struct ErrorDto {
            message: String,
        }

        let cfg = OpenApiRouteConfig::default()
            .produces_json::<UserDto>(200)
            .produces_json::<ErrorDto>(404);

        let mut op = OpenApiOperation::default();
        cfg.apply_to_operation(&mut op, &mut BTreeMap::new());
        let op_json = serde_json::to_value(op).expect("serialize");

        // Both statuses should appear
        assert!(
            op_json["responses"]["200"]["content"]
                .get("application/json")
                .is_some()
        );
        assert!(
            op_json["responses"]["404"]["content"]
                .get("application/json")
                .is_some()
        );
        // Default 200 is replaced by explicit responses
        assert_eq!(
            op_json["responses"]
                .as_object()
                .expect("responses object")
                .len(),
            2
        );
    }

    #[test]
    fn explicit_responses_replace_default_200() {
        let cfg = OpenApiRouteConfig::default().produces_json::<ResponsePayload>(201);

        let mut op = OpenApiOperation::default();
        cfg.apply_to_operation(&mut op, &mut BTreeMap::new());
        let op_json = serde_json::to_value(op).expect("serialize");

        // The default "200" must be gone - only "201" remains
        assert!(op_json["responses"].get("200").is_none());
        assert!(
            op_json["responses"]["201"]["content"]
                .get("application/json")
                .is_some()
        );
        assert_eq!(op_json["responses"]["201"]["description"], "Created");
    }

    #[test]
    fn merge_does_not_override_existing_responses() {
        let base = OpenApiRouteConfig::default().produces_json::<ResponsePayload>(200);
        let other = OpenApiRouteConfig::default()
            .produces_text(200)
            .produces_json::<ResponsePayload>(404);

        let merged = base.merge(&other);

        let mut op = OpenApiOperation::default();
        merged.apply_to_operation(&mut op, &mut BTreeMap::new());
        let op_json = serde_json::to_value(op).expect("serialize");

        // 200 should keep JSON (from base), not be overridden by text (from other)
        assert!(
            op_json["responses"]["200"]["content"]
                .get("application/json")
                .is_some()
        );
        assert!(
            op_json["responses"]["200"]["content"]
                .get("text/plain; charset=utf-8")
                .is_none()
        );
        // 404 should come from other
        assert!(
            op_json["responses"]["404"]["content"]
                .get("application/json")
                .is_some()
        );
    }

    #[test]
    fn into_status_code_works_for_u16_and_http_status_code() {
        assert_eq!(200u16.into_status_code(), 200);
        assert_eq!(201.into_status_code(), 201);
        assert_eq!(202u32.into_status_code(), 202);
        assert_eq!(http::StatusCode::NOT_FOUND.into_status_code(), 404);
        assert_eq!(http::StatusCode::CREATED.into_status_code(), 201);
    }

    #[cfg(feature = "problem-details")]
    mod problem_tests {
        use super::*;

        #[test]
        fn produces_problem_generates_problem_json_schema_for_status() {
            let cfg = OpenApiRouteConfig::default().produces_problem(400u16);
            let mut op = OpenApiOperation::default();
            cfg.apply_to_operation(&mut op, &mut BTreeMap::new());
            let op_json = serde_json::to_value(op).expect("serialize");

            let content = &op_json["responses"]["400"]["content"]["application/problem+json"];
            assert!(
                content.is_object(),
                "application/problem+json content should exist"
            );
            assert_eq!(content["example"]["title"], "Bad Request");
            assert_eq!(content["example"]["status"], 400);
            assert_eq!(
                content["example"]["type"],
                "https://tools.ietf.org/html/rfc9110"
            );
            assert_eq!(op_json["responses"]["400"]["description"], "Bad Request");
            // Default "200" must be gone
            assert!(op_json["responses"].get("200").is_none());
        }

        #[test]
        fn produces_problem_example_uses_provided_value() {
            #[derive(Serialize)]
            struct CustomProblem {
                r#type: String,
                title: String,
                status: u16,
                detail: String,
            }

            let cfg = OpenApiRouteConfig::default().produces_problem_example(
                422u16,
                CustomProblem {
                    r#type: "https://tools.ietf.org/html/rfc9110".into(),
                    title: "Unprocessable Content".into(),
                    status: 422,
                    detail: "Validation failed".into(),
                },
            );

            let mut op = OpenApiOperation::default();
            cfg.apply_to_operation(&mut op, &mut BTreeMap::new());
            let op_json = serde_json::to_value(op).expect("serialize");

            let content = &op_json["responses"]["422"]["content"]["application/problem+json"];
            assert!(
                content.is_object(),
                "application/problem+json content should exist"
            );
            assert_eq!(content["example"]["detail"], "Validation failed");
            assert_eq!(content["example"]["status"], 422);
            assert_eq!(
                op_json["responses"]["422"]["description"],
                "Unprocessable Entity"
            );
        }

        #[test]
        fn produces_problem_composes_with_other_status_responses() {
            let cfg = OpenApiRouteConfig::default()
                .produces_json::<ResponsePayload>(200)
                .produces_problem(400)
                .produces_problem(500);

            let mut op = OpenApiOperation::default();
            cfg.apply_to_operation(&mut op, &mut BTreeMap::new());
            let op_json = serde_json::to_value(op).expect("serialize");

            assert!(
                op_json["responses"]["200"]["content"]
                    .get("application/json")
                    .is_some()
            );
            assert!(
                op_json["responses"]["400"]["content"]
                    .get("application/problem+json")
                    .is_some()
            );
            assert!(
                op_json["responses"]["500"]["content"]
                    .get("application/problem+json")
                    .is_some()
            );
            assert_eq!(op_json["responses"].as_object().unwrap().len(), 3);
        }
    }

    #[test]
    fn produces_multipart_sets_response_content_type() {
        let cfg = OpenApiRouteConfig::default().produces_multipart(200u16);
        let resp = cfg.responses.get(&200u16).expect("200 response defined");
        match resp {
            ResponseBody::Content { content_type, .. } => {
                assert_eq!(content_type, "multipart/form-data");
            }
            _ => panic!("expected Content variant"),
        }
    }
}