delopay 0.20.0

Official Rust SDK for the DeloPay payments API
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
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
//! The connector (merchant connector account) models.
//!
//! `Debug` on [`ConnectorResponse`] and [`ConnectorWebhookRegisterResponse`] is
//! hand-written: the API echoes back credential-shaped fields
//! (`connector_account_details`, `connector_webhook_details`, and the
//! connector-minted `webhook_secret`), and a derived `Debug` would put them in
//! a log line.

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Placeholder printed in place of a credential-bearing field.
const REDACTED: &str = "[redacted]";

/// A merchant connector account as returned by the API.
///
/// Only [`merchant_connector_id`](ConnectorResponse::merchant_connector_id) is
/// required: the delete endpoint answers with a trimmed object carrying just
/// the ids, so everything else is optional rather than a hard deserialization
/// failure.
///
/// Unmodeled fields are preserved in [`extra`](ConnectorResponse::extra).
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorResponse {
    /// Unique connector account ID, e.g. `"mca_…"`.
    pub merchant_connector_id: String,

    /// Connector category, e.g. `"payment_processor"`, `"payout_processor"`.
    #[serde(default)]
    pub connector_type: Option<String>,
    /// Snake-case connector identifier, e.g. `"stripe"`, `"adyen"`.
    #[serde(default)]
    pub connector_name: Option<String>,
    /// Shop (business profile) the connector belongs to.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Merchant account that owns the connector.
    #[serde(default)]
    pub merchant_id: Option<String>,
    /// Connector status, e.g. `"active"` or `"inactive"`.
    #[serde(default)]
    pub status: Option<String>,
    /// Human-readable label, unique within the merchant account.
    #[serde(default)]
    pub connector_label: Option<String>,
    /// Gateway credentials, masked by the API. **Treated as secret**: redacted
    /// by [`Debug`].
    #[serde(default)]
    pub connector_account_details: Option<Value>,
    /// Payment methods enabled on this connector (open shapes).
    #[serde(default)]
    pub payment_methods_enabled: Option<Vec<Value>>,
    /// Arbitrary key-value metadata.
    #[serde(default)]
    pub metadata: Option<Value>,
    /// Whether the connector runs against the gateway's test environment.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// Whether the connector is disabled.
    #[serde(default)]
    pub disabled: Option<bool>,
    /// Incoming-webhook verification details. **Treated as secret**: redacted
    /// by [`Debug`].
    #[serde(default)]
    pub connector_webhook_details: Option<Value>,
    /// Whether a **live** incoming-webhook signing secret is stored.
    ///
    /// Presence only, never the secret. `connector_webhook_details` comes back
    /// `null` from a retrieve whatever is stored, so this is the only way to
    /// tell a configured secret from an unconfigured one; a stored empty
    /// secret reads as `false`.
    ///
    /// `None` is a third state: a router that predates the flag said nothing,
    /// which is not the same as saying there is no secret.
    #[serde(default)]
    pub has_live_webhook_secret: Option<bool>,
    /// Whether a **sandbox** incoming-webhook signing secret is stored, on the
    /// same terms as [`has_live_webhook_secret`](Self::has_live_webhook_secret).
    #[serde(default)]
    pub has_sandbox_webhook_secret: Option<bool>,
    /// ISO 8601 creation timestamp.
    #[serde(default)]
    pub created_at: Option<String>,
    /// Whether the connector was deleted, on the delete endpoint's response.
    #[serde(default)]
    pub deleted: Option<bool>,
    /// Every shop the account serves, enabled or not. Empty from an older
    /// API.
    #[serde(default)]
    pub assigned_profile_ids: Vec<String>,
    /// The other shops the account is shared with. Empty from an older API.
    #[serde(default)]
    pub shared_profile_ids: Vec<String>,
    /// The shops the account is assigned to but switched off for. Empty from
    /// an older API.
    #[serde(default)]
    pub disabled_profile_ids: Vec<String>,
    /// The payment methods enabled for sandbox payments. `None` means sandbox
    /// follows `payment_methods_enabled`.
    #[serde(default)]
    pub payment_methods_enabled_sandbox: Option<Vec<Value>>,
    /// Live payment method types the processor does not support.
    #[serde(default)]
    pub unsupported_payment_method_types_live: Option<Vec<String>>,
    /// Sandbox payment method types the processor does not support.
    #[serde(default)]
    pub unsupported_payment_method_types_sandbox: Option<Vec<String>>,
    /// How the processor tells sandbox from live: `"credentials"`,
    /// `"request_flag"`, `"deployment_host"`, `"none"`, `"unaudited"` or
    /// `"test_only"`.
    #[serde(default)]
    pub sandbox_mechanism: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for ConnectorResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectorResponse")
            .field("merchant_connector_id", &self.merchant_connector_id)
            .field("connector_type", &self.connector_type)
            .field("connector_name", &self.connector_name)
            .field("profile_id", &self.profile_id)
            .field("merchant_id", &self.merchant_id)
            .field("status", &self.status)
            .field("connector_label", &self.connector_label)
            .field(
                "connector_account_details",
                &self.connector_account_details.as_ref().map(|_| REDACTED),
            )
            .field("payment_methods_enabled", &self.payment_methods_enabled)
            .field("metadata", &self.metadata)
            .field("test_mode", &self.test_mode)
            .field("disabled", &self.disabled)
            .field(
                "connector_webhook_details",
                &self.connector_webhook_details.as_ref().map(|_| REDACTED),
            )
            .field("has_live_webhook_secret", &self.has_live_webhook_secret)
            .field(
                "has_sandbox_webhook_secret",
                &self.has_sandbox_webhook_secret,
            )
            .field("created_at", &self.created_at)
            .field("deleted", &self.deleted)
            .field("assigned_profile_ids", &self.assigned_profile_ids)
            .field("shared_profile_ids", &self.shared_profile_ids)
            .field("disabled_profile_ids", &self.disabled_profile_ids)
            .field(
                "payment_methods_enabled_sandbox",
                &self.payment_methods_enabled_sandbox,
            )
            .field(
                "unsupported_payment_method_types_live",
                &self.unsupported_payment_method_types_live,
            )
            .field(
                "unsupported_payment_method_types_sandbox",
                &self.unsupported_payment_method_types_sandbox,
            )
            .field("sandbox_mechanism", &self.sandbox_mechanism)
            .field("extra", &self.extra)
            .finish()
    }
}

/// Result of registering a webhook endpoint with a connector.
///
/// `webhook_secret` is the signing secret the connector minted for the new
/// endpoint (e.g. Stripe's `whsec_…`). It is already persisted server-side into
/// the connector's webhook verification details; [`Debug`] redacts it.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookRegisterResponse {
    /// Whether the registration succeeded: `"success"` or `"failure"`.
    pub webhook_registration_status: String,

    /// Event scope registered: the string `"all_events"`, or
    /// `{"specific_event": "…"}`.
    #[serde(default)]
    pub event_type: Option<Value>,
    /// Credential set registered against: `"live"` or `"sandbox"`.
    #[serde(default)]
    pub environment: Option<String>,
    /// The connector's identifier for the registered endpoint.
    #[serde(default)]
    pub connector_webhook_id: Option<String>,
    /// Signing secret the connector minted for the endpoint. **Secret**:
    /// redacted by [`Debug`].
    #[serde(default)]
    pub webhook_secret: Option<String>,
    /// Error code, when the registration failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message, when the registration failed.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for ConnectorWebhookRegisterResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectorWebhookRegisterResponse")
            .field(
                "webhook_registration_status",
                &self.webhook_registration_status,
            )
            .field("event_type", &self.event_type)
            .field("environment", &self.environment)
            .field("connector_webhook_id", &self.connector_webhook_id)
            .field(
                "webhook_secret",
                &self.webhook_secret.as_ref().map(|_| REDACTED),
            )
            .field("error_code", &self.error_code)
            .field("error_message", &self.error_message)
            .field("extra", &self.extra)
            .finish()
    }
}

/// One webhook endpoint registered with a connector.
///
/// Carries no secret: the signing secret is only ever returned at registration
/// time, so `Debug` is derived.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookEntry {
    /// The connector's identifier for this endpoint.
    pub connector_webhook_id: String,

    /// Event scope: the string `"all_events"`, or
    /// `{"specific_event": "…"}`.
    #[serde(default)]
    pub event_type: Option<Value>,
    /// Credential set the endpoint belongs to. Absent for registrations stored
    /// before environments were tracked (those are all live).
    #[serde(default)]
    pub environment: Option<String>,
    /// Callback URL the endpoint is registered to. Present when the list is
    /// sourced live from the connector (e.g. Stripe); absent for entries
    /// reconstructed from stored registration metadata only.
    #[serde(default)]
    pub webhook_url: Option<String>,
    /// Endpoint status as the connector reports it, e.g. `"enabled"`.
    #[serde(default)]
    pub status: Option<String>,
    /// Events the endpoint is subscribed to at the connector.
    #[serde(default)]
    pub enabled_events: Option<Vec<String>>,
    /// Events Delopay handles that this endpoint is **not** subscribed to. A
    /// PSP freezes an endpoint's event list at registration time, so an
    /// endpoint registered before an event type was added keeps missing it —
    /// nothing errors, the events simply never arrive.
    ///
    /// `Some([])` means the subscription is current. A non-empty list means
    /// those events are being silently dropped; call
    /// [`Connectors::sync_webhook_events`](crate::resources::connectors::Connectors::sync_webhook_events)
    /// to repair it. `None` means the subscription could not be inspected
    /// (non-Stripe connectors, or a list reconstructed from stored metadata) —
    /// which is not the same as "checked and healthy".
    #[serde(default)]
    pub missing_events: Option<Vec<String>>,
    /// Unix timestamp (seconds) the endpoint was created at the connector.
    #[serde(default)]
    pub created_at: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The webhook endpoints registered for one connector.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookListResponse {
    /// Snake-case connector identifier the endpoints belong to.
    pub connector: String,
    /// The registered endpoints.
    #[serde(default = "Vec::new")]
    pub webhooks: Vec<ConnectorWebhookEntry>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One endpoint's outcome from
/// [`Connectors::sync_webhook_events`](crate::resources::connectors::Connectors::sync_webhook_events).
///
/// Carries no secret: syncing preserves the existing endpoint and its signing
/// secret rather than minting a new one, so `Debug` is derived.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookSyncResult {
    /// The connector's identifier for the endpoint.
    pub connector_webhook_id: String,

    /// Credential set the endpoint belongs to: `"live"` or `"sandbox"`.
    #[serde(default)]
    pub environment: Option<String>,
    /// Callback URL the endpoint is registered to.
    #[serde(default)]
    pub webhook_url: Option<String>,
    /// Endpoint status as the connector reports it, e.g. `"enabled"`.
    #[serde(default)]
    pub status: Option<String>,
    /// Whether the subscription was actually rewritten. `false` with an empty
    /// [`added_events`](Self::added_events) means it was already current.
    #[serde(default)]
    pub updated: bool,
    /// Events that were missing and have now been subscribed.
    #[serde(default = "Vec::new")]
    pub added_events: Vec<String>,
    /// Set when this endpoint could not be updated; the others are unaffected.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The result of bringing a connector's webhook subscriptions up to date.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorWebhookSyncResponse {
    /// Snake-case connector identifier the endpoints belong to.
    pub connector: String,
    /// The full event set Delopay expects to be subscribed to.
    #[serde(default = "Vec::new")]
    pub expected_events: Vec<String>,
    /// One entry per endpoint registered at this connector account, across
    /// every credential set whose endpoints could be listed. A failure on one
    /// endpoint never aborts the rest.
    #[serde(default = "Vec::new")]
    pub endpoints: Vec<ConnectorWebhookSyncResult>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Outcome of registering one URL as a Stripe payment method domain.
///
/// The status strings the API sends today are `"registered"`,
/// `"already_registered"`, `"invalid_url"` and `"failed"`; kept as a `String`
/// so a new one does not fail the whole response.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct StripePaymentMethodDomainResult {
    /// The URL exactly as sent.
    pub url: String,

    /// Host actually registered with Stripe; absent when the URL failed to
    /// parse.
    #[serde(default)]
    pub domain: Option<String>,
    /// `"registered"`, `"already_registered"`, `"invalid_url"` or `"failed"`.
    #[serde(default)]
    pub status: Option<String>,
    /// Stripe's `apple_pay.status` for the domain (`"active"`, `"inactive"`),
    /// when reported.
    #[serde(default)]
    pub apple_pay_status: Option<String>,
    /// Human-readable failure or duplicate detail. Never contains credentials.
    #[serde(default)]
    pub message: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The per-URL outcomes of registering Stripe payment method domains.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct StripePaymentMethodDomainsRegisterResponse {
    /// Credential set the domains were registered against: `"live"` or
    /// `"sandbox"`.
    #[serde(default)]
    pub environment: Option<String>,
    /// One row per URL sent, in the order they were sent. Duplicates by
    /// resolved host are collapsed server-side but still get their own row.
    #[serde(default = "Vec::new")]
    pub results: Vec<StripePaymentMethodDomainResult>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What a connector account's own processor says about it.
///
/// This is **not** a credential check. A processor can revoke an account's
/// ability to take payments while the stored credentials stay perfectly valid,
/// and a credential check reports healthy throughout such an outage. Only the
/// account's own status carries that answer.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorHealthResponse {
    /// The connector account probed.
    pub merchant_connector_id: String,
    /// Connector (gateway) name, e.g. `"stripe"`.
    pub connector: String,
    /// Which credential set answered: `true` for sandbox, `false` for live.
    pub test_mode: bool,
    /// `"healthy"`, `"degraded"`, `"cannot_accept_payments"` or `"unknown"`.
    ///
    /// `"unknown"` is a real third state and must never be rendered as either
    /// good or bad news: reported as healthy it endorses an account that may be
    /// restricted, reported as a restriction it sends a merchant to fail over
    /// off a connector that was fine.
    pub state: ConnectorHealthState,
    /// Whether the processor will accept charges. Absent **and** `null` both
    /// mean the processor did not say; neither may be read as `false`. `false`
    /// appears only when the processor said so.
    #[serde(default)]
    pub can_accept_charges: Option<bool>,
    /// Per-method capability states as the processor reports them.
    #[serde(default = "Vec::new")]
    pub capabilities: Vec<ConnectorCapability>,
    /// What the processor is still waiting on, when it says.
    #[serde(default)]
    pub requirements: Option<ConnectorHealthRequirements>,
    /// The individual probes behind [`state`](Self::state).
    #[serde(default = "Vec::new")]
    pub checks: Vec<ConnectorHealthCheck>,
    /// Whether this answer was served from a stored probe rather than a fresh
    /// one. Ask for a refresh to force a new probe.
    #[serde(default)]
    pub stale: Option<bool>,
    /// Where the credentials that were probed came from, when reported.
    #[serde(default)]
    pub credential_source: Option<String>,
    /// The processor's own id for the account the credentials authenticate as.
    ///
    /// It is not a claim about a *connected* account: a Stripe direct charge
    /// sends `Stripe-Account` and runs on an account this probe never contacts.
    #[serde(default)]
    pub processor_account_id: Option<String>,
    /// The account's display name at the processor, else its business name.
    /// Never a label typed into DeloPay. Absent means "not reported" — render
    /// it that way rather than as blank or as your own label.
    #[serde(default)]
    pub processor_account_name: Option<String>,
    /// The account's country at the processor.
    #[serde(default)]
    pub processor_account_country: Option<String>,
    /// The account's default currency, upper-case ISO 4217. The account
    /// default, not a settlement promise.
    #[serde(default)]
    pub processor_default_currency: Option<String>,
    /// The address the processor associates with the account. Not a login.
    #[serde(default)]
    pub processor_account_email: Option<String>,
    /// The processor's own kind for the account, verbatim.
    #[serde(default)]
    pub processor_account_type: Option<String>,
    /// Whether the processor pays out on this account. Informational beside
    /// [`can_accept_charges`](Self::can_accept_charges): it does not move
    /// [`state`](Self::state).
    #[serde(default)]
    pub payouts_enabled: Option<bool>,
    /// Present exactly when the state is `"unknown"`, saying why nothing could
    /// be established — see [`ConnectorHealthUnknownReason`].
    #[serde(default)]
    pub unknown_reason: Option<ConnectorHealthUnknownReason>,
    /// When the probe ran (RFC 3339).
    #[serde(default)]
    pub probed_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The overall health verdict for a connector account: `"healthy"`,
/// `"degraded"`, `"cannot_accept_payments"` or `"unknown"`.
pub type ConnectorHealthState = String;

/// Why a connector's health could not be established, present exactly when the
/// state is `"unknown"`.
///
/// `"connector_not_supported"`, `"credentials_unreadable"`,
/// `"credentials_missing_api_key"`, `"sandbox_credentials_missing"`,
/// `"processor_unreachable"`, `"processor_rejected_credentials"`,
/// `"processor_response_unreadable"` and
/// `"processor_did_not_report_chargeability"`.
///
/// A stable code rather than a sentence: the router compiles no merchant-facing
/// prose, so render your own words. Worth branching on where the action
/// differs — a processor that could not be reached is an outage to wait out,
/// one that refused the credentials is a key to fix, and the two are
/// deliberately separate values so a consumer cannot confuse them.
pub type ConnectorHealthUnknownReason = String;

/// One payment method's state on the processor's account.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCapability {
    /// The processor's own key for the capability. Deliberately a plain
    /// string: processors add capabilities on their own schedule, and a closed
    /// set would drop a new one rather than show it.
    pub id: String,
    /// `"active"`, `"inactive"`, `"pending"` or `"unknown"`.
    pub state: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One probe behind a connector's health verdict.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorHealthCheck {
    /// The check's identifier.
    pub id: String,
    /// `"healthy"`, `"unhealthy"`, `"unknown"` or `"unsupported"`.
    pub status: String,
    /// Why the check reported what it did.
    #[serde(default)]
    pub reason: Option<String>,
    /// The values the translated reason carries, e.g. `amount_minor` and
    /// `currency`.
    #[serde(default)]
    pub params: Option<Value>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What a processor is still waiting on before the account is fully enabled.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorHealthRequirements {
    /// The processor's own reason for disabling the account, when it gives one.
    #[serde(default)]
    pub disabled_reason: Option<String>,
    /// Requirements due now.
    #[serde(default = "Vec::new")]
    pub currently_due: Vec<String>,
    /// Requirements whose deadline has passed.
    #[serde(default = "Vec::new")]
    pub past_due: Vec<String>,
    /// Errors the processor raised against submitted requirements.
    #[serde(default = "Vec::new")]
    pub errors: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One URL's outcome from registering Apple Pay domains on an Airwallex
/// account.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AirwallexApplePayDomainResult {
    /// The URL exactly as sent.
    pub url: String,
    /// The host actually registered; absent when the URL failed to parse.
    #[serde(default)]
    pub domain: Option<String>,
    /// `"registered"`, `"already_registered"`, `"invalid_url"` or `"failed"`.
    #[serde(default)]
    pub status: Option<String>,
    /// Airwallex's own detail for a failure. A failure usually means the domain
    /// is not yet serving the association file.
    #[serde(default)]
    pub message: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The per-URL outcomes of registering Apple Pay domains on an Airwallex
/// account.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AirwallexApplePayDomainsRegisterResponse {
    /// Credential set the domains were registered against: `"live"` or
    /// `"sandbox"`.
    #[serde(default)]
    pub environment: Option<String>,
    /// One row per URL sent, in the order they were sent.
    #[serde(default = "Vec::new")]
    pub results: Vec<AirwallexApplePayDomainResult>,
    /// Every domain now on the account, when the processor reports the full
    /// list back.
    #[serde(default = "Vec::new")]
    pub registered_domains: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A connected provider account's optional buyer-email preference, for one
/// credential environment.
///
/// HTTP success alone does not mean a preference changed: read
/// [`outcome`](Self::outcome). Only `"verified"` confirms a requested value
/// through a fresh read of the exact account.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorBuyerMailResponse {
    /// The connector account in the request path.
    pub merchant_connector_id: String,
    /// The provider, for example `"whop"`.
    pub connector: String,
    /// The provider account the preference belongs to.
    pub provider_account_id: String,
    /// `true` for the sandbox credential set, `false` for live.
    pub test_mode: bool,
    /// Reported as `"provider_account"`: the preference applies to every shop
    /// sharing the provider account, not to one shop.
    pub scope: String,
    /// The preference. `None` establishes no on/off value.
    #[serde(default)]
    pub send_customer_emails: Option<bool>,
    /// `"current"`, `"verified"`, `"conflict"`, `"refused"` or
    /// `"outcome_unknown"`.
    pub outcome: String,
    /// Stable explanation of a conflict, refusal or uncertain result.
    #[serde(default)]
    pub reason: Option<String>,
    /// ISO 8601 timestamp of the reported evidence.
    pub observed_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What folding copies of one provider account into a connector does, or did.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorConsolidationResponse {
    /// The account the copies are folded into.
    pub merchant_connector_id: String,
    /// The provider, for example `"stripe"`.
    pub connector_name: String,
    /// Whether this was a preview that wrote nothing.
    pub dry_run: bool,
    /// Whether this request folded the copies in.
    pub consolidated: bool,
    /// Confirms exactly this preview; it changes whenever an account does.
    pub preview_token: String,
    /// The kept account first, then every copy asked for.
    #[serde(default = "Vec::new")]
    pub accounts: Vec<ConsolidationAccount>,
    /// Every shop the consolidated account serves, before and after.
    #[serde(default = "Vec::new")]
    pub shops: Vec<ConsolidationShop>,
    /// The settings the eligible accounts disagree on.
    #[serde(default = "Vec::new")]
    pub conflicts: Vec<ConsolidationConflict>,
    /// What stops the consolidation, e.g. `"no_eligible_copies"`. Empty when
    /// it can be confirmed.
    #[serde(default = "Vec::new")]
    pub blockers: Vec<String>,
    /// How many records were renamed. Present once consolidated.
    #[serde(default)]
    pub changes: Option<ConsolidationChanges>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One account of a consolidation.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConsolidationAccount {
    /// The connector account.
    pub merchant_connector_id: String,
    /// The account's label.
    #[serde(default)]
    pub connector_label: Option<String>,
    /// Whether this is the account the copies are folded into.
    pub kept: bool,
    /// Why the account can or cannot be folded in, e.g. `"eligible"` or
    /// `"live_credentials_differ"`.
    pub eligibility: String,
    /// The shops the account serves now.
    #[serde(default = "Vec::new")]
    pub profile_ids: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One shop of a consolidated account.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConsolidationShop {
    /// The shop (business profile).
    pub profile_id: String,
    /// The accounts that serve the shop now.
    #[serde(default = "Vec::new")]
    pub served_by: Vec<String>,
    /// Whether the shop sends payments to this provider account now.
    pub enabled_before: bool,
    /// Whether it does afterwards; always equal to `enabled_before`.
    pub enabled_after: bool,
    /// The currencies the account takes in the shop afterwards; `None` when
    /// nothing restricts them.
    #[serde(default)]
    pub currencies_after: Option<Vec<String>>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A setting the accounts of a consolidation disagree on.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConsolidationConflict {
    /// The setting, e.g. `"payment_methods"`, `"label"` or `"limits"`.
    pub setting: String,
    /// Each distinct value and the accounts holding it.
    #[serde(default = "Vec::new")]
    pub values: Vec<ConsolidationConflictValue>,
    /// The accounts whose value may be chosen.
    #[serde(default = "Vec::new")]
    pub choosable: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One value of a conflicting setting.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConsolidationConflictValue {
    /// The accounts holding this value.
    #[serde(default = "Vec::new")]
    pub merchant_connector_ids: Vec<String>,
    /// A summary of the value, shaped per setting.
    #[serde(default)]
    pub summary: Value,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// How many records a consolidation moved from a copy to the kept account.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConsolidationChanges {
    /// Routing configurations.
    pub routing_configs: i32,
    /// Fallback connector lists.
    pub fallback_lists: i32,
    /// Checkout layouts.
    pub checkout_layouts: i32,
    /// Surcharge rules.
    pub surcharge_rules: i32,
    /// Hidden-account entries.
    pub hidden_accounts: i32,
    /// Subscription shop configurations.
    pub subscription_shop_configs: i32,
    /// Product references.
    pub product_references: i32,
    /// Shop billing settings.
    pub shop_billing_settings: i32,
    /// Role grants.
    pub role_grants: i32,
    /// Saved payment methods.
    pub saved_payment_methods: i32,
    /// Customers.
    pub customers: i32,
    /// Mandates.
    pub mandates: i32,
    /// Subscriptions moved with their agreements.
    pub subscriptions: i32,
    /// Subscription terms.
    pub subscription_terms: i32,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A connector account's transaction-currency policy.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCurrencyPolicyResponse {
    /// The connector account.
    pub merchant_connector_id: String,
    /// The provider, for example `"stripe"`.
    pub connector_name: String,
    /// The shop the connector was created in, which may have stopped using
    /// it. The shops it serves are [`shops`](Self::shops).
    pub profile_id: String,
    /// The account's own list. `None`: every currency the provider supports.
    #[serde(default)]
    pub allowed_currencies: Option<Vec<String>>,
    /// The policy was saved in a form this API version cannot read: the
    /// account takes no new payment until it is saved again.
    pub unreadable: bool,
    /// What the account does with a payment in a currency it does not take.
    pub conversion: ConnectorCurrencyConversion,
    /// What the provider is known to accept, overall and per method.
    pub provider_capability: ConnectorCurrencyCapability,
    /// Every shop the account serves that the caller may see.
    #[serde(default = "Vec::new")]
    pub shops: Vec<ConnectorShopCurrencies>,
    /// On a write: what it changes (`dry_run`) or changed.
    #[serde(default)]
    pub impact: Option<Vec<ConnectorCurrencyShopImpact>>,
    /// `true` after a saved change.
    pub applied: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A connector account's conversion setting, as read.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCurrencyConversion {
    /// The currency a payment in an untaken currency is converted to; `None`
    /// refuses such a payment.
    #[serde(default)]
    pub convert_to: Option<String>,
    /// The setting could not be read.
    #[serde(default)]
    pub unreadable: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A conversion setting: the currency a payment in a currency the connector
/// does not take is converted to.
///
/// Used on both sides of the currency-policy endpoints. `convert_to` is always
/// serialized: `null` means "refuse such a payment", which is a value, not an
/// omission.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCurrencyConversionSetting {
    /// ISO 4217 currency to convert to; `None` refuses the payment.
    #[serde(default)]
    pub convert_to: Option<String>,
    /// Any additional fields not modeled above.
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl ConnectorCurrencyConversionSetting {
    /// Convert payments in an untaken currency to `currency`.
    #[must_use]
    pub fn convert_to(currency: impl Into<String>) -> Self {
        Self {
            convert_to: Some(currency.into()),
            extra: serde_json::Map::new(),
        }
    }

    /// Refuse payments in an untaken currency (`{"convert_to": null}`).
    #[must_use]
    pub fn refuse() -> Self {
        Self::default()
    }
}

/// What the provider is known to accept.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCurrencyCapability {
    /// Currencies the provider accepts overall; `None` when not known.
    #[serde(default)]
    pub currencies: Option<Vec<String>>,
    /// Currencies per payment method type.
    #[serde(default = "Vec::new")]
    pub payment_method_types: Vec<Value>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The currencies a connector account takes in one shop it serves.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorShopCurrencies {
    /// The shop (business profile).
    pub profile_id: String,
    /// Whether the connector is switched off in this shop.
    pub disabled: bool,
    /// The shop's own narrowing; `None` follows the account's list.
    #[serde(default)]
    pub allowed_currencies: Option<Vec<String>>,
    /// The currencies in force in the shop; `None` when nothing restricts
    /// them.
    #[serde(default)]
    pub effective_currencies: Option<Vec<String>>,
    /// Shop currencies outside the account's list, which have no effect.
    #[serde(default = "Vec::new")]
    pub ignored_currencies: Vec<String>,
    /// The shop's own conversion setting; `None` follows the account's.
    #[serde(default)]
    pub conversion: Option<ConnectorCurrencyConversionSetting>,
    /// The conversion currency in force in the shop.
    #[serde(default)]
    pub effective_convert_to: Option<String>,
    /// The shop's currency policy at creation, when reported.
    #[serde(default)]
    pub creation_policy: Option<Value>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What a currency-policy write changes in one shop.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorCurrencyShopImpact {
    /// The shop (business profile).
    pub profile_id: String,
    /// Currencies in force before; `None` when unrestricted.
    #[serde(default)]
    pub before: Option<Vec<String>>,
    /// Currencies in force after; `None` when unrestricted.
    #[serde(default)]
    pub after: Option<Vec<String>>,
    /// Currencies the write removes.
    #[serde(default = "Vec::new")]
    pub removed: Vec<String>,
    /// Whether the write restricts a shop that took every currency.
    pub removed_unbounded: bool,
    /// Currencies no connector of the shop takes afterwards.
    #[serde(default = "Vec::new")]
    pub uncovered: Vec<Value>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The shops a connector account serves.
///
/// Every shop on it is treated the same: the account, not a shop, holds its
/// name, credentials, webhook and limits.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorShopsResponse {
    /// The connector account.
    pub merchant_connector_id: String,
    /// The shop the connector was created in. It may have stopped using the
    /// connector: read membership from
    /// [`assigned_profile_ids`](Self::assigned_profile_ids).
    pub profile_id: String,
    /// Shops, besides `profile_id`, the connector serves.
    #[serde(default = "Vec::new")]
    pub shared_profile_ids: Vec<String>,
    /// The shops the connector serves and is switched off in.
    #[serde(default = "Vec::new")]
    pub disabled_profile_ids: Vec<String>,
    /// Every shop the connector serves, switched on there or not.
    #[serde(default = "Vec::new")]
    pub assigned_profile_ids: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The route document a vault connector should have, diffed against what
/// exists. Nothing is written.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultRoutesPreviewResponse {
    /// The vault.
    pub vault_id: String,
    /// `"sandbox"` or `"live"`.
    pub environment: String,
    /// Opaque token covering the desired route document. Echo it byte for
    /// byte when applying.
    pub desired_fingerprint: String,
    /// The upstream hosts the desired routes forward to.
    #[serde(default = "Vec::new")]
    pub desired_upstream_hosts: Vec<String>,
    /// Opaque token covering what exists now; `None` when no routes exist.
    /// Echo it when applying, `None` included.
    #[serde(default)]
    pub current_fingerprint: Option<String>,
    /// The route changes applying would make.
    #[serde(default = "Vec::new")]
    pub changes: Vec<VaultRouteChange>,
    /// Non-blocking advisories.
    #[serde(default = "Vec::new")]
    pub warnings: Vec<VaultRouteWarning>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One route change of a vault route preview.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultRouteChange {
    /// The route.
    pub route_id: String,
    /// What the route is for, e.g. `"collect"` or `"reveal"`.
    pub purpose: String,
    /// The kind of change, e.g. `"create"` or `"update"`.
    pub change: String,
    /// The fields that change.
    #[serde(default = "Vec::new")]
    pub field_changes: Vec<Value>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A non-blocking advisory about vault routes.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultRouteWarning {
    /// Machine-readable warning code.
    pub code: String,
    /// The connector the warning concerns.
    #[serde(default)]
    pub connector: Option<String>,
    /// Detail for the warning.
    #[serde(default)]
    pub detail: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The result of writing a vault connector's routes.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultRoutesApplyResponse {
    /// Whether the routes were written.
    pub applied: bool,
    /// The ids of the routes in force.
    pub route_ids: VaultRouteIds,
    /// Whether the collect route's id was stored on the connector.
    pub collect_route_id_stored: bool,
    /// Non-blocking advisories.
    #[serde(default = "Vec::new")]
    pub warnings: Vec<VaultRouteWarning>,
    /// What a read-back after the write established.
    #[serde(default)]
    pub verification: Option<VaultRouteApplyVerification>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The ids of a vault's collect and reveal routes.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultRouteIds {
    /// The collect route.
    pub collect: String,
    /// The reveal route.
    pub reveal: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What a read-back after writing vault routes established.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultRouteApplyVerification {
    /// Facts the read-back confirmed.
    #[serde(default = "Vec::new")]
    pub established: Vec<String>,
    /// Facts the read-back could not confirm.
    #[serde(default = "Vec::new")]
    pub not_established: Vec<String>,
    /// Routes that appeared at the vault.
    #[serde(default = "Vec::new")]
    pub routes_appeared: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The shops whose switched-on vault account has stopped working.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultOutagesResponse {
    /// Empty when every vault works. A shop without a vault, or with its vault
    /// switched off, is never listed.
    #[serde(default = "Vec::new")]
    pub outages: Vec<VaultOutage>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One shop whose vault account refuses the API.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultOutage {
    /// The shop (business profile).
    pub profile_id: String,
    /// The shop's name.
    pub profile_name: String,
    /// The vault connector account.
    pub vault_connector_id: String,
    /// The vault connector's name.
    pub vault_connector_name: String,
    /// `"limit_reached"`, `"account_blocked"`, `"credentials_rejected"` or
    /// `"other"`.
    pub cause: String,
    /// ISO 8601 time the outage began.
    pub since: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The configuration checks of a vault connector account.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultVerificationResponse {
    /// Whether every check passed.
    pub passed: bool,
    /// Each check and its outcome.
    #[serde(default = "Vec::new")]
    pub checks: Vec<VaultCheck>,
    /// The shop's processors and whether each one's card payments can be
    /// hidden behind this vault.
    #[serde(default = "Vec::new")]
    pub processors: Vec<VaultProcessorHiding>,
    /// Vault egress IPs the merchant's processors may need to allowlist.
    #[serde(default = "Vec::new")]
    pub egress_ips_to_allowlist: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One vault configuration check.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultCheck {
    /// Which check.
    pub id: String,
    /// The check's outcome, e.g. `"pass"` or `"fail"`.
    pub status: String,
    /// Detail for the outcome.
    #[serde(default)]
    pub detail: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Whether one processor's card payments can be hidden behind a vault.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultProcessorHiding {
    /// The processor's connector account.
    pub merchant_connector_id: String,
    /// The processor, for example `"stripe"`.
    pub connector_name: String,
    /// Whether hiding is possible.
    pub status: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The callback addresses of a merchant's accounts at one payment provider.
///
/// An address belongs to the merchant, the provider and the environment, not
/// to one connector account: every account of that provider follows it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct WebhookAddressResponse {
    /// The provider, for example `"stripe"`.
    pub connector: String,
    /// The connector account in the request path.
    pub merchant_connector_id: String,
    /// `"managed"` (the provider's webhook is created and replaced for you) or
    /// `"manual"` (the merchant enters the URL at the provider).
    pub management: String,
    /// The limits an address must keep to.
    pub constraints: WebhookAddressConstraints,
    /// One entry per environment.
    #[serde(default = "Vec::new")]
    pub environments: Vec<WebhookAddressEnvironment>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The limits a callback address must keep to.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct WebhookAddressConstraints {
    /// Shortest `custom` alias.
    pub alias_min_length: i32,
    /// Longest `custom` alias.
    pub alias_max_length: i32,
    /// Longest `anonymous` prefix.
    pub prefix_max_length: i32,
    /// Shortest generated identifier body.
    pub body_min_length: i32,
    /// Shortest numeric generated identifier body.
    pub numeric_body_min_length: i32,
    /// Longest generated identifier body.
    pub body_max_length: i32,
    /// Address changes allowed per window.
    pub max_changes: i32,
    /// The change window, in days.
    pub change_window_days: i32,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The callback address of one environment.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct WebhookAddressEnvironment {
    /// `"live"` or `"sandbox"`; `None` for a provider whose address is
    /// shared across environments.
    #[serde(default)]
    pub environment: Option<String>,
    /// Whether one address serves both environments.
    pub shared_across_environments: bool,
    /// `"standard"`, `"custom"` or `"anonymous"`.
    pub mode: String,
    /// The saved alias or generated identifier.
    #[serde(default)]
    pub identifier: Option<String>,
    /// The saved identifier format, in `anonymous` mode.
    #[serde(default)]
    pub format: Option<WebhookAddressFormat>,
    /// ISO 8601 time of the last change.
    #[serde(default)]
    pub updated_at: Option<String>,
    /// How many changes remain in the window.
    pub rate_limit: WebhookAddressRateLimit,
    /// Whether the caller may change this address.
    pub editable: bool,
    /// Per credential group, the desired URL beside the registered one and its
    /// status. Only `registered` means the provider delivers to the desired
    /// URL.
    #[serde(default = "Vec::new")]
    pub groups: Vec<Value>,
    /// Affected credential groups made up only of accounts the caller may not
    /// see.
    pub hidden_group_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The identifier format of an `anonymous` callback address.
///
/// Used on both sides of the webhook-address endpoints.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct WebhookAddressFormat {
    /// A fixed prefix, e.g. `"wh-"`.
    pub prefix: String,
    /// The character set of the generated body, e.g. `"alphanumeric"`.
    pub style: String,
    /// Length of the generated body.
    pub length: i32,
    /// Any additional fields not modeled above.
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl WebhookAddressFormat {
    /// A format of `prefix` plus a `length`-character body in `style`.
    #[must_use]
    pub fn new(prefix: impl Into<String>, style: impl Into<String>, length: i32) -> Self {
        Self {
            prefix: prefix.into(),
            style: style.into(),
            length,
            extra: serde_json::Map::new(),
        }
    }
}

/// How many callback-address changes remain.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct WebhookAddressRateLimit {
    /// Changes left in the window.
    pub remaining_changes: i32,
    /// ISO 8601 time the next change is allowed, when none remain.
    #[serde(default)]
    pub next_change_allowed_at: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The result of validating a proposed callback address. Nothing is saved.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct WebhookAddressPreviewResponse {
    /// Whether the proposal is valid.
    pub valid: bool,
    /// Why the proposal is not valid. Empty when `valid` is `true`.
    #[serde(default = "Vec::new")]
    pub errors: Vec<WebhookAddressValidationError>,
    /// The identifier the `resulting_url` values use. Absent in `standard`
    /// mode and when the proposal is not valid.
    #[serde(default)]
    pub example_identifier: Option<String>,
    /// `true` when saving uses exactly `example_identifier`; `false` when
    /// saving generates a new identifier of the same shape.
    pub identifier_final: bool,
    /// Whether saving would change the callback URL.
    pub changes_address: bool,
    /// How many changes remain in the window.
    pub rate_limit: WebhookAddressRateLimit,
    /// Whether the caller may save this address.
    pub editable: bool,
    /// Whether saving needs `confirm_shared: true`, because the address also
    /// applies to other connector accounts.
    pub requires_shared_confirmation: bool,
    /// One entry per affected credential group the caller may see.
    #[serde(default = "Vec::new")]
    pub groups: Vec<WebhookAddressPreviewGroup>,
    /// Affected credential groups made up only of accounts the caller may not
    /// see.
    pub hidden_group_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Why a proposed callback address is not valid.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct WebhookAddressValidationError {
    /// The field at fault, e.g. `"alias"`.
    pub field: String,
    /// Machine-readable reason, e.g. `"too_short"`.
    pub code: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One credential group a proposed callback address affects.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct WebhookAddressPreviewGroup {
    /// Identifies the credential group.
    pub credentials_sha256: String,
    /// Whether the connector in the request path belongs to the group.
    pub contains_this_connector: bool,
    /// The group's callback URL now.
    pub current_url: String,
    /// The URL saving would give it; absent when the proposal is not valid.
    #[serde(default)]
    pub resulting_url: Option<String>,
    /// The connector accounts in the group the caller may see.
    #[serde(default = "Vec::new")]
    pub accounts: Vec<Value>,
    /// Accounts in the group the caller may not see.
    pub hidden_account_count: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Every webhook the provider lists for a connector's credentials in one
/// environment.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProviderWebhookListResponse {
    /// The provider, for example `"stripe"`.
    pub connector: String,
    /// `"live"` or `"sandbox"`.
    pub environment: String,
    /// What the listing covers: `"account"`, `"app"` or
    /// `"merchant_account"`.
    pub coverage: String,
    /// The provider account the list belongs to, partly masked.
    #[serde(default)]
    pub provider_account: Option<String>,
    /// Which changes the provider allows.
    pub capabilities: ProviderWebhookCapabilities,
    /// How many webhooks the provider allows, when known.
    #[serde(default)]
    pub endpoint_limit: Option<i32>,
    /// The events the platform's own webhook must carry.
    #[serde(default = "Vec::new")]
    pub required_events: Vec<String>,
    /// The state of the platform's own webhook.
    pub managed: ManagedWebhookState,
    /// Every webhook listed.
    #[serde(default = "Vec::new")]
    pub endpoints: Vec<ProviderWebhookEndpoint>,
    /// Whether the caller may change webhooks at the provider.
    pub editable: bool,
    /// Why the caller may not, e.g. `"missing_permission"`.
    #[serde(default)]
    pub edit_blocked: Option<String>,
    /// ISO 8601 time of the provider read.
    pub read_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Which webhook changes a provider allows.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProviderWebhookCapabilities {
    /// Creating a webhook.
    pub create: bool,
    /// Changing a webhook's URL.
    pub update_url: bool,
    /// Changing a webhook's events.
    pub update_events: bool,
    /// Switching a webhook on or off.
    pub update_enabled: bool,
    /// Deleting a webhook.
    pub delete: bool,
    /// Replacing every webhook with the platform's own.
    pub replace_all: bool,
    /// Why replacing every webhook is unavailable.
    #[serde(default)]
    pub replace_all_unavailable: Option<Value>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The state of the platform's own webhook at the provider.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ManagedWebhookState {
    /// Machine-readable state.
    pub status: String,
    /// The webhook's destination, masked.
    #[serde(default)]
    pub url: Option<String>,
    /// The provider's id of the webhook.
    #[serde(default)]
    pub endpoint_id: Option<String>,
    /// Required events the webhook lacks.
    #[serde(default = "Vec::new")]
    pub missing_events: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One webhook as the provider lists it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProviderWebhookEndpoint {
    /// The provider's id of the webhook.
    pub id: String,
    /// The destination, with every part that may hold a secret masked.
    pub url: String,
    /// The destination's host.
    pub host: String,
    /// Who the webhook belongs to, e.g. `"this_connector"` or `"other"`.
    pub owner: String,
    /// The label of the connector account an `other_connector` webhook
    /// belongs to.
    #[serde(default)]
    pub connector_label: Option<String>,
    /// The subscribed events; absent for a provider without per-webhook
    /// events.
    #[serde(default)]
    pub events: Option<Vec<String>>,
    /// `false` when the provider keeps the webhook but does not deliver to it.
    #[serde(default)]
    pub enabled: Option<bool>,
    /// Required events a platform webhook lacks.
    #[serde(default)]
    pub missing_events: Option<Vec<String>>,
    /// Unix timestamp (seconds) of creation, when reported.
    #[serde(default)]
    pub created_at: Option<i64>,
    /// This exact state of the webhook; a change or delete sends it back.
    pub fingerprint: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A webhook created at the provider.
///
/// `Debug` is hand-written: `signing_secret` is a live credential and prints
/// as `Some("[redacted]")`.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct ProviderWebhookCreateResponse {
    /// The webhook as the provider lists it.
    pub endpoint: ProviderWebhookEndpoint,
    /// The signing secret the provider returned. Returned this once: it is
    /// not kept and cannot be read again. Absent for a provider that returns
    /// none.
    #[serde(default)]
    pub signing_secret: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for ProviderWebhookCreateResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProviderWebhookCreateResponse")
            .field("endpoint", &self.endpoint)
            .field(
                "signing_secret",
                &self.signing_secret.as_ref().map(|_| REDACTED),
            )
            .field("extra", &self.extra)
            .finish()
    }
}

/// What deleting one webhook at the provider did.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProviderWebhookDeleteResult {
    /// The provider's id of the webhook.
    pub id: String,
    /// The destination, masked.
    pub url: String,
    /// `deleted`, `already_gone`, `failed`, `unknown` or `not_attempted`.
    pub outcome: String,
    /// The provider's message when it refused.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What replacing every webhook with the platform's own would delete and
/// keep. Nothing is changed.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProviderWebhookReplacePreviewResponse {
    /// The provider, for example `"stripe"`.
    pub connector: String,
    /// `"live"` or `"sandbox"`.
    pub environment: String,
    /// What the listing covers: `"account"`, `"app"` or
    /// `"merchant_account"`.
    pub coverage: String,
    /// The provider account the list belongs to, partly masked.
    #[serde(default)]
    pub provider_account: Option<String>,
    /// `register_first`, or `delete_first` when the provider's webhook limit
    /// leaves no room: then no webhook receives events for the account until
    /// the registration succeeds.
    pub sequence: String,
    /// The state of the platform's own webhook.
    pub managed: ManagedWebhookState,
    /// The webhooks a confirmed replacement deletes.
    #[serde(default = "Vec::new")]
    pub delete: Vec<ProviderWebhookEndpoint>,
    /// The webhooks it keeps.
    #[serde(default = "Vec::new")]
    pub keep: Vec<ProviderWebhookEndpoint>,
    /// The connector accounts whose credentials share this provider webhook.
    #[serde(default = "Vec::new")]
    pub accounts: Vec<Value>,
    /// Accounts sharing it that the caller may not see.
    pub hidden_account_count: i64,
    /// Whether the caller may change webhooks at the provider.
    pub editable: bool,
    /// Why the caller may not, e.g. `"missing_permission"`.
    #[serde(default)]
    pub edit_blocked: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What replacing every webhook with the platform's own did.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ProviderWebhookReplaceResponse {
    /// `completed`, `incomplete` (sending the request again continues), or
    /// `scope_changed` (the list changed since the preview; nothing was
    /// deleted).
    pub status: String,
    /// The order the replacement ran in.
    pub sequence: String,
    /// The state of the platform's own webhook afterwards.
    pub managed: ManagedWebhookState,
    /// One result per confirmed webhook.
    #[serde(default = "Vec::new")]
    pub results: Vec<ProviderWebhookDeleteResult>,
    /// Confirmed webhooks the provider still lists.
    #[serde(default = "Vec::new")]
    pub remaining: Vec<ProviderWebhookEndpoint>,
    /// Webhooks the provider lists now that were not confirmed. Never
    /// deleted.
    #[serde(default = "Vec::new")]
    pub unconfirmed: Vec<ProviderWebhookEndpoint>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The per-URL outcomes of registering Apple Pay domains on a Whop account.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct WhopApplePayDomainsRegisterResponse {
    /// Credential set the domains were registered against: `"live"` or
    /// `"sandbox"`.
    pub environment: String,
    /// One row per URL sent, in the order they were sent.
    #[serde(default = "Vec::new")]
    pub results: Vec<WhopApplePayDomainResult>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One URL's outcome in [`WhopApplePayDomainsRegisterResponse`].
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct WhopApplePayDomainResult {
    /// The URL exactly as sent.
    pub url: String,
    /// The host registered; absent when the URL failed to parse.
    #[serde(default)]
    pub domain: Option<String>,
    /// `"verified"`, `"already_verified"`, `"pending"`, `"invalid_url"` or
    /// `"failed"`. Only a verified domain shows Apple Pay.
    pub status: String,
    /// Whop's id of the domain.
    #[serde(default)]
    pub whop_domain_id: Option<String>,
    /// Whop's own detail for a failure.
    #[serde(default)]
    pub message: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    #[test]
    fn connector_response_decodes_shop_assignment_and_sandbox_fields() {
        let parsed: ConnectorResponse = serde_json::from_str(
            r#"{
                "merchant_connector_id": "mca_1",
                "assigned_profile_ids": ["pro_1", "pro_2"],
                "shared_profile_ids": ["pro_2"],
                "disabled_profile_ids": ["pro_2"],
                "payment_methods_enabled_sandbox": null,
                "unsupported_payment_method_types_live": ["klarna"],
                "sandbox_mechanism": "request_flag"
            }"#,
        )
        .unwrap();
        assert_eq!(parsed.assigned_profile_ids, ["pro_1", "pro_2"]);
        assert_eq!(parsed.shared_profile_ids, ["pro_2"]);
        assert!(parsed.payment_methods_enabled_sandbox.is_none());
        assert_eq!(parsed.sandbox_mechanism.as_deref(), Some("request_flag"));
        // An older API omits the shop lists; they read as empty.
        let older: ConnectorResponse =
            serde_json::from_str(r#"{"merchant_connector_id":"mca_1"}"#).unwrap();
        assert!(older.assigned_profile_ids.is_empty());
        assert!(older.disabled_profile_ids.is_empty());

        let check: ConnectorHealthCheck = serde_json::from_str(
            r#"{"id":"min_amount","status":"unhealthy","params":{"amount_minor":50,"currency":"EUR"}}"#,
        )
        .unwrap();
        assert_eq!(check.params.unwrap()["amount_minor"], 50);
    }

    /// Credentials the API echoes back must not reach a log line. Mutation:
    /// print `&self.connector_account_details` instead of the redacted map —
    /// the first assertion goes red.
    #[test]
    fn connector_response_debug_redacts_credentials() {
        let parsed: ConnectorResponse = serde_json::from_str(
            r#"{
                "merchant_connector_id": "mca_1",
                "connector_name": "stripe",
                "connector_account_details": {"api_key": "sk_live_supersecret"},
                "connector_webhook_details": {"merchant_secret": "whsec_topsecret"}
            }"#,
        )
        .unwrap();

        let rendered = format!("{parsed:?}");
        assert!(!rendered.contains("sk_live_supersecret"), "{rendered}");
        assert!(!rendered.contains("whsec_topsecret"), "{rendered}");
        assert!(
            rendered.contains("connector_account_details: Some(\"[redacted]\")"),
            "{rendered}"
        );
        assert!(
            rendered.contains("connector_webhook_details: Some(\"[redacted]\")"),
            "{rendered}"
        );
        // Non-secret fields still print, or the impl would be useless.
        assert!(rendered.contains("stripe"), "{rendered}");
        assert!(rendered.contains("mca_1"), "{rendered}");
    }

    /// An absent credential must be distinguishable from a present one.
    /// Mutation: `map(|_| REDACTED)` -> `map_or(Some(REDACTED), ...)`-style
    /// unconditional redaction makes this red.
    #[test]
    fn connector_response_debug_shows_none_for_absent_credentials() {
        let parsed: ConnectorResponse =
            serde_json::from_str(r#"{"merchant_connector_id":"mca_1"}"#).unwrap();
        let rendered = format!("{parsed:?}");
        assert!(
            rendered.contains("connector_account_details: None"),
            "{rendered}"
        );
    }

    /// Unknown fields land in `extra`, and known ones do not. Mutation:
    /// dropping `#[serde(flatten)]` from `extra` makes the lookup return
    /// `None`.
    #[test]
    fn connector_response_keeps_unknown_fields() {
        let parsed: ConnectorResponse = serde_json::from_str(
            r#"{"merchant_connector_id":"mca_1","status":"active","brand_new_field":42}"#,
        )
        .unwrap();
        assert_eq!(parsed.status.as_deref(), Some("active"));
        assert_eq!(parsed.extra.get("brand_new_field"), Some(&Value::from(42)));
        assert!(!parsed.extra.contains_key("status"));
    }

    /// The register response's minted signing secret must not print. Mutation:
    /// print `&self.webhook_secret` directly.
    #[test]
    fn register_response_debug_redacts_the_webhook_secret() {
        let parsed: ConnectorWebhookRegisterResponse = serde_json::from_str(
            r#"{
                "webhook_registration_status": "success",
                "event_type": "all_events",
                "environment": "sandbox",
                "connector_webhook_id": "we_1",
                "webhook_secret": "whsec_minted",
                "error_code": null,
                "error_message": null
            }"#,
        )
        .unwrap();

        let rendered = format!("{parsed:?}");
        assert!(!rendered.contains("whsec_minted"), "{rendered}");
        assert!(
            rendered.contains("webhook_secret: Some(\"[redacted]\")"),
            "{rendered}"
        );
        assert!(rendered.contains("we_1"), "{rendered}");
        assert_eq!(parsed.webhook_registration_status, "success");
        assert_eq!(parsed.environment.as_deref(), Some("sandbox"));
        assert_eq!(parsed.error_code, None);
    }

    /// A specific-event scope stays a structured value, and the list endpoint's
    /// entries deserialize. Mutation: typing `event_type` as `Option<String>`
    /// makes the object form fail to parse.
    #[test]
    fn webhook_list_parses_entries_and_structured_event_types() {
        let parsed: ConnectorWebhookListResponse = serde_json::from_str(
            r#"{
                "connector": "stripe",
                "webhooks": [
                    {
                        "connector_webhook_id": "we_1",
                        "event_type": {"specific_event": "payment_intent.succeeded"},
                        "enabled_events": ["payment_intent.succeeded"],
                        "created_at": 1700000000
                    }
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.connector, "stripe");
        assert_eq!(parsed.webhooks.len(), 1);
        let entry = &parsed.webhooks[0];
        assert_eq!(entry.connector_webhook_id, "we_1");
        assert_eq!(
            entry.event_type.as_ref().unwrap()["specific_event"],
            "payment_intent.succeeded"
        );
        assert_eq!(entry.created_at, Some(1_700_000_000));
        assert_eq!(entry.environment, None);
    }

    /// A response with no `webhooks` key must yield an empty list rather than
    /// failing. Mutation: drop `#[serde(default = "Vec::new")]`.
    #[test]
    fn webhook_list_defaults_to_no_webhooks() {
        let parsed: ConnectorWebhookListResponse =
            serde_json::from_str(r#"{"connector":"adyen"}"#).unwrap();
        assert!(parsed.webhooks.is_empty());
    }

    /// "Subscription is current" and "subscription was never inspected" are
    /// different answers and must stay distinguishable. Mutation: give
    /// `missing_events` a `#[serde(default = "Vec::new")]` and the absent case
    /// collapses into the empty one.
    #[test]
    fn webhook_entry_distinguishes_empty_from_absent_missing_events() {
        let parsed: ConnectorWebhookListResponse = serde_json::from_str(
            r#"{
                "connector": "stripe",
                "webhooks": [
                    {"connector_webhook_id": "we_current", "missing_events": []},
                    {"connector_webhook_id": "we_stale", "missing_events": ["refund.succeeded"]},
                    {"connector_webhook_id": "we_unknown"}
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.webhooks[0].missing_events.as_deref(), Some(&[][..]));
        assert_eq!(
            parsed.webhooks[1].missing_events.as_deref(),
            Some(&["refund.succeeded".to_string()][..])
        );
        assert_eq!(parsed.webhooks[2].missing_events, None);
    }

    /// A per-endpoint failure must parse alongside the endpoints that
    /// succeeded — the sync never aborts on one bad endpoint, so the response
    /// carries both shapes at once.
    #[test]
    fn webhook_sync_parses_mixed_endpoint_outcomes() {
        let parsed: ConnectorWebhookSyncResponse = serde_json::from_str(
            r#"{
                "connector": "stripe",
                "expected_events": ["payment_intent.succeeded", "refund.succeeded"],
                "endpoints": [
                    {
                        "connector_webhook_id": "we_1",
                        "environment": "live",
                        "webhook_url": "https://api.delopay.net/webhooks/mer_1/mca_1",
                        "status": "enabled",
                        "updated": true,
                        "added_events": ["refund.succeeded"]
                    },
                    {
                        "connector_webhook_id": "we_2",
                        "updated": false,
                        "added_events": [],
                        "error_message": "endpoint is disabled at Stripe"
                    }
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.expected_events.len(), 2);
        assert!(parsed.endpoints[0].updated);
        assert_eq!(parsed.endpoints[0].added_events, ["refund.succeeded"]);
        assert_eq!(parsed.endpoints[0].error_message, None);
        assert!(!parsed.endpoints[1].updated);
        assert!(parsed.endpoints[1].added_events.is_empty());
        assert_eq!(
            parsed.endpoints[1].error_message.as_deref(),
            Some("endpoint is disabled at Stripe")
        );
    }

    /// A URL that failed to parse has no `domain`, and that must survive
    /// deserialization rather than fail the whole response.
    #[test]
    fn stripe_domain_registration_parses_per_url_outcomes() {
        let parsed: StripePaymentMethodDomainsRegisterResponse = serde_json::from_str(
            r#"{
                "environment": "live",
                "results": [
                    {
                        "url": "https://checkout.delopay.net",
                        "domain": "checkout.delopay.net",
                        "status": "registered",
                        "apple_pay_status": "active"
                    },
                    {"url": "not a url", "status": "invalid_url", "message": "could not parse host"}
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(parsed.environment.as_deref(), Some("live"));
        assert_eq!(
            parsed.results[0].domain.as_deref(),
            Some("checkout.delopay.net")
        );
        assert_eq!(
            parsed.results[0].apple_pay_status.as_deref(),
            Some("active")
        );
        assert_eq!(parsed.results[1].domain, None);
        assert_eq!(parsed.results[1].status.as_deref(), Some("invalid_url"));
    }
}