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
//! Merchant-defined checkout fields: the buyer-facing inputs the hosted
//! checkout renders, whose submitted values land in the payment's `metadata`
//! under each field's `key`.
//!
//! Persisted JSON-stringified under `sdk_ui_rules.branding.customFields` — the
//! same transport as trust badges — and surfaced on
//! [`CheckoutBranding::custom_fields`](crate::branding::CheckoutBranding::custom_fields).
//!
//! # Conditional visibility
//!
//! A field can be gated on facts the payment already carries when the checkout
//! renders: the intent's `metadata` (which a shop integration fills per
//! product/category), its `currency`, or its `amount`. That is what lets one
//! shop serve a licence-key order (no fields) and an account order (login
//! fields) without two shops.
//!
//! **Evaluation is authoritative on the backend**, which filters the field list
//! before it reaches the buyer's browser — so merchant metadata never leaves
//! the server and the rules cannot be tampered with client-side. This module is
//! the shared specification, behaviourally identical to the TypeScript SDK's
//! `branding` evaluator and the router's Rust mirror; use it to preview a rule
//! or to render a checkout of your own.

use std::collections::BTreeMap;

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

/// The input control a field renders as.
///
/// A plain enum with a `from_wire` that degrades to [`Text`](Self::Text): an
/// older consumer decoding a type it does not know renders a text input rather
/// than dropping the field, which is the long-standing behaviour.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CustomFieldType {
    #[default]
    Text,
    Textarea,
    Password,
    Email,
    Select,
    Checkbox,
}

impl CustomFieldType {
    /// The wire string.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::Text => "text",
            Self::Textarea => "textarea",
            Self::Password => "password",
            Self::Email => "email",
            Self::Select => "select",
            Self::Checkbox => "checkbox",
        }
    }

    /// Parse a stored wire value; anything unrecognised degrades to
    /// [`Text`](Self::Text).
    pub fn from_wire(raw: Option<&Value>) -> Self {
        match raw.and_then(Value::as_str) {
            Some("textarea") => Self::Textarea,
            Some("password") => Self::Password,
            Some("email") => Self::Email,
            Some("select") => Self::Select,
            Some("checkbox") => Self::Checkbox,
            _ => Self::Text,
        }
    }

    /// Whether the value is free text, so length bounds and a placeholder
    /// apply. `select` and `checkbox` are choice controls and have neither.
    pub fn is_text_like(self) -> bool {
        !matches!(self, Self::Select | Self::Checkbox)
    }
}

/// Every field type, in editor order.
pub const ALL_CUSTOM_FIELD_TYPES: &[CustomFieldType] = &[
    CustomFieldType::Text,
    CustomFieldType::Textarea,
    CustomFieldType::Password,
    CustomFieldType::Email,
    CustomFieldType::Select,
    CustomFieldType::Checkbox,
];

/// Maximum number of fields one shop may configure.
pub const CUSTOM_FIELDS_MAX: usize = 20;

/// Maximum number of conditions in one field's visibility rule.
pub const CUSTOM_FIELD_CONDITIONS_MAX: usize = 10;

/// The two values a checkbox field ever submits. Strings, because the whole
/// metadata bag is a string map on the wire.
pub const CHECKBOX_CHECKED: &str = "true";
/// See [`CHECKBOX_CHECKED`].
pub const CHECKBOX_UNCHECKED: &str = "false";

/// Whether a stored/submitted checkbox value counts as ticked.
///
/// Tolerant of case and padding, so a value round-tripped through a shop
/// integration (`"True"`, `" true "`) still reads correctly.
pub fn is_checkbox_checked(value: Option<&str>) -> bool {
    value.is_some_and(|v| v.trim().eq_ignore_ascii_case(CHECKBOX_CHECKED))
}

/// Metadata keys must start with a letter, then letters/digits/underscore/dash,
/// up to 40 characters — keeping keys safe for every downstream metadata
/// consumer (dashboards, exports, PSP forwarding).
///
/// Hand-written rather than a regex dependency; the grammar is
/// `^[A-Za-z][A-Za-z0-9_-]{0,39}$`.
pub fn is_valid_custom_field_key(key: &str) -> bool {
    let mut chars = key.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !first.is_ascii_alphabetic() {
        return false;
    }
    if key.len() > 40 {
        return false;
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

/// Per-locale overrides (`"de"`, `"de-AT"`). A missing locale falls back to the
/// default-language string on the field itself — see [`custom_field_text`].
pub type CustomFieldTranslations = BTreeMap<String, String>;

/// One choice of a `select` field.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CustomFieldOption {
    /// Submitted value.
    pub value: String,
    /// Default-language label. Falls back to `value` when empty.
    pub label: String,
    /// Per-locale overrides of `label`.
    pub label_translations: CustomFieldTranslations,
}

/// What fact of the payment a condition reads.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CustomFieldConditionSource {
    #[default]
    Metadata,
    Currency,
    Amount,
}

impl CustomFieldConditionSource {
    /// The wire string.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::Metadata => "metadata",
            Self::Currency => "currency",
            Self::Amount => "amount",
        }
    }

    /// Parse a stored wire value; anything unrecognised degrades to
    /// [`Metadata`](Self::Metadata).
    pub fn from_wire(raw: Option<&Value>) -> Self {
        match raw.and_then(Value::as_str) {
            Some("currency") => Self::Currency,
            Some("amount") => Self::Amount,
            _ => Self::Metadata,
        }
    }

    /// The operators that make sense for this source.
    ///
    /// Currency is a closed three-letter set, so substring and numeric
    /// operators would only ever confuse; amount is numeric, so string
    /// operators do not apply. Metadata is free-form and gets all of them.
    pub fn operators(self) -> &'static [CustomFieldOperator] {
        use CustomFieldOperator as Op;
        match self {
            Self::Metadata => ALL_CUSTOM_FIELD_OPERATORS,
            Self::Currency => &[Op::Equals, Op::NotEquals, Op::In, Op::NotIn],
            Self::Amount => &[Op::Equals, Op::NotEquals, Op::Gt, Op::Gte, Op::Lt, Op::Lte],
        }
    }

    /// The operator a condition falls back to when its source changes and the
    /// current operator is not valid for the new source.
    pub fn default_operator(self) -> CustomFieldOperator {
        self.operators()
            .first()
            .copied()
            .unwrap_or(CustomFieldOperator::Equals)
    }
}

/// Every condition source, in editor order.
pub const ALL_CUSTOM_FIELD_CONDITION_SOURCES: &[CustomFieldConditionSource] = &[
    CustomFieldConditionSource::Metadata,
    CustomFieldConditionSource::Currency,
    CustomFieldConditionSource::Amount,
];

/// How a condition compares its operands.
///
/// String operators apply to metadata and currency; the numeric ones
/// (`gt`…`lte`) apply to amount and to metadata values that parse as numbers.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CustomFieldOperator {
    #[default]
    Equals,
    NotEquals,
    Contains,
    NotContains,
    StartsWith,
    EndsWith,
    In,
    NotIn,
    Exists,
    NotExists,
    Gt,
    Gte,
    Lt,
    Lte,
}

impl CustomFieldOperator {
    /// The wire string.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::Equals => "equals",
            Self::NotEquals => "not_equals",
            Self::Contains => "contains",
            Self::NotContains => "not_contains",
            Self::StartsWith => "starts_with",
            Self::EndsWith => "ends_with",
            Self::In => "in",
            Self::NotIn => "not_in",
            Self::Exists => "exists",
            Self::NotExists => "not_exists",
            Self::Gt => "gt",
            Self::Gte => "gte",
            Self::Lt => "lt",
            Self::Lte => "lte",
        }
    }

    /// Parse a wire value, or `None` when it names no known operator.
    pub fn from_wire_str(raw: &str) -> Option<Self> {
        ALL_CUSTOM_FIELD_OPERATORS
            .iter()
            .copied()
            .find(|op| op.as_wire() == raw)
    }

    /// Whether the operator reads its right-hand operand. `exists` /
    /// `not_exists` ignore it, so an editor hides the value input and
    /// validation must not demand one.
    pub fn takes_value(self) -> bool {
        !matches!(self, Self::Exists | Self::NotExists)
    }
}

/// Every operator, in editor order.
pub const ALL_CUSTOM_FIELD_OPERATORS: &[CustomFieldOperator] = &[
    CustomFieldOperator::Equals,
    CustomFieldOperator::NotEquals,
    CustomFieldOperator::Contains,
    CustomFieldOperator::NotContains,
    CustomFieldOperator::StartsWith,
    CustomFieldOperator::EndsWith,
    CustomFieldOperator::In,
    CustomFieldOperator::NotIn,
    CustomFieldOperator::Exists,
    CustomFieldOperator::NotExists,
    CustomFieldOperator::Gt,
    CustomFieldOperator::Gte,
    CustomFieldOperator::Lt,
    CustomFieldOperator::Lte,
];

/// The operators that ignore their right-hand operand.
pub const CUSTOM_FIELD_VALUELESS_OPERATORS: &[CustomFieldOperator] =
    &[CustomFieldOperator::Exists, CustomFieldOperator::NotExists];

/// One clause of a field's visibility rule.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CustomFieldCondition {
    /// Stable identity for editor list operations (reorder/remove). Not part of
    /// the semantics.
    pub id: String,
    pub source: CustomFieldConditionSource,
    /// Metadata key to read. Ignored (and persisted empty) for
    /// currency/amount.
    pub key: String,
    pub operator: CustomFieldOperator,
    /// Right-hand operand. `in`/`not_in` read it as a comma-separated list;
    /// `exists`/`not_exists` ignore it; amount comparisons parse it as an
    /// integer in the currency's minor unit (`1000` = 10.00).
    pub value: String,
}

/// How multiple conditions combine.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CustomFieldMatch {
    #[default]
    All,
    Any,
}

impl CustomFieldMatch {
    /// The wire string.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Any => "any",
        }
    }

    /// Parse a stored wire value; anything unrecognised degrades to
    /// [`All`](Self::All).
    pub fn from_wire(raw: Option<&Value>) -> Self {
        match raw.and_then(Value::as_str) {
            Some("any") => Self::Any,
            _ => Self::All,
        }
    }
}

/// Whether a field is unconditional or gated on [`conditions`].
///
/// [`conditions`]: CustomFieldVisibility::conditions
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CustomFieldVisibilityMode {
    /// Unconditional — the default, and what every pre-feature field decodes
    /// to.
    #[default]
    Always,
    /// Evaluate the conditions.
    Match,
}

impl CustomFieldVisibilityMode {
    /// The wire string.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::Always => "always",
            Self::Match => "match",
        }
    }

    /// Parse a stored wire value; anything unrecognised degrades to
    /// [`Always`](Self::Always).
    pub fn from_wire(raw: Option<&Value>) -> Self {
        match raw.and_then(Value::as_str) {
            Some("match") => Self::Match,
            _ => Self::Always,
        }
    }
}

/// A field's conditional-display rule.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct CustomFieldVisibility {
    pub mode: CustomFieldVisibilityMode,
    #[serde(rename = "match")]
    pub match_: CustomFieldMatch,
    pub conditions: Vec<CustomFieldCondition>,
}

/// The rule an unconditional field carries.
pub fn default_custom_field_visibility() -> CustomFieldVisibility {
    CustomFieldVisibility::default()
}

/// One merchant-defined checkout field.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CheckoutCustomField {
    /// Stable identity for editor list operations (reorder/remove).
    pub id: String,
    /// Metadata key the submitted value is stored under. Unique per shop; must
    /// satisfy [`is_valid_custom_field_key`].
    pub key: String,
    #[serde(rename = "type")]
    pub field_type: CustomFieldType,
    /// Default-language copy; the `*_translations` maps override per locale.
    pub label: String,
    pub label_translations: CustomFieldTranslations,
    pub placeholder: String,
    pub placeholder_translations: CustomFieldTranslations,
    pub help_text: String,
    pub help_text_translations: CustomFieldTranslations,
    /// On a checkbox this means "must be ticked" — the terms-acceptance case.
    pub required: bool,
    /// Disabled fields stay configured but are neither rendered nor submitted.
    pub enabled: bool,
    /// Length bounds apply to the text-like types; `None` is unbounded.
    pub min_length: Option<i64>,
    /// See [`min_length`](Self::min_length).
    pub max_length: Option<i64>,
    /// Prefill for text-like fields; for a select, the option `value` selected
    /// initially (empty = the placeholder "choose" state); for a checkbox,
    /// exactly [`CHECKBOX_CHECKED`] or [`CHECKBOX_UNCHECKED`].
    pub default_value: String,
    /// Select choices; ignored for other types.
    pub options: Vec<CustomFieldOption>,
    /// Conditional display. Always populated by the decoder — a field with no
    /// persisted rule decodes to [`CustomFieldVisibilityMode::Always`].
    pub visibility: CustomFieldVisibility,
}

impl CheckoutCustomField {
    /// A fresh enabled text field for `key`, labelled by the key.
    pub fn new(key: impl Into<String>) -> Self {
        let key = key.into();
        Self {
            id: format!("field-{key}"),
            label: key.clone(),
            key,
            field_type: CustomFieldType::Text,
            enabled: true,
            ..Default::default()
        }
    }
}

// --- Codec ---------------------------------------------------------------

/// Keep only non-empty string values, matching the TypeScript
/// `parseTranslations`.
fn parse_translations(raw: Option<&Value>) -> CustomFieldTranslations {
    let mut out = CustomFieldTranslations::new();
    let Some(obj) = raw.and_then(Value::as_object) else {
        return out;
    };
    for (k, v) in obj {
        if let Some(s) = v.as_str()
            && !s.is_empty()
        {
            out.insert(k.clone(), s.to_string());
        }
    }
    out
}

/// A stored bound, clamped to `[0, 5000]`. Accepts the numeric-string form a
/// hand-edited blob may carry.
fn parse_bounded_int(raw: Option<&Value>) -> Option<i64> {
    let n = match raw {
        Some(Value::Number(n)) => n.as_f64()?,
        Some(Value::String(s)) => s.trim().parse::<f64>().ok()?,
        _ => return None,
    };
    if n.fract() != 0.0 || n < 0.0 {
        return None;
    }
    Some((n as i64).min(5000))
}

fn parse_bool(raw: Option<&Value>, default: bool) -> bool {
    raw.and_then(Value::as_bool).unwrap_or(default)
}

fn str_or_empty(obj: &Map<String, Value>, key: &str) -> String {
    obj.get(key)
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string()
}

/// Normalize one persisted condition.
///
/// Total: an unusable source/operator falls back rather than dropping the row,
/// so a rule authored by a newer control-center never silently becomes "always
/// visible" on an older decoder — it becomes a stricter, still-evaluable rule.
fn normalize_condition(raw: &Value, index: usize) -> Option<CustomFieldCondition> {
    let obj = raw.as_object()?;
    let source = CustomFieldConditionSource::from_wire(obj.get("source"));
    let allowed = source.operators();
    let operator = obj
        .get("operator")
        .and_then(Value::as_str)
        .and_then(CustomFieldOperator::from_wire_str)
        .filter(|op| allowed.contains(op))
        .unwrap_or_else(|| source.default_operator());

    let value = match obj.get("value") {
        Some(Value::String(s)) => s.clone(),
        Some(Value::Number(n)) => n.to_string(),
        Some(Value::Bool(b)) => b.to_string(),
        _ => String::new(),
    };

    Some(CustomFieldCondition {
        id: match obj.get("id").and_then(Value::as_str) {
            Some(id) if !id.is_empty() => id.to_string(),
            _ => format!("cond-{index}"),
        },
        source,
        // Only metadata conditions carry a key; drop anything else so the
        // encoded form stays canonical.
        key: match source {
            CustomFieldConditionSource::Metadata => obj
                .get("key")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .trim()
                .to_string(),
            _ => String::new(),
        },
        operator,
        value,
    })
}

fn normalize_visibility(raw: Option<&Value>) -> CustomFieldVisibility {
    let Some(obj) = raw.and_then(Value::as_object) else {
        return default_custom_field_visibility();
    };
    let conditions = obj
        .get("conditions")
        .and_then(Value::as_array)
        .map(|rows| {
            rows.iter()
                .take(CUSTOM_FIELD_CONDITIONS_MAX)
                .enumerate()
                .filter_map(|(i, row)| normalize_condition(row, i))
                .collect()
        })
        .unwrap_or_default();

    CustomFieldVisibility {
        mode: CustomFieldVisibilityMode::from_wire(obj.get("mode")),
        match_: CustomFieldMatch::from_wire(obj.get("match")),
        conditions,
    }
}

/// Normalize one persisted/imported field object.
///
/// Total: anything malformed falls back per property; returns `None` only when
/// there is no usable key.
fn normalize_custom_field(raw: &Value, index: usize) -> Option<CheckoutCustomField> {
    let obj = raw.as_object()?;
    let key = obj
        .get("key")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .trim()
        .to_string();
    if !is_valid_custom_field_key(&key) {
        return None;
    }

    let field_type = CustomFieldType::from_wire(obj.get("type"));

    let options = if field_type == CustomFieldType::Select {
        obj.get("options")
            .and_then(Value::as_array)
            .map(|rows| {
                rows.iter()
                    .filter_map(Value::as_object)
                    .map(|o| {
                        let value = o.get("value").and_then(Value::as_str).unwrap_or_default();
                        CustomFieldOption {
                            value: value.to_string(),
                            label: match o.get("label").and_then(Value::as_str) {
                                Some(l) if !l.is_empty() => l.to_string(),
                                _ => value.to_string(),
                            },
                            label_translations: parse_translations(o.get("labelTranslations")),
                        }
                    })
                    .filter(|o| !o.value.is_empty())
                    .collect()
            })
            .unwrap_or_default()
    } else {
        Vec::new()
    };

    // Length bounds are meaningless for choice controls; drop them at decode so
    // a field switched to checkbox/select cannot carry stale bounds that would
    // then be validated against `"true"` / `"false"`.
    let text_like = field_type.is_text_like();
    let min_length = text_like
        .then(|| parse_bounded_int(obj.get("minLength")))
        .flatten();
    let max_length = text_like
        .then(|| parse_bounded_int(obj.get("maxLength")))
        .flatten();

    // A checkbox default is a tick state, not free text: anything not truthy
    // normalizes to unchecked, so the control can never start in a third state.
    let raw_default = str_or_empty(obj, "defaultValue");
    let default_value = if field_type == CustomFieldType::Checkbox {
        if is_checkbox_checked(Some(&raw_default)) {
            CHECKBOX_CHECKED.to_string()
        } else {
            CHECKBOX_UNCHECKED.to_string()
        }
    } else {
        raw_default
    };

    Some(CheckoutCustomField {
        id: match obj.get("id").and_then(Value::as_str) {
            Some(id) if !id.is_empty() => id.to_string(),
            _ => format!("field-{index}"),
        },
        label: match obj.get("label").and_then(Value::as_str) {
            Some(l) if !l.is_empty() => l.to_string(),
            _ => key.clone(),
        },
        key,
        field_type,
        label_translations: parse_translations(obj.get("labelTranslations")),
        placeholder: str_or_empty(obj, "placeholder"),
        placeholder_translations: parse_translations(obj.get("placeholderTranslations")),
        help_text: str_or_empty(obj, "helpText"),
        help_text_translations: parse_translations(obj.get("helpTextTranslations")),
        required: parse_bool(obj.get("required"), false),
        enabled: parse_bool(obj.get("enabled"), true),
        min_length,
        // Guard inverted bounds at decode so consumers never see min > max.
        max_length: match (min_length, max_length) {
            (Some(min), Some(max)) if max < min => None,
            _ => max_length,
        },
        default_value,
        options,
        visibility: normalize_visibility(obj.get("visibility")),
    })
}

/// Parse an array of field objects (already JSON-parsed).
///
/// `None` when the input is not an array — callers fall back to "no custom
/// fields". Duplicate keys keep the first occurrence, and the list is capped at
/// [`CUSTOM_FIELDS_MAX`].
pub fn parse_custom_fields_loose(raw: &Value) -> Option<Vec<CheckoutCustomField>> {
    let rows = raw.as_array()?;
    let mut seen: Vec<String> = Vec::new();
    let mut out: Vec<CheckoutCustomField> = Vec::new();
    for (i, row) in rows.iter().enumerate() {
        if out.len() >= CUSTOM_FIELDS_MAX {
            break;
        }
        let Some(field) = normalize_custom_field(row, i) else {
            continue;
        };
        if seen.iter().any(|k| k == &field.key) {
            continue;
        }
        seen.push(field.key.clone());
        out.push(field);
    }
    Some(out)
}

/// Decode the JSON-encoded custom fields stored under
/// `sdk_ui_rules.branding.customFields`.
///
/// Tolerant like [`decode_badges`](crate::branding::decode_badges): a malformed
/// payload falls through to `None`.
pub fn decode_custom_fields(raw: Option<&str>) -> Option<Vec<CheckoutCustomField>> {
    let parsed: Value = serde_json::from_str(raw?).ok()?;
    parse_custom_fields_loose(&parsed)
}

fn non_empty_translations(map: &CustomFieldTranslations) -> Option<Map<String, Value>> {
    let kept: Map<String, Value> = map
        .iter()
        .filter(|(_, v)| !v.trim().is_empty())
        .map(|(k, v)| (k.clone(), Value::String(v.clone())))
        .collect();
    (!kept.is_empty()).then_some(kept)
}

fn encode_visibility(v: &CustomFieldVisibility) -> Value {
    let conditions: Vec<Value> = v
        .conditions
        .iter()
        .map(|c| {
            let mut row = Map::new();
            row.insert("id".into(), Value::String(c.id.clone()));
            row.insert("source".into(), Value::String(c.source.as_wire().into()));
            if c.source == CustomFieldConditionSource::Metadata && !c.key.is_empty() {
                row.insert("key".into(), Value::String(c.key.clone()));
            }
            row.insert(
                "operator".into(),
                Value::String(c.operator.as_wire().into()),
            );
            if c.operator.takes_value() && !c.value.is_empty() {
                row.insert("value".into(), Value::String(c.value.clone()));
            }
            Value::Object(row)
        })
        .collect();

    let mut out = Map::new();
    out.insert("mode".into(), Value::String(v.mode.as_wire().into()));
    out.insert("match".into(), Value::String(v.match_.as_wire().into()));
    out.insert("conditions".into(), Value::Array(conditions));
    Value::Object(out)
}

/// The JSON array a field list encodes to, before stringification.
///
/// Exposed for callers that want the structured form; the bag entry itself is
/// the string [`encode_custom_fields`] returns.
pub fn custom_fields_to_value(fields: &[CheckoutCustomField]) -> Value {
    let rows: Vec<Value> = fields
        .iter()
        .map(|f| {
            let mut row = Map::new();
            row.insert("id".into(), Value::String(f.id.clone()));
            row.insert("key".into(), Value::String(f.key.clone()));
            row.insert("type".into(), Value::String(f.field_type.as_wire().into()));
            row.insert("label".into(), Value::String(f.label.clone()));
            if let Some(m) = non_empty_translations(&f.label_translations) {
                row.insert("labelTranslations".into(), Value::Object(m));
            }
            if !f.placeholder.is_empty() {
                row.insert("placeholder".into(), Value::String(f.placeholder.clone()));
            }
            if let Some(m) = non_empty_translations(&f.placeholder_translations) {
                row.insert("placeholderTranslations".into(), Value::Object(m));
            }
            if !f.help_text.is_empty() {
                row.insert("helpText".into(), Value::String(f.help_text.clone()));
            }
            if let Some(m) = non_empty_translations(&f.help_text_translations) {
                row.insert("helpTextTranslations".into(), Value::Object(m));
            }
            if f.required {
                row.insert("required".into(), Value::Bool(true));
            }
            if !f.enabled {
                row.insert("enabled".into(), Value::Bool(false));
            }
            // Length bounds only exist for free-text types; a choice control
            // that still carries them is stale state the decoder would drop.
            if f.field_type.is_text_like() {
                if let Some(min) = f.min_length {
                    row.insert("minLength".into(), Value::from(min));
                }
                if let Some(max) = f.max_length {
                    row.insert("maxLength".into(), Value::from(max));
                }
            }
            // A checkbox persists only "starts ticked"; unticked is the
            // decoder's default, so writing `"false"` would be noise on every
            // such field.
            if f.field_type == CustomFieldType::Checkbox {
                if is_checkbox_checked(Some(&f.default_value)) {
                    row.insert(
                        "defaultValue".into(),
                        Value::String(CHECKBOX_CHECKED.into()),
                    );
                }
            } else if !f.default_value.is_empty() {
                row.insert(
                    "defaultValue".into(),
                    Value::String(f.default_value.clone()),
                );
            }
            if f.field_type == CustomFieldType::Select {
                let options: Vec<Value> = f
                    .options
                    .iter()
                    .map(|o| {
                        let mut row = Map::new();
                        row.insert("value".into(), Value::String(o.value.clone()));
                        row.insert("label".into(), Value::String(o.label.clone()));
                        row.insert(
                            "labelTranslations".into(),
                            Value::Object(
                                o.label_translations
                                    .iter()
                                    .map(|(k, v)| (k.clone(), Value::String(v.clone())))
                                    .collect(),
                            ),
                        );
                        Value::Object(row)
                    })
                    .collect();
                row.insert("options".into(), Value::Array(options));
            }
            // Omitted for unconditional fields so the stored blob (and every
            // pre-feature payload) stays byte-identical to what it was.
            if f.visibility.mode == CustomFieldVisibilityMode::Match {
                row.insert("visibility".into(), encode_visibility(&f.visibility));
            }
            Value::Object(row)
        })
        .collect();
    Value::Array(rows)
}

/// JSON-stringify custom fields for the `sdk_ui_rules.branding.customFields`
/// bag entry.
pub fn encode_custom_fields(fields: &[CheckoutCustomField]) -> String {
    serde_json::to_string(&custom_fields_to_value(fields)).unwrap_or_else(|_| "[]".to_string())
}

// --- Evaluator -----------------------------------------------------------

/// The facts a rule can read.
///
/// `amount` is in the currency's minor unit (what the payment intent stores);
/// `metadata` values are already flattened to strings by
/// [`custom_field_context_from_metadata`].
#[derive(Debug, Clone, Default)]
pub struct CustomFieldContext {
    pub amount: i64,
    pub currency: String,
    pub metadata: BTreeMap<String, String>,
}

/// Flatten a payment's raw `metadata` object into the string map a rule
/// compares against.
///
/// Arrays join on `,` so a list-shaped value stays usable with `contains` /
/// `in`; objects fall back to their JSON form; `null` drops the key entirely.
pub fn custom_field_context_from_metadata(raw: &Value) -> BTreeMap<String, String> {
    let mut out = BTreeMap::new();
    let Some(obj) = raw.as_object() else {
        return out;
    };
    for (key, value) in obj {
        if let Some(flat) = flatten_metadata_value(value) {
            out.insert(key.clone(), flat);
        }
    }
    out
}

fn flatten_metadata_value(value: &Value) -> Option<String> {
    match value {
        Value::String(s) => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        Value::Bool(b) => Some(b.to_string()),
        Value::Null => None,
        Value::Array(items) => Some(
            items
                .iter()
                .filter_map(flatten_metadata_value)
                .collect::<Vec<_>>()
                .join(","),
        ),
        Value::Object(_) => serde_json::to_string(value).ok(),
    }
}

/// Case- and whitespace-insensitive comparison key.
///
/// Merchants type `Windows` in the builder and the shop sends `windows`;
/// exact-case matching would be a support-ticket generator.
fn norm(value: &str) -> String {
    value.trim().to_lowercase()
}

/// Parse an operand as a number using Rust's decimal-float grammar.
///
/// Deliberately narrower than a permissive parse: `f64::from_str` rejects
/// radix-prefixed literals (`0x10`) and this must agree with the backend, or a
/// merchant would see one rule in the builder and buyers would get another.
/// `inf`/`nan` are excluded too.
fn numeric(value: &str) -> Option<f64> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return None;
    }
    // `f64::from_str` accepts "inf"/"NaN"; the finiteness check drops them.
    let n: f64 = trimmed.parse().ok()?;
    n.is_finite().then_some(n)
}

fn split_list(value: &str) -> Vec<String> {
    value
        .split(',')
        .map(norm)
        .filter(|part| !part.is_empty())
        .collect()
}

/// Resolve the left-hand operand. `None` means "the metadata key is absent" —
/// which only `exists`/`not_exists` distinguish from empty.
fn operand_for(condition: &CustomFieldCondition, ctx: &CustomFieldContext) -> Option<String> {
    match condition.source {
        CustomFieldConditionSource::Currency => Some(ctx.currency.clone()),
        CustomFieldConditionSource::Amount => Some(ctx.amount.to_string()),
        CustomFieldConditionSource::Metadata => ctx.metadata.get(&condition.key).cloned(),
    }
}

/// Evaluate one condition against a payment.
pub fn evaluate_custom_field_condition(
    condition: &CustomFieldCondition,
    ctx: &CustomFieldContext,
) -> bool {
    use CustomFieldOperator as Op;

    let raw = operand_for(condition, ctx);
    let actual = raw.clone().unwrap_or_default();
    let expected = &condition.value;

    match condition.operator {
        Op::Exists => raw.is_some_and(|v| !v.trim().is_empty()),
        Op::NotExists => raw.is_none_or(|v| v.trim().is_empty()),
        Op::Equals => norm(&actual) == norm(expected),
        Op::NotEquals => norm(&actual) != norm(expected),
        Op::Contains => norm(&actual).contains(&norm(expected)),
        Op::NotContains => !norm(&actual).contains(&norm(expected)),
        Op::StartsWith => norm(&actual).starts_with(&norm(expected)),
        Op::EndsWith => norm(&actual).ends_with(&norm(expected)),
        Op::In => split_list(expected).contains(&norm(&actual)),
        Op::NotIn => !split_list(expected).contains(&norm(&actual)),
        Op::Gt | Op::Gte | Op::Lt | Op::Lte => {
            // Both sides must be numbers. A non-numeric metadata value never
            // matches a numeric comparison, rather than coercing to 0.
            let (Some(a), Some(b)) = (numeric(&actual), numeric(expected)) else {
                return false;
            };
            match condition.operator {
                Op::Gt => a > b,
                Op::Gte => a >= b,
                Op::Lt => a < b,
                _ => a <= b,
            }
        }
    }
}

/// Whether a field's rule matches the payment.
///
/// Fail-open in two spots, deliberately: [`Always`] and a `match` rule with no
/// conditions both resolve to visible. A half-authored rule should never
/// silently swallow a field the merchant needs collected — the control-center
/// flags the empty rule as a validation issue instead.
///
/// [`Always`]: CustomFieldVisibilityMode::Always
pub fn evaluate_custom_field_visibility(
    field: &CheckoutCustomField,
    ctx: &CustomFieldContext,
) -> bool {
    let v = &field.visibility;
    if v.mode != CustomFieldVisibilityMode::Match || v.conditions.is_empty() {
        return true;
    }
    match v.match_ {
        CustomFieldMatch::Any => v
            .conditions
            .iter()
            .any(|c| evaluate_custom_field_condition(c, ctx)),
        CustomFieldMatch::All => v
            .conditions
            .iter()
            .all(|c| evaluate_custom_field_condition(c, ctx)),
    }
}

/// Filter a field list to what the buyer should see for this payment.
///
/// Disabled fields are dropped here too — the two reasons a field does not
/// render are the same to every consumer.
pub fn visible_custom_fields<'a>(
    fields: &'a [CheckoutCustomField],
    ctx: &CustomFieldContext,
) -> Vec<&'a CheckoutCustomField> {
    fields
        .iter()
        .filter(|f| f.enabled && evaluate_custom_field_visibility(f, ctx))
        .collect()
}

// --- Locale resolution ---------------------------------------------------

/// Exact-locale-then-base-language lookup.
fn translation_for(map: &CustomFieldTranslations, locale: Option<&str>) -> Option<String> {
    let locale = locale?;
    let own = |k: &str| map.get(k).filter(|v| !v.is_empty()).cloned();
    if let Some(exact) = own(locale) {
        return Some(exact);
    }
    let base = locale.split('-').next().unwrap_or_default();
    (!base.is_empty() && base != locale).then(|| own(base))?
}

/// Which piece of a field's copy to resolve.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CustomFieldTextPart {
    Label,
    Placeholder,
    HelpText,
}

/// Resolve the display string for a field part in a buyer locale.
///
/// Exact locale wins (`de-AT`), then its base language (`de`), then the field's
/// default-language string; a label finally falls back to the key so a field is
/// never rendered nameless.
pub fn custom_field_text(
    field: &CheckoutCustomField,
    part: CustomFieldTextPart,
    locale: Option<&str>,
) -> String {
    let (map, fallback) = match part {
        CustomFieldTextPart::Label => (&field.label_translations, &field.label),
        CustomFieldTextPart::Placeholder => (&field.placeholder_translations, &field.placeholder),
        CustomFieldTextPart::HelpText => (&field.help_text_translations, &field.help_text),
    };
    if let Some(translated) = translation_for(map, locale) {
        return translated;
    }
    if !fallback.is_empty() {
        return fallback.clone();
    }
    match part {
        CustomFieldTextPart::Label => field.key.clone(),
        _ => String::new(),
    }
}

/// Resolve a select option's label in a buyer locale, falling back to the
/// default-language label and then to the option's own value.
pub fn custom_field_option_label(option: &CustomFieldOption, locale: Option<&str>) -> String {
    translation_for(&option.label_translations, locale).unwrap_or_else(|| {
        if option.label.is_empty() {
            option.value.clone()
        } else {
            option.label.clone()
        }
    })
}

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

    fn ctx(amount: i64, currency: &str, metadata: &[(&str, &str)]) -> CustomFieldContext {
        CustomFieldContext {
            amount,
            currency: currency.to_string(),
            metadata: metadata
                .iter()
                .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
                .collect(),
        }
    }

    fn condition(source: &str, key: &str, operator: &str, value: &str) -> CustomFieldCondition {
        CustomFieldCondition {
            id: "c1".into(),
            source: CustomFieldConditionSource::from_wire(Some(&json!(source))),
            key: key.into(),
            operator: CustomFieldOperator::from_wire_str(operator).unwrap(),
            value: value.into(),
        }
    }

    // --- key validation ---------------------------------------------------

    #[test]
    fn key_grammar_matches_the_documented_pattern() {
        assert!(is_valid_custom_field_key("account_login"));
        assert!(is_valid_custom_field_key("A"));
        assert!(is_valid_custom_field_key("a-b_9"));
        assert!(!is_valid_custom_field_key(""), "empty");
        assert!(
            !is_valid_custom_field_key("9lives"),
            "must start with a letter"
        );
        assert!(!is_valid_custom_field_key("_x"), "must start with a letter");
        assert!(!is_valid_custom_field_key("has space"));
        assert!(!is_valid_custom_field_key(&"a".repeat(41)), "40 chars max");
        assert!(is_valid_custom_field_key(&"a".repeat(40)));
    }

    // --- decode -----------------------------------------------------------

    #[test]
    fn decode_drops_rows_without_a_usable_key_and_dedupes() {
        let decoded = parse_custom_fields_loose(&json!([
            {"key": "login"},
            {"key": "login", "label": "Duplicate"},
            {"key": "9bad"},
            {"no": "key"},
            {"key": "password"}
        ]))
        .unwrap();

        let keys: Vec<&str> = decoded.iter().map(|f| f.key.as_str()).collect();
        assert_eq!(keys, ["login", "password"]);
    }

    #[test]
    fn decode_defaults_label_to_the_key_and_enables_by_default() {
        let decoded = parse_custom_fields_loose(&json!([{"key": "login"}])).unwrap();
        assert_eq!(decoded[0].label, "login");
        assert!(decoded[0].enabled);
        assert!(!decoded[0].required);
        assert_eq!(decoded[0].field_type, CustomFieldType::Text);
        assert_eq!(
            decoded[0].visibility.mode,
            CustomFieldVisibilityMode::Always
        );
    }

    /// An unknown type must render as a text input, not delete the field —
    /// long-standing behaviour that lets a newer control-center ship a type
    /// before every consumer knows it.
    #[test]
    fn decode_degrades_an_unknown_type_to_text() {
        let decoded = parse_custom_fields_loose(&json!([{"key": "x", "type": "colour"}])).unwrap();
        assert_eq!(decoded[0].field_type, CustomFieldType::Text);
    }

    /// Bounds on a choice control would be validated against `"true"` /
    /// `"false"`, so they are dropped at decode.
    #[test]
    fn decode_drops_length_bounds_from_choice_controls() {
        let decoded = parse_custom_fields_loose(&json!([
            {"key": "terms", "type": "checkbox", "minLength": 2, "maxLength": 10},
            {"key": "plan", "type": "select", "minLength": 2, "options": [{"value": "pro"}]},
            {"key": "note", "type": "text", "minLength": 2, "maxLength": 10}
        ]))
        .unwrap();
        assert_eq!(decoded[0].min_length, None);
        assert_eq!(decoded[1].min_length, None);
        assert_eq!(decoded[2].min_length, Some(2));
        assert_eq!(decoded[2].max_length, Some(10));
    }

    /// A consumer must never see `min > max`.
    #[test]
    fn decode_drops_an_inverted_max_bound() {
        let decoded =
            parse_custom_fields_loose(&json!([{"key": "x", "minLength": 10, "maxLength": 2}]))
                .unwrap();
        assert_eq!(decoded[0].min_length, Some(10));
        assert_eq!(decoded[0].max_length, None);
    }

    /// The checkbox default is a tick state; a third state would make
    /// "declined" indistinguishable from "never asked" in the metadata.
    #[test]
    fn decode_normalizes_a_checkbox_default_to_one_of_two_states() {
        let decoded = parse_custom_fields_loose(&json!([
            {"key": "a", "type": "checkbox", "defaultValue": " True "},
            {"key": "b", "type": "checkbox", "defaultValue": "whatever"},
            {"key": "c", "type": "checkbox"}
        ]))
        .unwrap();
        assert_eq!(decoded[0].default_value, CHECKBOX_CHECKED);
        assert_eq!(decoded[1].default_value, CHECKBOX_UNCHECKED);
        assert_eq!(decoded[2].default_value, CHECKBOX_UNCHECKED);
    }

    #[test]
    fn decode_keeps_select_options_and_drops_valueless_ones() {
        let decoded = parse_custom_fields_loose(&json!([{
            "key": "plan",
            "type": "select",
            "options": [
                {"value": "pro", "label": "Pro", "labelTranslations": {"de": "Profi", "fr": ""}},
                {"value": "", "label": "ignored"},
                {"value": "basic"}
            ]
        }]))
        .unwrap();
        let options = &decoded[0].options;
        assert_eq!(options.len(), 2);
        assert_eq!(options[0].label_translations.get("de").unwrap(), "Profi");
        assert!(!options[0].label_translations.contains_key("fr"));
        // A missing label falls back to the value, so no option renders blank.
        assert_eq!(options[1].label, "basic");
    }

    /// A rule authored by a newer control-center must degrade to a stricter,
    /// still-evaluable rule — never to "always visible".
    #[test]
    fn decode_falls_back_an_operator_the_source_does_not_allow() {
        let decoded = parse_custom_fields_loose(&json!([{
            "key": "x",
            "visibility": {
                "mode": "match",
                "match": "any",
                "conditions": [{"source": "amount", "operator": "contains", "value": "5"}]
            }
        }]))
        .unwrap();
        let c = &decoded[0].visibility.conditions[0];
        assert_eq!(c.source, CustomFieldConditionSource::Amount);
        assert_eq!(c.operator, CustomFieldOperator::Equals);
        assert_eq!(decoded[0].visibility.mode, CustomFieldVisibilityMode::Match);
    }

    /// Only metadata conditions carry a key, so the encoded form stays
    /// canonical whatever a hand-edited blob contained.
    #[test]
    fn decode_drops_a_key_from_a_non_metadata_condition() {
        let decoded = parse_custom_fields_loose(&json!([{
            "key": "x",
            "visibility": {"mode": "match", "conditions": [
                {"source": "currency", "key": "stale", "operator": "equals", "value": "EUR"}
            ]}
        }]))
        .unwrap();
        assert_eq!(decoded[0].visibility.conditions[0].key, "");
    }

    #[test]
    fn decode_caps_conditions_and_fields() {
        let conditions: Vec<Value> = (0..25)
            .map(|i| json!({"source": "metadata", "key": format!("k{i}"), "operator": "exists"}))
            .collect();
        let fields: Vec<Value> = (0..30)
            .map(|i| json!({"key": format!("field{i}"), "visibility": {"mode": "match", "conditions": conditions}}))
            .collect();
        let decoded = parse_custom_fields_loose(&Value::Array(fields)).unwrap();
        assert_eq!(decoded.len(), CUSTOM_FIELDS_MAX);
        assert_eq!(
            decoded[0].visibility.conditions.len(),
            CUSTOM_FIELD_CONDITIONS_MAX
        );
    }

    #[test]
    fn decode_custom_fields_tolerates_malformed_json() {
        assert!(decode_custom_fields(None).is_none());
        assert!(decode_custom_fields(Some("not json")).is_none());
        assert!(decode_custom_fields(Some("{}")).is_none());
        assert_eq!(decode_custom_fields(Some("[]")).unwrap().len(), 0);
    }

    // --- encode -----------------------------------------------------------

    /// A field with no rule must encode byte-identically to a pre-feature
    /// payload, or upgrading the SDK rewrites every merchant's stored blob.
    #[test]
    fn encode_omits_visibility_for_an_unconditional_field() {
        let field = CheckoutCustomField::new("login");
        let encoded = encode_custom_fields(std::slice::from_ref(&field));
        assert!(!encoded.contains("visibility"), "{encoded}");
        assert!(!encoded.contains("required"), "{encoded}");
        assert!(!encoded.contains("enabled"), "{encoded}");
    }

    #[test]
    fn encode_round_trips_a_conditional_field() {
        let mut field = CheckoutCustomField::new("login");
        field.field_type = CustomFieldType::Email;
        field.required = true;
        field.min_length = Some(3);
        field.max_length = Some(64);
        field
            .label_translations
            .insert("de".into(), "Anmeldung".into());
        field.visibility = CustomFieldVisibility {
            mode: CustomFieldVisibilityMode::Match,
            match_: CustomFieldMatch::Any,
            conditions: vec![
                condition("metadata", "product", "equals", "spotify"),
                condition("amount", "", "gte", "1000"),
            ],
        };

        let round_tripped =
            decode_custom_fields(Some(&encode_custom_fields(std::slice::from_ref(&field))))
                .unwrap();
        assert_eq!(round_tripped[0], field);
    }

    /// Writing `defaultValue: "false"` on every unticked checkbox would be
    /// noise the decoder produces anyway.
    #[test]
    fn encode_persists_only_a_ticked_checkbox_default() {
        let mut ticked = CheckoutCustomField::new("terms");
        ticked.field_type = CustomFieldType::Checkbox;
        ticked.default_value = CHECKBOX_CHECKED.into();
        let mut unticked = CheckoutCustomField::new("news");
        unticked.field_type = CustomFieldType::Checkbox;
        unticked.default_value = CHECKBOX_UNCHECKED.into();

        let encoded: Value =
            serde_json::from_str(&encode_custom_fields(&[ticked, unticked])).unwrap();
        assert_eq!(encoded[0]["defaultValue"], CHECKBOX_CHECKED);
        assert!(encoded[1].get("defaultValue").is_none(), "{encoded}");
    }

    /// The value input is hidden for `exists`, so persisting a stale operand
    /// would resurface it the next time the source or operator changes.
    #[test]
    fn encode_drops_the_operand_of_a_valueless_operator() {
        let mut field = CheckoutCustomField::new("x");
        field.visibility = CustomFieldVisibility {
            mode: CustomFieldVisibilityMode::Match,
            match_: CustomFieldMatch::All,
            conditions: vec![CustomFieldCondition {
                value: "stale".into(),
                ..condition("metadata", "product", "exists", "stale")
            }],
        };
        let encoded: Value =
            serde_json::from_str(&encode_custom_fields(std::slice::from_ref(&field))).unwrap();
        let cond = &encoded[0]["visibility"]["conditions"][0];
        assert_eq!(cond["operator"], "exists");
        assert!(cond.get("value").is_none(), "{cond}");
    }

    // --- evaluator --------------------------------------------------------

    #[test]
    fn string_operators_are_case_and_whitespace_insensitive() {
        let c = ctx(1000, "EUR", &[("product", " Windows ")]);
        assert!(evaluate_custom_field_condition(
            &condition("metadata", "product", "equals", "windows"),
            &c
        ));
        assert!(evaluate_custom_field_condition(
            &condition("metadata", "product", "contains", "WIND"),
            &c
        ));
        assert!(evaluate_custom_field_condition(
            &condition("metadata", "product", "starts_with", "win"),
            &c
        ));
        assert!(evaluate_custom_field_condition(
            &condition("metadata", "product", "ends_with", "OWS"),
            &c
        ));
        assert!(!evaluate_custom_field_condition(
            &condition("metadata", "product", "not_contains", "wind"),
            &c
        ));
    }

    #[test]
    fn list_operators_split_on_commas() {
        let c = ctx(1000, "EUR", &[("plan", "pro")]);
        assert!(evaluate_custom_field_condition(
            &condition("metadata", "plan", "in", "basic, PRO ,team"),
            &c
        ));
        assert!(evaluate_custom_field_condition(
            &condition("metadata", "plan", "not_in", "basic,team"),
            &c
        ));
    }

    /// `exists` is the only operator that separates "absent" from "blank" —
    /// and a present-but-blank value counts as missing.
    #[test]
    fn exists_treats_a_blank_value_as_missing() {
        let c = ctx(1000, "EUR", &[("blank", "   "), ("set", "x")]);
        assert!(evaluate_custom_field_condition(
            &condition("metadata", "set", "exists", ""),
            &c
        ));
        assert!(!evaluate_custom_field_condition(
            &condition("metadata", "blank", "exists", ""),
            &c
        ));
        assert!(evaluate_custom_field_condition(
            &condition("metadata", "absent", "not_exists", ""),
            &c
        ));
    }

    /// A missing metadata key reads as `""` for value operators, so `equals ""`
    /// matches it — the documented behaviour the backend mirrors.
    #[test]
    fn a_missing_metadata_key_reads_as_empty_for_value_operators() {
        let c = ctx(1000, "EUR", &[]);
        assert!(evaluate_custom_field_condition(
            &condition("metadata", "absent", "equals", ""),
            &c
        ));
        assert!(!evaluate_custom_field_condition(
            &condition("metadata", "absent", "equals", "x"),
            &c
        ));
    }

    #[test]
    fn numeric_operators_compare_the_amount() {
        let c = ctx(2500, "EUR", &[]);
        assert!(evaluate_custom_field_condition(
            &condition("amount", "", "gte", "2500"),
            &c
        ));
        assert!(evaluate_custom_field_condition(
            &condition("amount", "", "lt", "2501"),
            &c
        ));
        assert!(!evaluate_custom_field_condition(
            &condition("amount", "", "gt", "2500"),
            &c
        ));
    }

    /// A non-numeric operand must never coerce to zero — that would make
    /// `gte 0` match every junk value.
    #[test]
    fn numeric_operators_refuse_a_non_numeric_operand() {
        let c = ctx(1000, "EUR", &[("qty", "many")]);
        assert!(!evaluate_custom_field_condition(
            &condition("metadata", "qty", "gte", "0"),
            &c
        ));
        assert!(!evaluate_custom_field_condition(
            &condition("metadata", "qty", "lt", "notanumber"),
            &c
        ));
    }

    /// `0x10` parses as 16 in JavaScript's `Number()` but is rejected by
    /// `f64::from_str`. Both sides must agree, or the merchant sees one rule
    /// and buyers get another.
    #[test]
    fn numeric_operators_reject_radix_literals_and_infinities() {
        let c = ctx(1000, "EUR", &[("hex", "0x10"), ("inf", "inf")]);
        assert!(!evaluate_custom_field_condition(
            &condition("metadata", "hex", "gte", "5"),
            &c
        ));
        assert!(!evaluate_custom_field_condition(
            &condition("metadata", "inf", "gt", "5"),
            &c
        ));
    }

    #[test]
    fn visibility_fails_open_for_always_and_for_an_empty_match_rule() {
        let c = ctx(1000, "EUR", &[]);
        let always = CheckoutCustomField::new("a");
        assert!(evaluate_custom_field_visibility(&always, &c));

        let mut empty_rule = CheckoutCustomField::new("b");
        empty_rule.visibility.mode = CustomFieldVisibilityMode::Match;
        assert!(
            evaluate_custom_field_visibility(&empty_rule, &c),
            "a half-authored rule must not swallow the field"
        );
    }

    #[test]
    fn visibility_combines_conditions_with_all_and_any() {
        let c = ctx(5000, "EUR", &[("product", "spotify")]);
        let mut field = CheckoutCustomField::new("login");
        field.visibility.mode = CustomFieldVisibilityMode::Match;
        field.visibility.conditions = vec![
            condition("metadata", "product", "equals", "spotify"),
            condition("amount", "", "gt", "9000"),
        ];

        field.visibility.match_ = CustomFieldMatch::All;
        assert!(!evaluate_custom_field_visibility(&field, &c));
        field.visibility.match_ = CustomFieldMatch::Any;
        assert!(evaluate_custom_field_visibility(&field, &c));
    }

    #[test]
    fn visible_custom_fields_drops_disabled_and_non_matching_fields() {
        let c = ctx(1000, "EUR", &[("product", "windows")]);
        let shown = CheckoutCustomField::new("shown");
        let mut disabled = CheckoutCustomField::new("disabled");
        disabled.enabled = false;
        let mut hidden = CheckoutCustomField::new("hidden");
        hidden.visibility.mode = CustomFieldVisibilityMode::Match;
        hidden.visibility.conditions = vec![condition("metadata", "product", "equals", "spotify")];

        let fields = vec![shown, disabled, hidden];
        let visible = visible_custom_fields(&fields, &c);
        assert_eq!(visible.len(), 1);
        assert_eq!(visible[0].key, "shown");
    }

    // --- metadata flattening ----------------------------------------------

    #[test]
    fn metadata_flattening_joins_arrays_and_drops_nulls() {
        let flat = custom_field_context_from_metadata(&json!({
            "s": "text",
            "n": 42,
            "b": true,
            "list": ["a", 1, null, "b"],
            "obj": {"k": "v"},
            "nothing": null
        }));
        assert_eq!(flat.get("s").unwrap(), "text");
        assert_eq!(flat.get("n").unwrap(), "42");
        assert_eq!(flat.get("b").unwrap(), "true");
        // Joined so a list-shaped value stays usable with `contains` / `in`.
        assert_eq!(flat.get("list").unwrap(), "a,1,b");
        assert_eq!(flat.get("obj").unwrap(), r#"{"k":"v"}"#);
        assert!(!flat.contains_key("nothing"));
    }

    #[test]
    fn metadata_flattening_ignores_a_non_object() {
        assert!(custom_field_context_from_metadata(&json!("nope")).is_empty());
        assert!(custom_field_context_from_metadata(&json!([1, 2])).is_empty());
    }

    // --- locale resolution ------------------------------------------------

    #[test]
    fn text_resolves_exact_locale_then_base_then_default_then_key() {
        let mut field = CheckoutCustomField::new("login");
        field.label = "Login".into();
        field.label_translations.insert("de".into(), "Konto".into());
        field
            .label_translations
            .insert("de-AT".into(), "Zugang".into());

        fn label(field: &CheckoutCustomField, locale: Option<&str>) -> String {
            custom_field_text(field, CustomFieldTextPart::Label, locale)
        }
        assert_eq!(label(&field, Some("de-AT")), "Zugang");
        assert_eq!(
            label(&field, Some("de-CH")),
            "Konto",
            "falls back to the base language"
        );
        assert_eq!(label(&field, Some("fr")), "Login");
        assert_eq!(label(&field, None), "Login");

        // A field is never rendered nameless.
        field.label = String::new();
        field.label_translations.clear();
        assert_eq!(label(&field, Some("fr")), "login");
        // Non-label parts resolve to empty rather than to the key.
        assert_eq!(
            custom_field_text(&field, CustomFieldTextPart::Placeholder, Some("fr")),
            ""
        );
    }

    #[test]
    fn option_label_falls_back_to_the_label_then_the_value() {
        let mut option = CustomFieldOption {
            value: "pro".into(),
            label: "Pro".into(),
            label_translations: CustomFieldTranslations::new(),
        };
        option
            .label_translations
            .insert("de".into(), "Profi".into());
        assert_eq!(custom_field_option_label(&option, Some("de-AT")), "Profi");
        assert_eq!(custom_field_option_label(&option, Some("fr")), "Pro");
        option.label = String::new();
        assert_eq!(custom_field_option_label(&option, None), "pro");
    }

    // --- vocabulary -------------------------------------------------------

    #[test]
    fn operators_by_source_stay_narrower_than_the_full_set() {
        assert_eq!(
            CustomFieldConditionSource::Metadata.operators().len(),
            ALL_CUSTOM_FIELD_OPERATORS.len()
        );
        assert_eq!(
            CustomFieldConditionSource::Currency.default_operator(),
            CustomFieldOperator::Equals
        );
        assert!(
            !CustomFieldConditionSource::Currency
                .operators()
                .contains(&CustomFieldOperator::Contains),
            "a 3-letter closed set has no use for substring matching"
        );
        assert!(
            !CustomFieldConditionSource::Amount
                .operators()
                .contains(&CustomFieldOperator::StartsWith)
        );
        for op in CUSTOM_FIELD_VALUELESS_OPERATORS {
            assert!(!op.takes_value());
        }
        assert!(CustomFieldOperator::Equals.takes_value());
    }

    #[test]
    fn type_helpers_agree_on_which_types_are_text_like() {
        for t in ALL_CUSTOM_FIELD_TYPES {
            let expected = !matches!(t, CustomFieldType::Select | CustomFieldType::Checkbox);
            assert_eq!(t.is_text_like(), expected, "{}", t.as_wire());
            // Every type must survive a wire round-trip, or the decoder
            // silently rewrites a merchant's choice to `text`.
            assert_eq!(
                CustomFieldType::from_wire(Some(&json!(t.as_wire()))),
                *t,
                "{}",
                t.as_wire()
            );
        }
    }

    #[test]
    fn checkbox_checked_is_tolerant_of_case_and_padding() {
        assert!(is_checkbox_checked(Some("true")));
        assert!(is_checkbox_checked(Some(" True ")));
        assert!(!is_checkbox_checked(Some("false")));
        assert!(!is_checkbox_checked(Some("")));
        assert!(!is_checkbox_checked(None));
    }
}