delopay 0.3.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
//! Fee-rule programs: typed Euclid wire types plus a fluent builder.
//!
//! A merchant's fee can be a Euclid *program* that conditions on payment
//! method, connector, amount, currency, card network, billing country and the
//! merchant's previous-month volume. Rules are evaluated in order; the first
//! match wins, otherwise the default selection applies.
//!
//! The types here mirror the backend wire format exactly, including its
//! deliberate casing split (the SDK is otherwise snake_case): the Euclid tree
//! ([`PlatformFeeProgram`], [`PlatformFeeRule`], [`EuclidIfStatement`],
//! [`EuclidComparison`]) serializes **camelCase**, while [`PlatformFeeOutput`]
//! is **snake_case**. Prefer [`fee_program()`] over hand-writing the AST.
//!
//! ```
//! use delopay::resources::fee_program::{
//!     FeeRuleConditions, FeeRuleInput, FeeSpecInput, fee_program,
//! };
//!
//! # fn main() -> delopay::Result<()> {
//! let algorithm = fee_program()
//!     .rule(
//!         FeeRuleInput::new("crypto", FeeSpecInput::new().percentage(1.0))
//!             .when(FeeRuleConditions::new().payment_method("crypto")),
//!     )
//!     .otherwise(FeeSpecInput::new().percentage(3.0))
//!     .build()?;
//!
//! // client.fees().rules().upsert_program(&algorithm, None, "merch_1").await?;
//! # let _ = algorithm;
//! # Ok(())
//! # }
//! ```

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

use crate::core::error::{DelopayError, Result};

// ---------------------------------------------------------------------------
// Wire types
// ---------------------------------------------------------------------------

/// Euclid comparison operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EuclidComparisonType {
    /// `lhs == value`.
    Equal,
    /// `lhs != value`.
    NotEqual,
    /// `lhs < value`.
    LessThan,
    /// `lhs <= value`.
    LessThanEqual,
    /// `lhs > value`.
    GreaterThan,
    /// `lhs >= value`.
    GreaterThanEqual,
}

/// One entry of an [`EuclidValue::NumberComparisonArray`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NumberComparison {
    /// The operator to apply to `number`.
    #[serde(rename = "comparisonType")]
    pub comparison_type: EuclidComparisonType,
    /// The right-hand side of the comparison.
    pub number: Number,
}

/// A key/value pair for [`EuclidValue::MetadataVariant`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MetadataVariant {
    /// The metadata key to read.
    pub key: String,
    /// The value the key must hold.
    pub value: String,
}

/// A tagged Euclid value. Serializes as `{"type": <tag>, "value": <value>}`.
///
/// Enum-ish dimensions (`payment_method`, `connector`, `currency`,
/// `card_network`, `billing_country`) use [`EuclidValue::EnumVariant`];
/// numeric dimensions (`amount`, `merchant_volume`) use
/// [`EuclidValue::Number`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum EuclidValue {
    /// A single number, e.g. an amount in minor units.
    Number(Number),
    /// A backend enum variant name, e.g. `card`.
    EnumVariant(String),
    /// A free-form string.
    StrValue(String),
    /// A set of numbers.
    NumberArray(Vec<Number>),
    /// A set of enum variant names.
    EnumVariantArray(Vec<String>),
    /// A metadata key/value match.
    MetadataVariant(MetadataVariant),
    /// A set of number comparisons, all of which must hold.
    NumberComparisonArray(Vec<NumberComparison>),
}

impl From<i64> for EuclidValue {
    fn from(value: i64) -> Self {
        EuclidValue::Number(Number::from(value))
    }
}

impl From<String> for EuclidValue {
    fn from(value: String) -> Self {
        EuclidValue::EnumVariant(value)
    }
}

impl From<&str> for EuclidValue {
    fn from(value: &str) -> Self {
        EuclidValue::EnumVariant(value.to_string())
    }
}

/// A single condition.
///
/// `lhs` is a backend dimension key — e.g. `payment_method`, `connector`,
/// `currency`, `card_network`, `billing_country`, `amount`, `merchant_volume`,
/// or a payment-method-type key (`crypto`, `wallet`, `bank_redirect`, …).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EuclidComparison {
    /// The dimension being compared.
    pub lhs: String,
    /// The operator.
    pub comparison: EuclidComparisonType,
    /// The tagged right-hand side.
    pub value: EuclidValue,
    /// Required on the wire — send `{}` when empty.
    #[serde(default)]
    pub metadata: Map<String, Value>,
}

impl EuclidComparison {
    /// A comparison with empty `metadata` — the only shape the builder emits.
    pub fn new(
        lhs: impl Into<String>,
        comparison: EuclidComparisonType,
        value: impl Into<EuclidValue>,
    ) -> Self {
        Self {
            lhs: lhs.into(),
            comparison,
            value: value.into(),
            metadata: Map::new(),
        }
    }
}

/// An IF block; all comparisons in `condition` are ANDed, and `nested` (when
/// present) is an OR across sub-blocks that is ANDed with `condition`.
///
/// `nested` is omitted from the JSON when `None`; the engine treats an absent
/// and a `null` `nested` identically.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct EuclidIfStatement {
    /// The ANDed comparisons of this block.
    pub condition: Vec<EuclidComparison>,
    /// OR branches ANDed with `condition`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nested: Option<Vec<EuclidIfStatement>>,
}

/// How a matched rule prices the transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlatformFeeKind {
    /// A percentage of the transaction amount.
    Percentage,
    /// A fixed amount in minor units.
    Flat,
    /// Percentage plus flat amount.
    Combined,
}

/// A concrete fee. snake_case on the wire, and every field is always emitted
/// (as `null` when unset) — the engine distinguishes "unset" from "absent".
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PlatformFeeOutput {
    /// Inferred from which of the amounts are set.
    pub fee_type: PlatformFeeKind,
    /// Percentage fee — `2.5` means 2.5%.
    pub percentage_fee: Option<f64>,
    /// Flat fee in minor units.
    pub flat_fee_amount: Option<i64>,
    /// Currency of [`flat_fee_amount`](Self::flat_fee_amount).
    pub flat_fee_currency: Option<String>,
    /// Floor for the computed fee, in minor units.
    pub min_fee_amount: Option<i64>,
    /// Cap for the computed fee, in minor units.
    pub max_fee_amount: Option<i64>,
}

/// The Euclid program output `O`: a matched branch may set a concrete fee.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PlatformFeeRuleOutput {
    /// The fee this branch applies, or `null` to fall through to the flat
    /// schedules and volume tier.
    #[serde(default)]
    pub fee: Option<PlatformFeeOutput>,
}

/// A single fee rule (`Rule<PlatformFeeRules>`). camelCase on the wire.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlatformFeeRule {
    /// Rule name, echoed back as `matched_rule` by the preview endpoint.
    pub name: String,
    /// The fee applied when the rule matches.
    pub connector_selection: PlatformFeeRuleOutput,
    /// The rule's conditions; statements are ORed with each other.
    pub statements: Vec<EuclidIfStatement>,
}

/// The fee-rule program (`Program<PlatformFeeRules>`). camelCase on the wire.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlatformFeeProgram {
    /// Applied when no rule matches.
    pub default_selection: PlatformFeeRuleOutput,
    /// Evaluated in order; the first match wins.
    pub rules: Vec<PlatformFeeRule>,
    /// Required on the wire — send `{}` when empty.
    #[serde(default)]
    pub metadata: Map<String, Value>,
}

// ---------------------------------------------------------------------------
// Condition tree
// ---------------------------------------------------------------------------

/// A single condition leaf in the builder's condition tree.
#[derive(Debug, Clone, PartialEq)]
pub struct LeafNode {
    /// The dimension being compared.
    pub lhs: String,
    /// The operator.
    pub comparison: EuclidComparisonType,
    /// The tagged right-hand side.
    pub value: EuclidValue,
}

/// A node in the builder's condition tree: a leaf, an AND group, or an OR
/// group.
///
/// Build one with [`leaf`], [`all_of`] and [`any_of`] rather than by hand.
#[derive(Debug, Clone, PartialEq)]
pub enum ConditionNode {
    /// A single comparison.
    Leaf(LeafNode),
    /// AND — every child must match. An empty `All` always matches.
    All(Vec<ConditionNode>),
    /// OR — any matching child is enough. An empty `Any` is rejected by
    /// [`FeeProgramBuilder::rule`].
    Any(Vec<ConditionNode>),
}

/// A condition leaf.
///
/// The value is tagged by its Rust type: integers become
/// [`EuclidValue::Number`] and strings become [`EuclidValue::EnumVariant`].
/// For any other tag, construct [`ConditionNode::Leaf`] directly.
///
/// ```
/// use delopay::resources::fee_program::{ConditionNode, EuclidComparisonType, EuclidValue, leaf};
///
/// let node = leaf("amount", EuclidComparisonType::GreaterThan, 500_000);
/// assert!(matches!(node, ConditionNode::Leaf(l) if l.value == EuclidValue::Number(500_000.into())));
/// ```
pub fn leaf(
    lhs: impl Into<String>,
    comparison: EuclidComparisonType,
    value: impl Into<EuclidValue>,
) -> ConditionNode {
    ConditionNode::Leaf(LeafNode {
        lhs: lhs.into(),
        comparison,
        value: value.into(),
    })
}

/// AND group — all children must match.
pub fn all_of(children: impl IntoIterator<Item = ConditionNode>) -> ConditionNode {
    ConditionNode::All(children.into_iter().collect())
}

/// OR group — any child matching is enough.
pub fn any_of(children: impl IntoIterator<Item = ConditionNode>) -> ConditionNode {
    ConditionNode::Any(children.into_iter().collect())
}

/// Flatten associativity (nested all-in-all / any-in-any) and collapse
/// single-child groups, so every group child of an `All` is an `Any`.
///
/// Exposed because [`rule_match_to_tree`] returns a normalized tree: comparing
/// a hand-built tree against a decoded one means normalizing it first.
pub fn normalize_node(node: &ConditionNode) -> ConditionNode {
    let (is_any, children) = match node {
        ConditionNode::Leaf(_) => return node.clone(),
        ConditionNode::All(children) => (false, children),
        ConditionNode::Any(children) => (true, children),
    };

    let mut flat: Vec<ConditionNode> = Vec::with_capacity(children.len());
    for child in children.iter().map(normalize_node) {
        match (&child, is_any) {
            (ConditionNode::All(inner), false) | (ConditionNode::Any(inner), true) => {
                flat.extend(inner.iter().cloned());
            }
            _ => flat.push(child),
        }
    }

    if flat.len() == 1 {
        return flat.remove(0);
    }
    if is_any {
        ConditionNode::Any(flat)
    } else {
        ConditionNode::All(flat)
    }
}

fn leaf_to_comparison(node: &LeafNode) -> EuclidComparison {
    EuclidComparison {
        lhs: node.lhs.clone(),
        comparison: node.comparison,
        value: node.value.clone(),
        metadata: Map::new(),
    }
}

/// Encode one normalized node into a single statement.
fn to_statement(node: &ConditionNode) -> EuclidIfStatement {
    let children = match node {
        ConditionNode::Leaf(l) => {
            return EuclidIfStatement {
                condition: vec![leaf_to_comparison(l)],
                nested: None,
            };
        }
        // Unreachable via `encode_statements` (it strips a top-level `Any`);
        // kept for totality.
        ConditionNode::Any(children) => {
            return EuclidIfStatement {
                condition: Vec::new(),
                nested: Some(children.iter().map(to_statement).collect()),
            };
        }
        ConditionNode::All(children) => children,
    };

    // After normalization the group children of an `All` are all `Any`.
    let condition: Vec<EuclidComparison> = children
        .iter()
        .filter_map(|c| match c {
            ConditionNode::Leaf(l) => Some(leaf_to_comparison(l)),
            _ => None,
        })
        .collect();
    let groups: Vec<&ConditionNode> = children
        .iter()
        .filter(|c| !matches!(c, ConditionNode::Leaf(_)))
        .collect();

    let Some((first, rest)) = groups.split_first() else {
        return EuclidIfStatement {
            condition,
            nested: None,
        };
    };

    let branches = match first {
        ConditionNode::All(inner) | ConditionNode::Any(inner) => inner,
        ConditionNode::Leaf(_) => unreachable!("groups excludes leaves"),
    };

    // `first` is an OR; AND each of its branches with the remaining OR groups.
    let nested = branches
        .iter()
        .map(|branch| {
            let mut anded = Vec::with_capacity(rest.len() + 1);
            anded.push(branch.clone());
            anded.extend(rest.iter().map(|g| (*g).clone()));
            to_statement(&normalize_node(&ConditionNode::All(anded)))
        })
        .collect();

    EuclidIfStatement {
        condition,
        nested: Some(nested),
    }
}

/// Encode a rule's match (a condition tree) into the engine's `statements[]`.
///
/// A top-level OR spreads across statements (statements are ORed with each
/// other); anything else becomes a single statement.
pub fn encode_statements(node: &ConditionNode) -> Vec<EuclidIfStatement> {
    match normalize_node(node) {
        ConditionNode::Any(children) => children.iter().map(to_statement).collect(),
        other => vec![to_statement(&other)],
    }
}

fn comparison_to_leaf(c: &EuclidComparison) -> ConditionNode {
    ConditionNode::Leaf(LeafNode {
        lhs: c.lhs.clone(),
        comparison: c.comparison,
        value: c.value.clone(),
    })
}

fn statement_to_node(stmt: &EuclidIfStatement) -> ConditionNode {
    let leaves: Vec<ConditionNode> = stmt.condition.iter().map(comparison_to_leaf).collect();
    match &stmt.nested {
        Some(nested) if !nested.is_empty() => {
            let or_node = any_of(nested.iter().map(statement_to_node));
            if leaves.is_empty() {
                or_node
            } else {
                let mut anded = leaves;
                anded.push(or_node);
                ConditionNode::All(anded)
            }
        }
        _ => {
            if leaves.len() == 1 {
                leaves.into_iter().next().expect("length checked")
            } else {
                ConditionNode::All(leaves)
            }
        }
    }
}

/// Decode a rule's `statements[]` back into a condition tree.
///
/// The result is **logically equivalent** to the source. It equals
/// [`normalize_node`] of the original only when no `All` group contained two
/// or more `Any` groups; where [`encode_statements`] distributed AND over OR,
/// the decoded shape is the distributed one (still equivalent).
pub fn rule_match_to_tree(statements: &[EuclidIfStatement]) -> ConditionNode {
    if statements.len() == 1 {
        return normalize_node(&statement_to_node(&statements[0]));
    }
    normalize_node(&any_of(statements.iter().map(statement_to_node)))
}

/// One decoded rule, as returned by [`program_to_tree`].
#[derive(Debug, Clone, PartialEq)]
pub struct FeeRuleTree {
    /// The rule's name.
    pub name: String,
    /// The rule's conditions as an editable tree.
    pub match_tree: ConditionNode,
    /// The fee the rule applies, if any.
    pub fee: Option<PlatformFeeOutput>,
}

/// A decoded program, as returned by [`program_to_tree`].
#[derive(Debug, Clone, PartialEq)]
pub struct FeeProgramTree {
    /// The rules, in evaluation order.
    pub rules: Vec<FeeRuleTree>,
    /// The default selection's fee, applied when no rule matches.
    pub otherwise: Option<PlatformFeeOutput>,
}

/// Decode a stored program into the builder's editable model.
///
/// Each rule's tree carries the same equivalence caveat as
/// [`rule_match_to_tree`].
pub fn program_to_tree(program: &PlatformFeeProgram) -> FeeProgramTree {
    FeeProgramTree {
        rules: program
            .rules
            .iter()
            .map(|r| FeeRuleTree {
                name: r.name.clone(),
                match_tree: rule_match_to_tree(&r.statements),
                fee: r.connector_selection.fee.clone(),
            })
            .collect(),
        otherwise: program.default_selection.fee.clone(),
    }
}

// ---------------------------------------------------------------------------
// Builder inputs
// ---------------------------------------------------------------------------

/// How a rule (or the default) prices a transaction.
///
/// `fee_type` is inferred: percentage-only → [`PlatformFeeKind::Percentage`],
/// flat-only → [`PlatformFeeKind::Flat`], both → [`PlatformFeeKind::Combined`].
/// Setting neither also yields `percentage`, with a null percentage.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct FeeSpecInput {
    /// Percentage fee, e.g. `2.5` means 2.5%.
    pub percentage: Option<f64>,
    /// Flat fee in minor units.
    pub flat: Option<i64>,
    /// ISO 4217 currency for the flat fee.
    pub flat_currency: Option<String>,
    /// Clamp floor in minor units.
    pub min: Option<i64>,
    /// Clamp ceiling in minor units.
    pub max: Option<i64>,
}

impl FeeSpecInput {
    /// An empty spec; set the amounts you need.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the percentage fee — `2.5` means 2.5%.
    pub fn percentage(mut self, percentage: f64) -> Self {
        self.percentage = Some(percentage);
        self
    }

    /// Set the flat fee amount (minor units) and its currency.
    pub fn flat(mut self, amount: i64, currency: impl Into<String>) -> Self {
        self.flat = Some(amount);
        self.flat_currency = Some(currency.into());
        self
    }

    /// Set the flat fee amount (minor units) without a currency.
    pub fn flat_amount(mut self, amount: i64) -> Self {
        self.flat = Some(amount);
        self
    }

    /// Set the clamp floor, in minor units.
    pub fn min(mut self, min: i64) -> Self {
        self.min = Some(min);
        self
    }

    /// Set the clamp ceiling, in minor units.
    pub fn max(mut self, max: i64) -> Self {
        self.max = Some(max);
        self
    }
}

impl From<&FeeSpecInput> for PlatformFeeOutput {
    fn from(spec: &FeeSpecInput) -> Self {
        let fee_type = match (spec.percentage.is_some(), spec.flat.is_some()) {
            (true, true) => PlatformFeeKind::Combined,
            (false, true) => PlatformFeeKind::Flat,
            _ => PlatformFeeKind::Percentage,
        };
        PlatformFeeOutput {
            fee_type,
            percentage_fee: spec.percentage,
            flat_fee_amount: spec.flat,
            flat_fee_currency: spec.flat_currency.clone(),
            min_fee_amount: spec.min,
            max_fee_amount: spec.max,
        }
    }
}

/// Friendly conditions for a rule.
///
/// Every set field becomes one condition and they are ANDed together, in the
/// field order below. For dimensions not covered here (payment-method-type
/// keys like `crypto`/`wallet`, metadata, value arrays) use
/// [`FeeRuleInput::raw_conditions`], or drop down to
/// [`FeeRuleInput::match_tree`].
#[derive(Debug, Clone, Default, PartialEq)]
pub struct FeeRuleConditions {
    /// `payment_method == v`, e.g. `card`, `crypto`, `wallet`.
    pub payment_method: Option<String>,
    /// `connector == v`, e.g. `stripe`, `cryptomus`.
    pub connector: Option<String>,
    /// `currency == v`, e.g. `USD`.
    pub currency: Option<String>,
    /// `card_network == v`, e.g. `Visa`.
    pub card_network: Option<String>,
    /// Customer billing-address country.
    ///
    /// Must be the exact backend `Country` enum variant (PascalCase full name,
    /// e.g. `Germany` / `UnitedStatesOfAmerica`), not an ISO code — the engine
    /// lowers `billing_country` via case-sensitive `from_str`.
    pub billing_country: Option<String>,
    /// `amount == n` (minor units).
    pub amount_equals: Option<i64>,
    /// `amount > n` (minor units).
    pub amount_greater_than: Option<i64>,
    /// `amount < n` (minor units).
    pub amount_less_than: Option<i64>,
    /// `merchant_volume == n` — the merchant's previous-month volume snapshot
    /// (USD minor units).
    pub merchant_volume_equals: Option<i64>,
    /// `merchant_volume > n` (USD minor units).
    pub merchant_volume_greater_than: Option<i64>,
    /// `merchant_volume < n` (USD minor units).
    pub merchant_volume_less_than: Option<i64>,
}

impl FeeRuleConditions {
    /// No conditions; set the dimensions you need.
    pub fn new() -> Self {
        Self::default()
    }

    /// Match one payment method, e.g. `card` or `crypto`.
    pub fn payment_method(mut self, value: impl Into<String>) -> Self {
        self.payment_method = Some(value.into());
        self
    }

    /// Match one connector, e.g. `stripe`.
    pub fn connector(mut self, value: impl Into<String>) -> Self {
        self.connector = Some(value.into());
        self
    }

    /// Match one currency, e.g. `USD`.
    pub fn currency(mut self, value: impl Into<String>) -> Self {
        self.currency = Some(value.into());
        self
    }

    /// Match one card network, e.g. `Visa`.
    pub fn card_network(mut self, value: impl Into<String>) -> Self {
        self.card_network = Some(value.into());
        self
    }

    /// Match one billing country — the backend `Country` variant name, not an
    /// ISO code. See [`Self::billing_country`].
    pub fn billing_country(mut self, value: impl Into<String>) -> Self {
        self.billing_country = Some(value.into());
        self
    }

    /// `amount == n` (minor units).
    pub fn amount_equals(mut self, value: i64) -> Self {
        self.amount_equals = Some(value);
        self
    }

    /// `amount > n` (minor units).
    pub fn amount_greater_than(mut self, value: i64) -> Self {
        self.amount_greater_than = Some(value);
        self
    }

    /// `amount < n` (minor units).
    pub fn amount_less_than(mut self, value: i64) -> Self {
        self.amount_less_than = Some(value);
        self
    }

    /// `merchant_volume == n` (USD minor units).
    pub fn merchant_volume_equals(mut self, value: i64) -> Self {
        self.merchant_volume_equals = Some(value);
        self
    }

    /// `merchant_volume > n` (USD minor units).
    pub fn merchant_volume_greater_than(mut self, value: i64) -> Self {
        self.merchant_volume_greater_than = Some(value);
        self
    }

    /// `merchant_volume < n` (USD minor units).
    pub fn merchant_volume_less_than(mut self, value: i64) -> Self {
        self.merchant_volume_less_than = Some(value);
        self
    }

    /// The comparisons this set of conditions expands to, in field order.
    fn to_comparisons(&self) -> Vec<EuclidComparison> {
        use EuclidComparisonType::{Equal, GreaterThan, LessThan};

        let enums: [(&str, &Option<String>); 5] = [
            ("payment_method", &self.payment_method),
            ("connector", &self.connector),
            ("currency", &self.currency),
            ("card_network", &self.card_network),
            ("billing_country", &self.billing_country),
        ];
        let numbers: [(&str, EuclidComparisonType, Option<i64>); 6] = [
            ("amount", Equal, self.amount_equals),
            ("amount", GreaterThan, self.amount_greater_than),
            ("amount", LessThan, self.amount_less_than),
            ("merchant_volume", Equal, self.merchant_volume_equals),
            (
                "merchant_volume",
                GreaterThan,
                self.merchant_volume_greater_than,
            ),
            ("merchant_volume", LessThan, self.merchant_volume_less_than),
        ];

        let mut out = Vec::new();
        for (lhs, value) in enums {
            if let Some(v) = value {
                out.push(EuclidComparison::new(lhs, Equal, v.as_str()));
            }
        }
        for (lhs, comparison, value) in numbers {
            if let Some(v) = value {
                out.push(EuclidComparison::new(lhs, comparison, v));
            }
        }
        out
    }
}

/// One rule to append with [`FeeProgramBuilder::rule`].
#[derive(Debug, Clone, PartialEq)]
pub struct FeeRuleInput {
    /// The rule's name, echoed back by the preview endpoint.
    pub name: String,
    /// Friendly conditions (ANDed). Leave empty for an always-matching rule
    /// (prefer [`FeeProgramBuilder::otherwise`]).
    pub when: FeeRuleConditions,
    /// Extra raw conditions ANDed in, for dimensions `when` does not cover.
    pub raw_conditions: Vec<EuclidComparison>,
    /// Nested AND/OR condition tree. When set it **replaces** `when` and
    /// `raw_conditions`.
    pub match_tree: Option<ConditionNode>,
    /// How the rule prices a matching transaction.
    pub fee: FeeSpecInput,
}

impl FeeRuleInput {
    /// A named rule with a fee and no conditions yet.
    pub fn new(name: impl Into<String>, fee: FeeSpecInput) -> Self {
        Self {
            name: name.into(),
            when: FeeRuleConditions::new(),
            raw_conditions: Vec::new(),
            match_tree: None,
            fee,
        }
    }

    /// Set the friendly conditions (ANDed).
    pub fn when(mut self, when: FeeRuleConditions) -> Self {
        self.when = when;
        self
    }

    /// Add raw conditions, ANDed in after the friendly ones.
    pub fn raw_conditions(mut self, raw: impl IntoIterator<Item = EuclidComparison>) -> Self {
        self.raw_conditions.extend(raw);
        self
    }

    /// Use a nested AND/OR tree instead of [`Self::when`] /
    /// [`Self::raw_conditions`].
    pub fn match_tree(mut self, node: ConditionNode) -> Self {
        self.match_tree = Some(node);
        self
    }
}

/// Reject `Any` groups with no children — they would match nothing, which is
/// never what the caller meant. Returns the failure message, not a
/// `DelopayError`, so [`FeeProgramBuilder`] can stay `Clone`.
fn check_no_empty_any(node: &ConditionNode) -> std::result::Result<(), String> {
    let children = match node {
        ConditionNode::Leaf(_) => return Ok(()),
        ConditionNode::Any(children) => {
            if children.is_empty() {
                return Err(
                    "fee program: an any_of() group must have at least one condition".to_string(),
                );
            }
            children
        }
        ConditionNode::All(children) => children,
    };
    children.iter().try_for_each(check_no_empty_any)
}

// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------

/// Fluent builder for a fee-rule program.
///
/// Emits the exact Euclid wire shape (camelCase tree, tagged values,
/// `metadata: {}` everywhere) so callers never hand-write the AST. Rules are
/// evaluated in order; the first match wins, else
/// [`otherwise`](Self::otherwise) (the default selection).
///
/// Validation errors from [`rule`](Self::rule) are recorded and surfaced by
/// [`build`](Self::build), keeping the chain ergonomic.
///
/// ```
/// use delopay::resources::fee_program::{
///     EuclidComparisonType, FeeRuleInput, FeeSpecInput, all_of, any_of, fee_program, leaf,
/// };
///
/// # fn main() -> delopay::Result<()> {
/// let program = fee_program()
///     .rule(
///         FeeRuleInput::new("crypto_or_big_card", FeeSpecInput::new().percentage(1.5))
///             .match_tree(any_of([
///                 leaf("payment_method", EuclidComparisonType::Equal, "crypto"),
///                 all_of([
///                     leaf("payment_method", EuclidComparisonType::Equal, "card"),
///                     leaf("merchant_volume", EuclidComparisonType::GreaterThan, 1_000_000),
///                 ]),
///             ])),
///     )
///     .otherwise(FeeSpecInput::new().percentage(3.0))
///     .build()?;
///
/// assert_eq!(program.rules[0].statements.len(), 2);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Default)]
pub struct FeeProgramBuilder {
    rules: Vec<PlatformFeeRule>,
    default_fee: Option<PlatformFeeOutput>,
    /// The first validation failure, kept as a message so the builder stays
    /// `Clone` (`DelopayError` is not).
    error: Option<String>,
}

impl FeeProgramBuilder {
    /// An empty program.
    pub fn new() -> Self {
        Self::default()
    }

    /// Append a rule. `when` and `raw_conditions` are ANDed; a
    /// [`match_tree`](FeeRuleInput::match_tree) replaces both.
    pub fn rule(mut self, input: FeeRuleInput) -> Self {
        let statements = match &input.match_tree {
            Some(node) => {
                if let Err(e) = check_no_empty_any(node) {
                    if self.error.is_none() {
                        self.error = Some(e);
                    }
                    return self;
                }
                encode_statements(node)
            }
            None => {
                let mut condition = input.when.to_comparisons();
                condition.extend(input.raw_conditions.iter().cloned());
                vec![EuclidIfStatement {
                    condition,
                    nested: None,
                }]
            }
        };

        self.rules.push(PlatformFeeRule {
            name: input.name,
            connector_selection: PlatformFeeRuleOutput {
                fee: Some((&input.fee).into()),
            },
            statements,
        });
        self
    }

    /// Set the default selection, applied when no rule matches. Omitting it
    /// leaves the default fee null, which falls through to the flat schedules.
    pub fn otherwise(mut self, fee: FeeSpecInput) -> Self {
        self.default_fee = Some((&fee).into());
        self
    }

    /// Produce the wire-ready program, or the first error recorded by
    /// [`rule`](Self::rule).
    pub fn build(self) -> Result<PlatformFeeProgram> {
        if let Some(message) = self.error {
            return Err(DelopayError::InvalidRequest(message));
        }
        Ok(PlatformFeeProgram {
            default_selection: PlatformFeeRuleOutput {
                fee: self.default_fee,
            },
            rules: self.rules,
            metadata: Map::new(),
        })
    }
}

/// Start building a fee-rule program. See [`FeeProgramBuilder`].
pub fn fee_program() -> FeeProgramBuilder {
    FeeProgramBuilder::new()
}

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

    use EuclidComparisonType::{Equal, GreaterThan, LessThan};

    fn pm(v: &str) -> ConditionNode {
        leaf("payment_method", Equal, v)
    }

    fn vol(n: i64) -> ConditionNode {
        leaf("merchant_volume", GreaterThan, n)
    }

    fn full_fee(percentage: f64) -> Value {
        json!({
            "fee_type": "percentage",
            "percentage_fee": percentage,
            "flat_fee_amount": null,
            "flat_fee_currency": null,
            "min_fee_amount": null,
            "max_fee_amount": null,
        })
    }

    // -- wire format ------------------------------------------------------

    #[test]
    fn emits_the_exact_euclid_program() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("crypto", FeeSpecInput::new().percentage(1.0))
                    .when(FeeRuleConditions::new().payment_method("crypto")),
            )
            .rule(
                FeeRuleInput::new("card_on_cryptomus", FeeSpecInput::new().percentage(2.0)).when(
                    FeeRuleConditions::new()
                        .payment_method("card")
                        .connector("cryptomus"),
                ),
            )
            .otherwise(FeeSpecInput::new().percentage(3.0))
            .build()
            .unwrap();

        assert_eq!(
            serde_json::to_value(&program).unwrap(),
            json!({
                "defaultSelection": { "fee": full_fee(3.0) },
                "rules": [
                    {
                        "name": "crypto",
                        "connectorSelection": { "fee": full_fee(1.0) },
                        "statements": [{
                            "condition": [{
                                "lhs": "payment_method",
                                "comparison": "equal",
                                "value": { "type": "enum_variant", "value": "crypto" },
                                "metadata": {},
                            }],
                        }],
                    },
                    {
                        "name": "card_on_cryptomus",
                        "connectorSelection": { "fee": full_fee(2.0) },
                        "statements": [{
                            "condition": [
                                {
                                    "lhs": "payment_method",
                                    "comparison": "equal",
                                    "value": { "type": "enum_variant", "value": "card" },
                                    "metadata": {},
                                },
                                {
                                    "lhs": "connector",
                                    "comparison": "equal",
                                    "value": { "type": "enum_variant", "value": "cryptomus" },
                                    "metadata": {},
                                },
                            ],
                        }],
                    },
                ],
                "metadata": {},
            })
        );
    }

    #[test]
    fn serializes_camel_case_keys_and_tagged_values() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("r", FeeSpecInput::new().percentage(1.0))
                    .when(FeeRuleConditions::new().payment_method("card")),
            )
            .build()
            .unwrap();
        let json = serde_json::to_string(&program).unwrap();

        assert!(json.contains(r#""defaultSelection""#), "{json}");
        assert!(json.contains(r#""connectorSelection""#), "{json}");
        assert!(json.contains(r#""type":"enum_variant""#), "{json}");
        // Never snake_case for the tree keys.
        assert!(!json.contains(r#""default_selection""#), "{json}");
        assert!(!json.contains(r#""connector_selection""#), "{json}");
    }

    #[test]
    fn numeric_conditions_serialize_as_integers_not_floats() {
        // A float here (`500000.0`) would fail the engine's integer decode.
        let program = fee_program()
            .rule(
                FeeRuleInput::new("big", FeeSpecInput::new().percentage(2.0))
                    .when(FeeRuleConditions::new().amount_greater_than(500_000)),
            )
            .build()
            .unwrap();
        let json = serde_json::to_string(&program).unwrap();
        assert!(json.contains(r#""value":500000"#), "{json}");
    }

    #[test]
    fn infers_fee_type_percentage_flat_combined() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("flat", FeeSpecInput::new().flat(30, "USD"))
                    .when(FeeRuleConditions::new().connector("stripe")),
            )
            .rule(
                FeeRuleInput::new(
                    "combined",
                    FeeSpecInput::new().percentage(2.0).flat_amount(30),
                )
                .when(FeeRuleConditions::new().currency("USD")),
            )
            .otherwise(FeeSpecInput::new().percentage(1.0))
            .build()
            .unwrap();

        let first = program.rules[0].connector_selection.fee.as_ref().unwrap();
        assert_eq!(first.fee_type, PlatformFeeKind::Flat);
        assert_eq!(first.flat_fee_amount, Some(30));
        assert_eq!(first.flat_fee_currency.as_deref(), Some("USD"));
        assert_eq!(
            program.rules[1]
                .connector_selection
                .fee
                .as_ref()
                .unwrap()
                .fee_type,
            PlatformFeeKind::Combined
        );
        // No amounts at all still reads as `percentage`.
        assert_eq!(
            PlatformFeeOutput::from(&FeeSpecInput::new()).fee_type,
            PlatformFeeKind::Percentage
        );
    }

    #[test]
    fn maps_amount_conditions_to_numeric_comparisons() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("big", FeeSpecInput::new().percentage(2.0))
                    .when(FeeRuleConditions::new().amount_greater_than(500_000)),
            )
            .build()
            .unwrap();

        assert_eq!(
            program.rules[0].statements[0].condition[0],
            EuclidComparison {
                lhs: "amount".to_string(),
                comparison: GreaterThan,
                value: EuclidValue::Number(500_000.into()),
                metadata: Map::new(),
            }
        );
    }

    #[test]
    fn maps_merchant_volume_conditions_combinable_with_method() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("crypto_high_volume", FeeSpecInput::new().percentage(1.0)).when(
                    FeeRuleConditions::new()
                        .payment_method("crypto")
                        .merchant_volume_greater_than(1_000_000),
                ),
            )
            .build()
            .unwrap();

        assert_eq!(
            program.rules[0].statements[0].condition,
            vec![
                EuclidComparison::new("payment_method", Equal, "crypto"),
                EuclidComparison::new("merchant_volume", GreaterThan, 1_000_000),
            ]
        );
    }

    #[test]
    fn ands_friendly_conditions_with_raw_conditions_after_them() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("crypto_type", FeeSpecInput::new().percentage(1.0))
                    .when(FeeRuleConditions::new().payment_method("crypto"))
                    .raw_conditions([EuclidComparison::new("crypto", Equal, "crypto_currency")]),
            )
            .build()
            .unwrap();

        let condition = &program.rules[0].statements[0].condition;
        assert_eq!(condition.len(), 2);
        assert_eq!(condition[0].lhs, "payment_method");
        assert_eq!(condition[1].lhs, "crypto");
    }

    #[test]
    fn defaults_to_null_fee_when_otherwise_is_omitted() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("r", FeeSpecInput::new().percentage(1.0))
                    .when(FeeRuleConditions::new().payment_method("card")),
            )
            .build()
            .unwrap();

        assert_eq!(program.default_selection.fee, None);
        // The key must still be on the wire, as an explicit null.
        assert_eq!(
            serde_json::to_value(&program).unwrap()["defaultSelection"],
            json!({ "fee": null })
        );
    }

    // -- condition-tree constructors ---------------------------------------

    #[test]
    fn leaf_tags_numbers_as_number_and_strings_as_enum_variant() {
        assert_eq!(
            leaf("amount", GreaterThan, 500_000),
            ConditionNode::Leaf(LeafNode {
                lhs: "amount".to_string(),
                comparison: GreaterThan,
                value: EuclidValue::Number(500_000.into()),
            })
        );
        assert_eq!(
            leaf("payment_method", Equal, "crypto"),
            ConditionNode::Leaf(LeafNode {
                lhs: "payment_method".to_string(),
                comparison: Equal,
                value: EuclidValue::EnumVariant("crypto".to_string()),
            })
        );
    }

    #[test]
    fn all_of_and_any_of_are_distinct_groups() {
        let a = leaf("connector", Equal, "stripe");
        assert_eq!(all_of([a.clone()]), ConditionNode::All(vec![a.clone()]));
        assert_eq!(any_of([a.clone()]), ConditionNode::Any(vec![a]));
    }

    // -- encode_statements --------------------------------------------------

    #[test]
    fn single_leaf_encodes_to_one_statement_with_no_nested() {
        assert_eq!(
            encode_statements(&pm("card")),
            vec![EuclidIfStatement {
                condition: vec![EuclidComparison::new("payment_method", Equal, "card")],
                nested: None,
            }]
        );
    }

    #[test]
    fn all_of_leaves_encodes_to_one_anded_statement() {
        let stmts = encode_statements(&all_of([pm("card"), vol(1_000_000)]));
        assert_eq!(stmts.len(), 1);
        assert_eq!(
            stmts[0]
                .condition
                .iter()
                .map(|c| c.lhs.as_str())
                .collect::<Vec<_>>(),
            ["payment_method", "merchant_volume"]
        );
        assert_eq!(stmts[0].nested, None);
    }

    #[test]
    fn any_of_at_top_encodes_to_one_statement_per_branch() {
        let stmts = encode_statements(&any_of([
            pm("crypto"),
            all_of([pm("card"), vol(1_000_000)]),
        ]));
        assert_eq!(stmts.len(), 2);
        assert_eq!(
            stmts[0].condition[0].value,
            EuclidValue::EnumVariant("crypto".to_string())
        );
        assert_eq!(
            stmts[1]
                .condition
                .iter()
                .map(|c| c.lhs.as_str())
                .collect::<Vec<_>>(),
            ["payment_method", "merchant_volume"]
        );
    }

    #[test]
    fn all_of_leaf_and_any_of_encodes_condition_anded_with_nested_or() {
        let stmts = encode_statements(&all_of([
            vol(1_000_000),
            any_of([pm("card"), pm("wallet")]),
        ]));
        assert_eq!(stmts.len(), 1);
        assert_eq!(
            stmts[0]
                .condition
                .iter()
                .map(|c| c.lhs.as_str())
                .collect::<Vec<_>>(),
            ["merchant_volume"]
        );
        let nested = stmts[0].nested.as_ref().expect("nested OR");
        assert_eq!(nested.len(), 2);
        assert_eq!(
            nested[0].condition[0].value,
            EuclidValue::EnumVariant("card".to_string())
        );
        assert_eq!(
            nested[1].condition[0].value,
            EuclidValue::EnumVariant("wallet".to_string())
        );
    }

    /// `normalize_node` must be pinned against literal trees, not against
    /// itself: the round-trip tests compare `decode(encode(t))` to
    /// `normalize_node(&t)`, so a broken normalizer stays invisible there.
    #[test]
    fn normalize_collapses_single_child_groups_and_flattens_associativity() {
        assert_eq!(normalize_node(&all_of([pm("card")])), pm("card"));
        assert_eq!(normalize_node(&any_of([pm("card")])), pm("card"));
        assert_eq!(normalize_node(&all_of([any_of([pm("card")])])), pm("card"));
        assert_eq!(
            normalize_node(&all_of([pm("card"), all_of([vol(1), pm("wallet")])])),
            all_of([pm("card"), vol(1), pm("wallet")])
        );
        assert_eq!(
            normalize_node(&any_of([pm("card"), any_of([pm("wallet"), pm("crypto")])])),
            any_of([pm("card"), pm("wallet"), pm("crypto")])
        );
        // An `any` inside an `all` is *not* flattened — that is the shape
        // `to_statement` relies on.
        assert_eq!(
            normalize_node(&all_of([pm("card"), any_of([pm("wallet"), pm("crypto")])])),
            all_of([pm("card"), any_of([pm("wallet"), pm("crypto")])])
        );
    }

    #[test]
    fn flattens_nested_all_and_collapses_single_child_groups() {
        assert_eq!(
            encode_statements(&all_of([all_of([pm("card")])])),
            encode_statements(&pm("card"))
        );
        // Same for `any` associativity.
        assert_eq!(
            encode_statements(&any_of([any_of([pm("card"), pm("wallet")])])),
            encode_statements(&any_of([pm("card"), pm("wallet")]))
        );
    }

    #[test]
    fn preserves_an_and_inside_an_or_branch_that_is_anded_with_another_condition() {
        // ((card AND stripe) OR wallet) AND USD
        let stmts = encode_statements(&all_of([
            any_of([
                all_of([
                    leaf("payment_method", Equal, "card"),
                    leaf("connector", Equal, "stripe"),
                ]),
                leaf("payment_method", Equal, "wallet"),
            ]),
            leaf("currency", Equal, "USD"),
        ]));
        assert_eq!(stmts.len(), 1);
        assert_eq!(
            stmts[0]
                .condition
                .iter()
                .map(|c| c.lhs.as_str())
                .collect::<Vec<_>>(),
            ["currency"]
        );
        let nested = stmts[0].nested.as_ref().expect("nested OR");
        assert_eq!(nested.len(), 2);
        // The first branch must stay an AND of card+stripe; `currency` stays on
        // the outer condition (there are no further OR groups to distribute).
        assert_eq!(
            nested[0]
                .condition
                .iter()
                .map(|c| c.lhs.as_str())
                .collect::<Vec<_>>(),
            ["payment_method", "connector"]
        );
        assert_eq!(nested[0].nested, None);
    }

    // -- builder rule(match) -----------------------------------------------

    #[test]
    fn emits_multi_statement_or_rules_from_a_match_tree() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("crypto_or_big_card", FeeSpecInput::new().percentage(1.5))
                    .match_tree(any_of([pm("crypto"), all_of([pm("card"), vol(1_000_000)])])),
            )
            .otherwise(FeeSpecInput::new().percentage(3.0))
            .build()
            .unwrap();

        assert_eq!(program.rules[0].statements.len(), 2);
        assert_eq!(
            program.rules[0]
                .connector_selection
                .fee
                .as_ref()
                .unwrap()
                .percentage_fee,
            Some(1.5)
        );
    }

    #[test]
    fn still_supports_the_flat_when_sugar_as_a_single_statement() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("r", FeeSpecInput::new().percentage(1.0))
                    .when(FeeRuleConditions::new().payment_method("card")),
            )
            .build()
            .unwrap();
        assert_eq!(program.rules[0].statements.len(), 1);
    }

    #[test]
    fn rejects_an_empty_any_of_in_a_match_tree() {
        let err = fee_program()
            .rule(
                FeeRuleInput::new("bad", FeeSpecInput::new().percentage(1.0))
                    .match_tree(any_of([])),
            )
            .build()
            .unwrap_err();
        match err {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("any_of"), "{msg}"),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    #[test]
    fn rejects_a_nested_empty_any_of() {
        let err = fee_program()
            .rule(
                FeeRuleInput::new("bad", FeeSpecInput::new().percentage(1.0))
                    .match_tree(all_of([pm("card"), any_of([])])),
            )
            .build()
            .unwrap_err();
        assert!(matches!(err, DelopayError::InvalidRequest(_)));
    }

    #[test]
    fn still_allows_an_empty_all_of_as_an_always_match() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("always", FeeSpecInput::new().percentage(1.0))
                    .match_tree(all_of([])),
            )
            .build()
            .unwrap();
        assert_eq!(program.rules.len(), 1);
        assert!(program.rules[0].statements[0].condition.is_empty());
    }

    #[test]
    fn a_rejected_rule_is_not_appended() {
        let builder = fee_program()
            .rule(
                FeeRuleInput::new("ok", FeeSpecInput::new().percentage(1.0))
                    .when(FeeRuleConditions::new().payment_method("card")),
            )
            .rule(
                FeeRuleInput::new("bad", FeeSpecInput::new().percentage(1.0))
                    .match_tree(any_of([])),
            );
        assert_eq!(builder.rules.len(), 1);
        assert!(builder.build().is_err());
    }

    // -- decode / round-trip -----------------------------------------------

    #[test]
    fn decode_of_encode_is_structurally_equal_to_normalize() {
        let cases = [
            pm("card"),
            all_of([pm("card"), vol(1_000_000)]),
            any_of([pm("crypto"), all_of([pm("card"), vol(1_000_000)])]),
        ];
        for tree in cases {
            assert_eq!(
                rule_match_to_tree(&encode_statements(&tree)),
                normalize_node(&tree),
                "round-trip changed {tree:?}"
            );
        }
    }

    #[test]
    fn round_trips_a_leaf_anded_with_an_or() {
        let t = all_of([
            pm("card"),
            any_of([
                leaf("amount", GreaterThan, 500_000),
                leaf("amount", LessThan, 1_000_000),
            ]),
        ]);
        assert_eq!(
            rule_match_to_tree(&encode_statements(&t)),
            normalize_node(&t)
        );
    }

    #[test]
    fn decodes_an_and_of_two_ors_to_the_distributed_form() {
        let a = pm("card");
        let b = pm("wallet");
        let c = leaf("currency", Equal, "USD");
        let d = leaf("currency", Equal, "EUR");
        let decoded = rule_match_to_tree(&encode_statements(&all_of([
            any_of([a.clone(), b.clone()]),
            any_of([c.clone(), d.clone()]),
        ])));

        assert_eq!(
            decoded,
            any_of([
                all_of([a, any_of([c.clone(), d.clone()])]),
                all_of([b, any_of([c, d])]),
            ])
        );
    }

    #[test]
    fn program_to_tree_decodes_names_fees_and_the_default() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("crypto", FeeSpecInput::new().percentage(1.0))
                    .when(FeeRuleConditions::new().payment_method("crypto")),
            )
            .otherwise(FeeSpecInput::new().flat(30, "USD"))
            .build()
            .unwrap();

        let tree = program_to_tree(&program);
        assert_eq!(tree.rules.len(), 1);
        assert_eq!(tree.rules[0].name, "crypto");
        assert_eq!(tree.rules[0].match_tree, pm("crypto"));
        assert_eq!(
            tree.rules[0].fee.as_ref().unwrap().percentage_fee,
            Some(1.0)
        );
        let otherwise = tree.otherwise.as_ref().expect("default fee");
        assert_eq!(otherwise.fee_type, PlatformFeeKind::Flat);
        assert_eq!(otherwise.flat_fee_amount, Some(30));
    }

    #[test]
    fn program_round_trips_through_json() {
        let program = fee_program()
            .rule(
                FeeRuleInput::new("r", FeeSpecInput::new().percentage(1.0).min(50).max(900))
                    .match_tree(all_of([vol(1_000_000), any_of([pm("card"), pm("wallet")])])),
            )
            .otherwise(FeeSpecInput::new().percentage(3.0))
            .build()
            .unwrap();

        let encoded = serde_json::to_string(&program).unwrap();
        let decoded: PlatformFeeProgram = serde_json::from_str(&encoded).unwrap();
        assert_eq!(decoded, program);
    }
}