payrix 0.3.0

Rust client for the Payrix payment processing API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
//! Chargeback dispute handling workflow with compile-time state enforcement.
//!
//! This module provides a high-level, type-safe API for handling chargeback disputes
//! using Rust's typestate pattern to ensure valid state transitions at compile time.
//!
//! # Chargeback Lifecycle
//!
//! Chargebacks follow a specific lifecycle where certain actions are only valid
//! at certain stages:
//!
//! ```text
//!                                     ┌──────────────────────────────────────┐
//!                                     │          (cycle can repeat)          │
//!                                     ▼                                      │
//! Retrieval → First → Representment → Pre-Arbitration → Second Chargeback  ──┘
//!     │         │          │               │                    │
//!     │         │          │               │               ┌────┴────┐
//!     │    ┌────┴────┐     │          ┌────┴────┐          │         │
//!     ▼    ▼         ▼     ▼          ▼         ▼          ▼         ▼
//!  (wait) Represent Accept (await)  Accept   Request    Represent Accept
//!         + Evidence Liability      Liability Arbitration + Evidence Liability
//!//!//!                                                          Arbitration
//!//!                                                     ┌─────────┼─────────┐
//!                                                     ▼         ▼         ▼
//!                                                    Won       Lost     Split
//! ```
//!
//! # Typestate Pattern
//!
//! This module uses the typestate pattern to ensure that:
//! - `represent()` is only callable in `First`, `PreArbitration`, and `SecondChargeback` states
//! - `accept_liability()` is only callable in `First`, `PreArbitration`, and `SecondChargeback` states
//! - `request_arbitration()` is only callable in `PreArbitration` state
//!
//! Attempting to call these methods in invalid states results in a **compile error**,
//! not a runtime error.
//!
//! # Key Insight: Stateless API
//!
//! Chargebacks can take weeks to months to resolve. This API is designed to be:
//! - **Stateless** - Always load fresh state from Payrix API
//! - **Event-driven** - Works with webhooks to track state changes
//! - **Refreshable** - Easy to reload state from the latest API data
//!
//! # Example
//!
//! ```no_run
//! use payrix::{PayrixClient, Environment};
//! use payrix::workflows::dispute_handling::{ChargebackDispute, ActiveDispute, Evidence};
//!
//! # async fn example() -> payrix::Result<()> {
//! let client = PayrixClient::new("api-key", Environment::Test)?;
//!
//! // Load a chargeback - runtime state becomes compile-time type
//! let dispute = ChargebackDispute::load(&client, "t1_chb_123").await?;
//!
//! match dispute {
//!     ChargebackDispute::Active(active) => match active {
//!         ActiveDispute::First(first) => {
//!             // represent() ONLY available here - won't compile elsewhere
//!             let evidence = Evidence::new("Customer received goods as described")
//!                 .with_document("receipt.pdf", vec![/* pdf bytes */], "application/pdf");
//!             let represented = first.represent(&client, evidence).await?;
//!             println!("Chargeback represented, now in representment stage");
//!         }
//!         ActiveDispute::PreArbitration(pre_arb) => {
//!             // request_arbitration() ONLY available here
//!             let arbitrating = pre_arb.request_arbitration(&client).await?;
//!             println!("Arbitration requested");
//!         }
//!         _ => {
//!             println!("No action required at this stage");
//!         }
//!     },
//!     ChargebackDispute::Terminal(terminal) => {
//!         println!("Dispute closed: {:?}", terminal.inner().status);
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Evidence Requirements
//!
//! When representing a chargeback, evidence must meet Payrix requirements:
//! - Maximum 8 documents per representment
//! - Maximum 1 MB per document
//! - Maximum 8 MB total combined
//! - Supported formats: TIFF/TIF, PDF (primary); PNG, JPG, GIF (also accepted)
//! - Must submit 5 business days before the reply deadline

use std::marker::PhantomData;
use std::path::Path;

use base64::Engine;

use crate::client::PayrixClient;
use crate::entity::EntityType;
use crate::error::{Error, Result};
use crate::types::{
    Chargeback, ChargebackCycle, ChargebackDocument, ChargebackDocumentType, ChargebackMessage,
    ChargebackMessageType, ChargebackStatusValue, CreateChargebackDocument, CreateChargebackMessage,
    PayrixId,
};

// =============================================================================
// Evidence Constants (Payrix Requirements)
// =============================================================================

/// Maximum number of documents allowed per representment.
pub const MAX_DOCUMENTS: usize = 8;

/// Maximum size per document in bytes (1 MB).
pub const MAX_DOCUMENT_SIZE: usize = 1_048_576;

/// Maximum total size for all documents in bytes (8 MB).
pub const MAX_TOTAL_SIZE: usize = 8_388_608;

// =============================================================================
// Section 1: State Marker Types
// =============================================================================

/// Sealed trait module to prevent external implementations.
mod private {
    pub trait Sealed {}
}

/// Trait for chargeback state markers.
///
/// This trait is sealed and cannot be implemented outside this module,
/// ensuring that only the predefined states are valid.
pub trait ChargebackState: private::Sealed {
    /// Returns the human-readable name of this state.
    fn state_name() -> &'static str;
}

/// Initial retrieval stage - awaiting first chargeback.
///
/// At this stage, no actions are available. The merchant must wait
/// for the issuer to file the first chargeback.
#[derive(Debug, Clone, Copy)]
pub struct Retrieval;

impl private::Sealed for Retrieval {}
impl ChargebackState for Retrieval {
    fn state_name() -> &'static str {
        "retrieval"
    }
}

/// First chargeback stage - merchant can respond.
///
/// Available actions:
/// - [`TypedChargeback::represent`] - Submit evidence to dispute the chargeback
/// - [`TypedChargeback::accept_liability`] - Accept the chargeback
#[derive(Debug, Clone, Copy)]
pub struct First;

impl private::Sealed for First {}
impl ChargebackState for First {
    fn state_name() -> &'static str {
        "first"
    }
}

/// Representment stage - awaiting issuer decision.
///
/// At this stage, no actions are available. The merchant must wait
/// for the issuer to review the submitted evidence.
#[derive(Debug, Clone, Copy)]
pub struct Representment;

impl private::Sealed for Representment {}
impl ChargebackState for Representment {
    fn state_name() -> &'static str {
        "representment"
    }
}

/// Pre-arbitration stage - merchant must choose to arbitrate or accept.
///
/// Available actions:
/// - [`TypedChargeback::request_arbitration`] - Escalate to card network arbitration
/// - [`TypedChargeback::accept_liability`] - Accept the chargeback
/// - [`TypedChargeback::represent`] - Submit additional evidence (if allowed)
#[derive(Debug, Clone, Copy)]
pub struct PreArbitration;

impl private::Sealed for PreArbitration {}
impl ChargebackState for PreArbitration {
    fn state_name() -> &'static str {
        "preArbitration"
    }
}

/// Second chargeback stage - another round of dispute.
///
/// Available actions:
/// - [`TypedChargeback::represent`] - Submit evidence to dispute the chargeback
/// - [`TypedChargeback::accept_liability`] - Accept the chargeback
#[derive(Debug, Clone, Copy)]
pub struct SecondChargeback;

impl private::Sealed for SecondChargeback {}
impl ChargebackState for SecondChargeback {
    fn state_name() -> &'static str {
        "secondChargeback"
    }
}

/// Arbitration stage - awaiting card network decision.
///
/// At this stage, no actions are available. The merchant must wait
/// for the card network to make a final decision.
#[derive(Debug, Clone, Copy)]
pub struct Arbitration;

impl private::Sealed for Arbitration {}
impl ChargebackState for Arbitration {
    fn state_name() -> &'static str {
        "arbitration"
    }
}

/// Terminal stage - chargeback is closed.
///
/// The dispute has reached a final state (won, lost, or closed).
/// No further actions are available.
#[derive(Debug, Clone, Copy)]
pub struct Terminal;

impl private::Sealed for Terminal {}
impl ChargebackState for Terminal {
    fn state_name() -> &'static str {
        "terminal"
    }
}

// =============================================================================
// Section 2: TypedChargeback Wrapper
// =============================================================================

/// A chargeback with compile-time state enforcement.
///
/// This wrapper provides state-specific methods that are only available
/// when the chargeback is in the appropriate state. For example,
/// `represent()` is only available on `TypedChargeback<First>`.
///
/// # Type Parameters
///
/// * `S` - The current state of the chargeback (e.g., `First`, `PreArbitration`)
#[derive(Debug, Clone)]
pub struct TypedChargeback<S: ChargebackState> {
    inner: Chargeback,
    _state: PhantomData<S>,
}

impl<S: ChargebackState> TypedChargeback<S> {
    /// Create a new typed chargeback from raw chargeback data.
    fn new(chargeback: Chargeback) -> Self {
        Self {
            inner: chargeback,
            _state: PhantomData,
        }
    }

    /// Get a reference to the underlying chargeback data.
    pub fn inner(&self) -> &Chargeback {
        &self.inner
    }

    /// Consume the wrapper and return the underlying chargeback data.
    pub fn into_inner(self) -> Chargeback {
        self.inner
    }

    /// Get the chargeback ID.
    pub fn id(&self) -> &PayrixId {
        &self.inner.id
    }

    /// Get the current state name.
    pub fn state_name(&self) -> &'static str {
        S::state_name()
    }

    /// Get the chargeback amount in cents.
    pub fn amount(&self) -> Option<i64> {
        self.inner.total
    }

    /// Get the reason code for this chargeback.
    pub fn reason_code(&self) -> Option<&str> {
        self.inner.reason_code.as_deref()
    }

    /// Get the reason description for this chargeback.
    pub fn reason(&self) -> Option<&str> {
        self.inner.reason.as_deref()
    }

    /// Get the reply deadline as YYYYMMDD integer.
    pub fn reply_deadline(&self) -> Option<i32> {
        self.inner.reply
    }

    /// Check if this chargeback is actionable.
    pub fn is_actionable(&self) -> bool {
        self.inner.actionable
    }

    /// Get the associated merchant ID.
    pub fn merchant_id(&self) -> Option<&PayrixId> {
        self.inner.merchant.as_ref()
    }

    /// Get the associated transaction ID.
    pub fn transaction_id(&self) -> Option<&PayrixId> {
        self.inner.txn.as_ref()
    }
}

// =============================================================================
// Section 3: Evidence Types
// =============================================================================

/// Evidence document for chargeback representment.
///
/// Each document must be under 1 MB and in a supported format.
#[derive(Debug, Clone)]
pub struct EvidenceDocument {
    /// Document filename.
    pub name: String,
    /// Document content as bytes.
    pub content: Vec<u8>,
    /// MIME type (e.g., "application/pdf", "image/tiff").
    pub mime_type: String,
}

impl EvidenceDocument {
    /// Create a new evidence document.
    ///
    /// # Arguments
    ///
    /// * `name` - The filename (e.g., "receipt.pdf")
    /// * `content` - The file content as bytes
    /// * `mime_type` - The MIME type (e.g., "application/pdf")
    pub fn new(name: impl Into<String>, content: Vec<u8>, mime_type: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            content,
            mime_type: mime_type.into(),
        }
    }

    /// Get the size of this document in bytes.
    pub fn size(&self) -> usize {
        self.content.len()
    }

    /// Validate this document against Payrix requirements.
    pub fn validate(&self) -> Result<()> {
        if self.content.len() > MAX_DOCUMENT_SIZE {
            return Err(Error::Validation(format!(
                "Document '{}' exceeds maximum size of {} bytes (actual: {} bytes)",
                self.name,
                MAX_DOCUMENT_SIZE,
                self.content.len()
            )));
        }

        // Validate MIME type
        let valid_types = [
            "image/tiff",
            "image/tif",
            "application/pdf",
            "image/png",
            "image/jpeg",
            "image/jpg",
            "image/gif",
        ];

        if !valid_types.contains(&self.mime_type.as_str()) {
            return Err(Error::Validation(format!(
                "Document '{}' has unsupported MIME type '{}'. Supported: {:?}",
                self.name, self.mime_type, valid_types
            )));
        }

        Ok(())
    }
}

/// Evidence for chargeback representment.
///
/// Contains a required message explaining the dispute and optional
/// supporting documents.
///
/// # Example
///
/// ```
/// use payrix::workflows::dispute_handling::Evidence;
///
/// let evidence = Evidence::new("Customer received the goods as described per tracking #1234")
///     .with_document("receipt.pdf", vec![/* pdf bytes */], "application/pdf")
///     .with_document("tracking.png", vec![/* image bytes */], "image/png");
/// ```
#[derive(Debug, Clone)]
pub struct Evidence {
    /// Required message explaining the dispute response.
    pub message: String,
    /// Supporting documents (max 8, max 8 MB total).
    pub documents: Vec<EvidenceDocument>,
}

impl Evidence {
    /// Create new evidence with a message.
    ///
    /// # Arguments
    ///
    /// * `message` - Explanation of why the chargeback should be reversed
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            documents: Vec::new(),
        }
    }

    /// Add a document to this evidence.
    ///
    /// # Arguments
    ///
    /// * `name` - The filename
    /// * `content` - The file content as bytes
    /// * `mime_type` - The MIME type
    pub fn with_document(
        mut self,
        name: impl Into<String>,
        content: Vec<u8>,
        mime_type: impl Into<String>,
    ) -> Self {
        self.documents
            .push(EvidenceDocument::new(name, content, mime_type));
        self
    }

    /// Add a pre-built evidence document.
    pub fn with_evidence_document(mut self, doc: EvidenceDocument) -> Self {
        self.documents.push(doc);
        self
    }

    /// Get the total size of all documents in bytes.
    pub fn total_size(&self) -> usize {
        self.documents.iter().map(|d| d.size()).sum()
    }

    /// Validate this evidence against Payrix requirements.
    ///
    /// Checks:
    /// - Message is not empty
    /// - Maximum 8 documents
    /// - Each document under 1 MB
    /// - Total size under 8 MB
    /// - All MIME types are supported
    pub fn validate(&self) -> Result<()> {
        if self.message.trim().is_empty() {
            return Err(Error::Validation(
                "Evidence message cannot be empty".to_string(),
            ));
        }

        if self.documents.len() > MAX_DOCUMENTS {
            return Err(Error::Validation(format!(
                "Too many documents: {} (maximum: {})",
                self.documents.len(),
                MAX_DOCUMENTS
            )));
        }

        let total_size = self.total_size();
        if total_size > MAX_TOTAL_SIZE {
            return Err(Error::Validation(format!(
                "Total document size {} bytes exceeds maximum of {} bytes",
                total_size, MAX_TOTAL_SIZE
            )));
        }

        for doc in &self.documents {
            doc.validate()?;
        }

        Ok(())
    }
}

// =============================================================================
// Section 3b: Evidence Helper Functions
// =============================================================================

/// Create an evidence document from raw bytes.
///
/// Automatically infers MIME type from file extension.
///
/// # Arguments
///
/// * `filename` - The filename with extension (e.g., "receipt.pdf")
/// * `content` - The file content as bytes
pub fn evidence_from_bytes(filename: &str, content: Vec<u8>) -> Result<EvidenceDocument> {
    let mime_type = mime_type_from_extension(filename)?;
    let doc = EvidenceDocument::new(filename, content, mime_type);
    doc.validate()?;
    Ok(doc)
}

/// Create an evidence document from a file path.
///
/// Reads the file and automatically infers MIME type from extension.
///
/// # Arguments
///
/// * `path` - Path to the file
pub fn evidence_from_path(path: impl AsRef<Path>) -> Result<EvidenceDocument> {
    let path = path.as_ref();
    let filename = path
        .file_name()
        .and_then(|n| n.to_str())
        .ok_or_else(|| Error::Validation("Invalid file path".to_string()))?;

    let content = std::fs::read(path).map_err(|e| Error::Io(e.to_string()))?;
    evidence_from_bytes(filename, content)
}

/// Create an evidence document from a base64 data URL.
///
/// Parses data URLs in the format: `data:[<mediatype>][;base64],<data>`
///
/// This is commonly used when receiving file uploads from browser JavaScript
/// using `FileReader.readAsDataURL()`.
///
/// # Arguments
///
/// * `filename` - The filename to use for this document
/// * `data_url` - The base64 data URL (e.g., "data:application/pdf;base64,JVBERi0...")
///
/// # Example
///
/// ```
/// use payrix::workflows::dispute_handling::evidence_from_base64_url;
///
/// // Parse a base64-encoded PDF from a browser upload
/// let doc = evidence_from_base64_url(
///     "receipt.pdf",
///     "data:application/pdf;base64,JVBERi0xLjQK"
/// );
/// ```
pub fn evidence_from_base64_url(filename: &str, data_url: &str) -> Result<EvidenceDocument> {
    // Parse data URL format: data:[<mediatype>][;base64],<data>
    let data_url = data_url
        .strip_prefix("data:")
        .ok_or_else(|| Error::Validation("Invalid data URL: must start with 'data:'".to_string()))?;

    let (header, data) = data_url.split_once(',').ok_or_else(|| {
        Error::Validation("Invalid data URL: missing comma separator".to_string())
    })?;

    // Parse header parts (e.g., "application/pdf;base64" or just "application/pdf")
    let parts: Vec<&str> = header.split(';').collect();
    let mime_type = parts.first().unwrap_or(&"application/octet-stream");

    // Check if base64 encoded
    let is_base64 = parts.iter().any(|p| *p == "base64");
    if !is_base64 {
        return Err(Error::Validation(
            "Only base64-encoded data URLs are supported".to_string(),
        ));
    }

    // Decode base64
    use base64::{engine::general_purpose::STANDARD, Engine};
    let content = STANDARD.decode(data).map_err(|e| {
        Error::Validation(format!("Invalid base64 in data URL: {}", e))
    })?;

    let doc = EvidenceDocument::new(filename, content, *mime_type);
    doc.validate()?;
    Ok(doc)
}

/// Infer MIME type from file extension.
fn mime_type_from_extension(filename: &str) -> Result<&'static str> {
    let ext = filename
        .rsplit('.')
        .next()
        .map(|e| e.to_lowercase())
        .unwrap_or_default();

    match ext.as_str() {
        "pdf" => Ok("application/pdf"),
        "tiff" | "tif" => Ok("image/tiff"),
        "png" => Ok("image/png"),
        "jpg" | "jpeg" => Ok("image/jpeg"),
        "gif" => Ok("image/gif"),
        _ => Err(Error::Validation(format!(
            "Unsupported file extension '{}'. Supported: pdf, tiff, tif, png, jpg, jpeg, gif",
            ext
        ))),
    }
}

// =============================================================================
// Section 4: State-Specific Methods
// =============================================================================

impl TypedChargeback<First> {
    /// Submit evidence to represent (dispute) this chargeback.
    ///
    /// This sends a response to the issuer with your evidence supporting
    /// that the transaction was valid.
    ///
    /// # Arguments
    ///
    /// * `client` - The Payrix client
    /// * `evidence` - Evidence supporting your case
    ///
    /// # Returns
    ///
    /// A `TypedChargeback<Representment>` representing the new state.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Evidence validation fails
    /// - The chargeback is not actionable
    /// - The API call fails
    pub async fn represent(
        self,
        client: &PayrixClient,
        evidence: Evidence,
    ) -> Result<TypedChargeback<Representment>> {
        evidence.validate()?;

        if !self.inner.actionable {
            return Err(Error::Validation(
                "Chargeback is not currently actionable".to_string(),
            ));
        }

        // Create the chargeback message
        let message = CreateChargebackMessage {
            chargeback: self.inner.id.to_string(),
            message_type: Some(ChargebackMessageType::Represent),
            subject: Some("Representment".to_string()),
            message: Some(evidence.message),
        };

        let response: ChargebackMessage = client
            .create(EntityType::ChargebackMessages, &message)
            .await?;

        // Upload documents attached to this chargeback message
        for doc in evidence.documents {
            let document_type = mime_type_to_document_type(&doc.mime_type);
            let encoded_content = base64::engine::general_purpose::STANDARD.encode(&doc.content);

            let new_doc = CreateChargebackDocument {
                chargeback: self.inner.id.to_string(),
                chargeback_message: Some(response.id.to_string()),
                name: Some(doc.name),
                document_type: Some(document_type),
                mime_type: Some(doc.mime_type),
                description: None,
                data: Some(encoded_content),
            };

            let _doc_response: ChargebackDocument = client
                .create(EntityType::ChargebackDocuments, &new_doc)
                .await?;
        }

        // Reload the chargeback to get the updated state
        let updated: Chargeback = client
            .get_one(EntityType::Chargebacks, self.inner.id.as_str())
            .await?
            .ok_or_else(|| Error::NotFound("Chargeback not found after update".to_string()))?;

        Ok(TypedChargeback::new(updated))
    }

    /// Accept liability for this chargeback.
    ///
    /// This acknowledges the chargeback and stops the dispute process.
    /// The chargeback amount will be deducted from your account.
    ///
    /// # Arguments
    ///
    /// * `client` - The Payrix client
    ///
    /// # Returns
    ///
    /// A `TypedChargeback<Terminal>` representing the closed state.
    pub async fn accept_liability(self, client: &PayrixClient) -> Result<TypedChargeback<Terminal>> {
        if !self.inner.actionable {
            return Err(Error::Validation(
                "Chargeback is not currently actionable".to_string(),
            ));
        }

        let message = CreateChargebackMessage {
            chargeback: self.inner.id.to_string(),
            message_type: Some(ChargebackMessageType::AcceptLiability),
            subject: Some("Accept Liability".to_string()),
            message: Some("Merchant accepts liability for this chargeback".to_string()),
        };

        let _response: ChargebackMessage = client
            .create(EntityType::ChargebackMessages, &message)
            .await?;

        let updated: Chargeback = client
            .get_one(EntityType::Chargebacks, self.inner.id.as_str())
            .await?
            .ok_or_else(|| Error::NotFound("Chargeback not found after update".to_string()))?;

        Ok(TypedChargeback::new(updated))
    }
}

impl TypedChargeback<PreArbitration> {
    /// Request arbitration from the card network.
    ///
    /// This escalates the dispute to the card network (Visa, Mastercard, etc.)
    /// for a final binding decision. There is typically a fee for arbitration,
    /// which may be refunded if you win.
    ///
    /// # Arguments
    ///
    /// * `client` - The Payrix client
    ///
    /// # Returns
    ///
    /// A `TypedChargeback<Arbitration>` representing the arbitration stage.
    pub async fn request_arbitration(
        self,
        client: &PayrixClient,
    ) -> Result<TypedChargeback<Arbitration>> {
        if !self.inner.actionable {
            return Err(Error::Validation(
                "Chargeback is not currently actionable".to_string(),
            ));
        }

        let message = CreateChargebackMessage {
            chargeback: self.inner.id.to_string(),
            message_type: Some(ChargebackMessageType::RequestArbitration),
            subject: Some("Request Arbitration".to_string()),
            message: Some("Merchant requests card network arbitration".to_string()),
        };

        let _response: ChargebackMessage = client
            .create(EntityType::ChargebackMessages, &message)
            .await?;

        let updated: Chargeback = client
            .get_one(EntityType::Chargebacks, self.inner.id.as_str())
            .await?
            .ok_or_else(|| Error::NotFound("Chargeback not found after update".to_string()))?;

        Ok(TypedChargeback::new(updated))
    }

    /// Submit additional evidence in pre-arbitration.
    ///
    /// Some card networks allow submitting additional evidence during
    /// pre-arbitration before escalating to full arbitration.
    pub async fn represent(
        self,
        client: &PayrixClient,
        evidence: Evidence,
    ) -> Result<TypedChargeback<Representment>> {
        evidence.validate()?;

        if !self.inner.actionable {
            return Err(Error::Validation(
                "Chargeback is not currently actionable".to_string(),
            ));
        }

        let message = CreateChargebackMessage {
            chargeback: self.inner.id.to_string(),
            message_type: Some(ChargebackMessageType::Represent),
            subject: Some("Pre-Arbitration Response".to_string()),
            message: Some(evidence.message),
        };

        let response: ChargebackMessage = client
            .create(EntityType::ChargebackMessages, &message)
            .await?;

        // Upload documents attached to this chargeback message
        for doc in evidence.documents {
            let document_type = mime_type_to_document_type(&doc.mime_type);
            let encoded_content = base64::engine::general_purpose::STANDARD.encode(&doc.content);

            let new_doc = CreateChargebackDocument {
                chargeback: self.inner.id.to_string(),
                chargeback_message: Some(response.id.to_string()),
                name: Some(doc.name),
                document_type: Some(document_type),
                mime_type: Some(doc.mime_type),
                description: None,
                data: Some(encoded_content),
            };

            let _doc_response: ChargebackDocument = client
                .create(EntityType::ChargebackDocuments, &new_doc)
                .await?;
        }

        let updated: Chargeback = client
            .get_one(EntityType::Chargebacks, self.inner.id.as_str())
            .await?
            .ok_or_else(|| Error::NotFound("Chargeback not found after update".to_string()))?;

        Ok(TypedChargeback::new(updated))
    }

    /// Accept liability for this chargeback.
    pub async fn accept_liability(self, client: &PayrixClient) -> Result<TypedChargeback<Terminal>> {
        if !self.inner.actionable {
            return Err(Error::Validation(
                "Chargeback is not currently actionable".to_string(),
            ));
        }

        let message = CreateChargebackMessage {
            chargeback: self.inner.id.to_string(),
            message_type: Some(ChargebackMessageType::AcceptLiability),
            subject: Some("Accept Liability".to_string()),
            message: Some("Merchant accepts liability for this chargeback".to_string()),
        };

        let _response: ChargebackMessage = client
            .create(EntityType::ChargebackMessages, &message)
            .await?;

        let updated: Chargeback = client
            .get_one(EntityType::Chargebacks, self.inner.id.as_str())
            .await?
            .ok_or_else(|| Error::NotFound("Chargeback not found after update".to_string()))?;

        Ok(TypedChargeback::new(updated))
    }
}

impl TypedChargeback<SecondChargeback> {
    /// Submit evidence to represent this second chargeback.
    pub async fn represent(
        self,
        client: &PayrixClient,
        evidence: Evidence,
    ) -> Result<TypedChargeback<Representment>> {
        evidence.validate()?;

        if !self.inner.actionable {
            return Err(Error::Validation(
                "Chargeback is not currently actionable".to_string(),
            ));
        }

        let message = CreateChargebackMessage {
            chargeback: self.inner.id.to_string(),
            message_type: Some(ChargebackMessageType::Represent),
            subject: Some("Second Chargeback Representment".to_string()),
            message: Some(evidence.message),
        };

        let response: ChargebackMessage = client
            .create(EntityType::ChargebackMessages, &message)
            .await?;

        // Upload documents attached to this chargeback message
        for doc in evidence.documents {
            let document_type = mime_type_to_document_type(&doc.mime_type);
            let encoded_content = base64::engine::general_purpose::STANDARD.encode(&doc.content);

            let new_doc = CreateChargebackDocument {
                chargeback: self.inner.id.to_string(),
                chargeback_message: Some(response.id.to_string()),
                name: Some(doc.name),
                document_type: Some(document_type),
                mime_type: Some(doc.mime_type),
                description: None,
                data: Some(encoded_content),
            };

            let _doc_response: ChargebackDocument = client
                .create(EntityType::ChargebackDocuments, &new_doc)
                .await?;
        }

        let updated: Chargeback = client
            .get_one(EntityType::Chargebacks, self.inner.id.as_str())
            .await?
            .ok_or_else(|| Error::NotFound("Chargeback not found after update".to_string()))?;

        Ok(TypedChargeback::new(updated))
    }

    /// Accept liability for this chargeback.
    pub async fn accept_liability(self, client: &PayrixClient) -> Result<TypedChargeback<Terminal>> {
        if !self.inner.actionable {
            return Err(Error::Validation(
                "Chargeback is not currently actionable".to_string(),
            ));
        }

        let message = CreateChargebackMessage {
            chargeback: self.inner.id.to_string(),
            message_type: Some(ChargebackMessageType::AcceptLiability),
            subject: Some("Accept Liability".to_string()),
            message: Some("Merchant accepts liability for this chargeback".to_string()),
        };

        let _response: ChargebackMessage = client
            .create(EntityType::ChargebackMessages, &message)
            .await?;

        let updated: Chargeback = client
            .get_one(EntityType::Chargebacks, self.inner.id.as_str())
            .await?
            .ok_or_else(|| Error::NotFound("Chargeback not found after update".to_string()))?;

        Ok(TypedChargeback::new(updated))
    }
}

// =============================================================================
// Section 5: Runtime Bridge
// =============================================================================

/// An active (non-terminal) chargeback dispute.
///
/// This enum dispatches to the appropriate typed state based on the
/// chargeback's current cycle.
#[derive(Debug, Clone)]
pub enum ActiveDispute {
    /// Retrieval stage - awaiting first chargeback.
    Retrieval(TypedChargeback<Retrieval>),
    /// First chargeback stage - can represent or accept.
    First(TypedChargeback<First>),
    /// Representment stage - awaiting issuer decision.
    Representment(TypedChargeback<Representment>),
    /// Pre-arbitration stage - can arbitrate, represent, or accept.
    PreArbitration(TypedChargeback<PreArbitration>),
    /// Second chargeback stage - can represent or accept.
    SecondChargeback(TypedChargeback<SecondChargeback>),
    /// Arbitration stage - awaiting card network decision.
    Arbitration(TypedChargeback<Arbitration>),
}

impl ActiveDispute {
    /// Get the underlying chargeback ID.
    pub fn id(&self) -> &PayrixId {
        match self {
            Self::Retrieval(c) => c.id(),
            Self::First(c) => c.id(),
            Self::Representment(c) => c.id(),
            Self::PreArbitration(c) => c.id(),
            Self::SecondChargeback(c) => c.id(),
            Self::Arbitration(c) => c.id(),
        }
    }

    /// Get the state name.
    pub fn state_name(&self) -> &'static str {
        match self {
            Self::Retrieval(_) => Retrieval::state_name(),
            Self::First(_) => First::state_name(),
            Self::Representment(_) => Representment::state_name(),
            Self::PreArbitration(_) => PreArbitration::state_name(),
            Self::SecondChargeback(_) => SecondChargeback::state_name(),
            Self::Arbitration(_) => Arbitration::state_name(),
        }
    }

    /// Get a reference to the underlying chargeback data.
    pub fn inner(&self) -> &Chargeback {
        match self {
            Self::Retrieval(c) => c.inner(),
            Self::First(c) => c.inner(),
            Self::Representment(c) => c.inner(),
            Self::PreArbitration(c) => c.inner(),
            Self::SecondChargeback(c) => c.inner(),
            Self::Arbitration(c) => c.inner(),
        }
    }
}

/// A chargeback dispute - either active or terminal.
///
/// This is the primary entry point for working with chargebacks.
/// Use [`ChargebackDispute::load`] to fetch a chargeback from the API.
#[derive(Debug, Clone)]
pub enum ChargebackDispute {
    /// An active dispute that may have available actions.
    Active(ActiveDispute),
    /// A terminal dispute that is closed.
    Terminal(TypedChargeback<Terminal>),
}

impl ChargebackDispute {
    /// Load a chargeback from the Payrix API.
    ///
    /// This is the primary entry point for working with chargebacks.
    /// The returned dispute is typed according to the chargeback's current state.
    ///
    /// # Arguments
    ///
    /// * `client` - The Payrix client
    /// * `id` - The chargeback ID
    ///
    /// # Returns
    ///
    /// A `ChargebackDispute` in the appropriate state.
    pub async fn load(client: &PayrixClient, id: &str) -> Result<Self> {
        let chargeback: Chargeback = client
            .get_one(EntityType::Chargebacks, id)
            .await?
            .ok_or_else(|| Error::NotFound(format!("Chargeback not found: {}", id)))?;

        Ok(Self::from_chargeback(chargeback))
    }

    /// Convert a raw chargeback into a typed dispute.
    ///
    /// Useful when you have chargeback data from a webhook or other source.
    pub fn from_chargeback(chargeback: Chargeback) -> Self {
        // Check if terminal first
        if let Some(status) = &chargeback.status {
            match status {
                ChargebackStatusValue::Closed
                | ChargebackStatusValue::Won
                | ChargebackStatusValue::Lost => {
                    return Self::Terminal(TypedChargeback::new(chargeback));
                }
                _ => {}
            }
        }

        // Check cycle for terminal states
        if let Some(cycle) = &chargeback.cycle {
            match cycle {
                ChargebackCycle::ArbitrationWon
                | ChargebackCycle::ArbitrationLost
                | ChargebackCycle::ArbitrationSplit
                | ChargebackCycle::Reversal => {
                    return Self::Terminal(TypedChargeback::new(chargeback));
                }
                _ => {}
            }
        }

        // Map to active state based on cycle
        let active = match chargeback.cycle {
            Some(ChargebackCycle::Retrieval) => {
                ActiveDispute::Retrieval(TypedChargeback::new(chargeback))
            }
            Some(ChargebackCycle::First) => ActiveDispute::First(TypedChargeback::new(chargeback)),
            Some(ChargebackCycle::Representment) => {
                ActiveDispute::Representment(TypedChargeback::new(chargeback))
            }
            Some(ChargebackCycle::PreArbitration)
            | Some(ChargebackCycle::IssuerDeclinedPreArbitration)
            | Some(ChargebackCycle::ResponseToIssuerPreArbitration)
            | Some(ChargebackCycle::MerchantDeclinedPreArbitration) => {
                ActiveDispute::PreArbitration(TypedChargeback::new(chargeback))
            }
            Some(ChargebackCycle::Arbitration)
            | Some(ChargebackCycle::PreCompliance)
            | Some(ChargebackCycle::Compliance) => {
                ActiveDispute::Arbitration(TypedChargeback::new(chargeback))
            }
            // Default to First for unknown or None
            None => ActiveDispute::First(TypedChargeback::new(chargeback)),
            _ => ActiveDispute::First(TypedChargeback::new(chargeback)),
        };

        Self::Active(active)
    }

    /// Refresh this dispute with the latest data from the API.
    ///
    /// Returns a new `ChargebackDispute` with the updated state.
    pub async fn refresh(&self, client: &PayrixClient) -> Result<Self> {
        Self::load(client, self.id().as_str()).await
    }

    /// Get the chargeback ID.
    pub fn id(&self) -> &PayrixId {
        match self {
            Self::Active(active) => active.id(),
            Self::Terminal(terminal) => terminal.id(),
        }
    }

    /// Get the state name.
    pub fn state_name(&self) -> &'static str {
        match self {
            Self::Active(active) => active.state_name(),
            Self::Terminal(_) => Terminal::state_name(),
        }
    }

    /// Get a reference to the underlying chargeback data.
    pub fn inner(&self) -> &Chargeback {
        match self {
            Self::Active(active) => active.inner(),
            Self::Terminal(terminal) => terminal.inner(),
        }
    }

    /// Check if this dispute is terminal (closed).
    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Terminal(_))
    }

    /// Check if this dispute is active (not closed).
    pub fn is_active(&self) -> bool {
        matches!(self, Self::Active(_))
    }
}

// =============================================================================
// Section 6: Convenience Functions
// =============================================================================

/// Get all actionable chargebacks for a merchant.
///
/// Returns chargebacks that are open and have available actions.
///
/// # Arguments
///
/// * `client` - The Payrix client
/// * `merchant_id` - The merchant ID to filter by
pub async fn get_actionable_disputes(
    client: &PayrixClient,
    merchant_id: &str,
) -> Result<Vec<ChargebackDispute>> {
    let search = format!(
        "merchant[equals]={}&status[equals]=open&actionable[equals]=1",
        merchant_id
    );

    let chargebacks: Vec<Chargeback> = client.search(EntityType::Chargebacks, &search).await?;

    Ok(chargebacks
        .into_iter()
        .map(ChargebackDispute::from_chargeback)
        .collect())
}

/// Get chargebacks for a merchant filtered by cycle.
///
/// # Arguments
///
/// * `client` - The Payrix client
/// * `merchant_id` - The merchant ID to filter by
/// * `cycle` - The chargeback cycle to filter by
pub async fn get_disputes_by_cycle(
    client: &PayrixClient,
    merchant_id: &str,
    cycle: ChargebackCycle,
) -> Result<Vec<ChargebackDispute>> {
    let cycle_str = match cycle {
        ChargebackCycle::Retrieval => "retrieval",
        ChargebackCycle::First => "first",
        ChargebackCycle::Representment => "representment",
        ChargebackCycle::PreArbitration => "preArbitration",
        ChargebackCycle::Arbitration => "arbitration",
        _ => return Ok(Vec::new()), // Terminal states don't need searching
    };

    let search = format!(
        "merchant[equals]={}&cycle[equals]={}",
        merchant_id, cycle_str
    );

    let chargebacks: Vec<Chargeback> = client.search(EntityType::Chargebacks, &search).await?;

    Ok(chargebacks
        .into_iter()
        .map(ChargebackDispute::from_chargeback)
        .collect())
}

/// Get all chargebacks for a specific transaction.
///
/// # Arguments
///
/// * `client` - The Payrix client
/// * `transaction_id` - The transaction ID
pub async fn get_disputes_for_transaction(
    client: &PayrixClient,
    transaction_id: &str,
) -> Result<Vec<ChargebackDispute>> {
    let search = format!("txn[equals]={}", transaction_id);

    let chargebacks: Vec<Chargeback> = client.search(EntityType::Chargebacks, &search).await?;

    Ok(chargebacks
        .into_iter()
        .map(ChargebackDispute::from_chargeback)
        .collect())
}

// =============================================================================
// Section 6b: Helper Functions
// =============================================================================

/// Convert a MIME type to a ChargebackDocumentType.
fn mime_type_to_document_type(mime_type: &str) -> ChargebackDocumentType {
    match mime_type.to_lowercase().as_str() {
        "application/pdf" => ChargebackDocumentType::Pdf,
        "image/tiff" | "image/tif" => ChargebackDocumentType::Tiff,
        "image/png" => ChargebackDocumentType::Png,
        "image/jpeg" | "image/jpg" => ChargebackDocumentType::Jpg,
        "image/gif" => ChargebackDocumentType::Image,
        "text/plain" => ChargebackDocumentType::Text,
        _ if mime_type.starts_with("image/") => ChargebackDocumentType::Image,
        _ => ChargebackDocumentType::Other,
    }
}

// =============================================================================
// Section 7: Tests
// =============================================================================

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

    // =========================================================================
    // State Marker Tests
    // =========================================================================

    #[test]
    fn test_state_names() {
        assert_eq!(Retrieval::state_name(), "retrieval");
        assert_eq!(First::state_name(), "first");
        assert_eq!(Representment::state_name(), "representment");
        assert_eq!(PreArbitration::state_name(), "preArbitration");
        assert_eq!(SecondChargeback::state_name(), "secondChargeback");
        assert_eq!(Arbitration::state_name(), "arbitration");
        assert_eq!(Terminal::state_name(), "terminal");
    }

    // =========================================================================
    // Evidence Validation Tests
    // =========================================================================

    #[test]
    fn test_evidence_creation() {
        let evidence = Evidence::new("Test message");
        assert_eq!(evidence.message, "Test message");
        assert!(evidence.documents.is_empty());
    }

    #[test]
    fn test_evidence_with_document() {
        let evidence = Evidence::new("Test message")
            .with_document("receipt.pdf", vec![1, 2, 3], "application/pdf");

        assert_eq!(evidence.documents.len(), 1);
        assert_eq!(evidence.documents[0].name, "receipt.pdf");
        assert_eq!(evidence.documents[0].mime_type, "application/pdf");
    }

    #[test]
    fn test_evidence_validation_empty_message() {
        let evidence = Evidence::new("");
        let result = evidence.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("cannot be empty"));
    }

    #[test]
    fn test_evidence_validation_whitespace_message() {
        let evidence = Evidence::new("   ");
        let result = evidence.validate();
        assert!(result.is_err());
    }

    #[test]
    fn test_evidence_validation_too_many_documents() {
        let mut evidence = Evidence::new("Test");
        for i in 0..9 {
            evidence = evidence.with_document(
                format!("doc{}.pdf", i),
                vec![1],
                "application/pdf",
            );
        }

        let result = evidence.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Too many documents"));
    }

    #[test]
    fn test_evidence_validation_document_too_large() {
        let large_content = vec![0u8; MAX_DOCUMENT_SIZE + 1];
        let evidence = Evidence::new("Test").with_document("large.pdf", large_content, "application/pdf");

        let result = evidence.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("exceeds maximum size"));
    }

    #[test]
    fn test_evidence_validation_invalid_mime_type() {
        let evidence = Evidence::new("Test").with_document("file.exe", vec![1], "application/exe");

        let result = evidence.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("unsupported MIME type"));
    }

    #[test]
    fn test_evidence_validation_valid() {
        let evidence = Evidence::new("Valid evidence message")
            .with_document("receipt.pdf", vec![1, 2, 3], "application/pdf")
            .with_document("photo.png", vec![4, 5, 6], "image/png");

        assert!(evidence.validate().is_ok());
    }

    #[test]
    fn test_evidence_total_size() {
        let evidence = Evidence::new("Test")
            .with_document("a.pdf", vec![1, 2, 3], "application/pdf")
            .with_document("b.pdf", vec![4, 5, 6, 7], "application/pdf");

        assert_eq!(evidence.total_size(), 7);
    }

    // =========================================================================
    // Evidence Helper Tests
    // =========================================================================

    #[test]
    fn test_mime_type_from_extension() {
        assert_eq!(mime_type_from_extension("file.pdf").unwrap(), "application/pdf");
        assert_eq!(mime_type_from_extension("file.PDF").unwrap(), "application/pdf");
        assert_eq!(mime_type_from_extension("file.tiff").unwrap(), "image/tiff");
        assert_eq!(mime_type_from_extension("file.tif").unwrap(), "image/tiff");
        assert_eq!(mime_type_from_extension("file.png").unwrap(), "image/png");
        assert_eq!(mime_type_from_extension("file.jpg").unwrap(), "image/jpeg");
        assert_eq!(mime_type_from_extension("file.jpeg").unwrap(), "image/jpeg");
        assert_eq!(mime_type_from_extension("file.gif").unwrap(), "image/gif");
    }

    #[test]
    fn test_mime_type_unsupported() {
        assert!(mime_type_from_extension("file.exe").is_err());
        assert!(mime_type_from_extension("file.doc").is_err());
    }

    #[test]
    fn test_evidence_from_bytes() {
        let doc = evidence_from_bytes("receipt.pdf", vec![1, 2, 3]).unwrap();
        assert_eq!(doc.name, "receipt.pdf");
        assert_eq!(doc.mime_type, "application/pdf");
    }

    #[test]
    fn test_evidence_from_base64_url() {
        // "test" in base64 is "dGVzdA=="
        let doc = evidence_from_base64_url("file.pdf", "data:application/pdf;base64,dGVzdA==").unwrap();
        assert_eq!(doc.name, "file.pdf");
        assert_eq!(doc.mime_type, "application/pdf");
        assert_eq!(doc.content, b"test");
    }

    #[test]
    fn test_evidence_from_base64_url_invalid() {
        // Missing data: prefix
        assert!(evidence_from_base64_url("file.pdf", "application/pdf;base64,dGVzdA==").is_err());

        // Missing comma
        assert!(evidence_from_base64_url("file.pdf", "data:application/pdf;base64").is_err());

        // Not base64 encoded
        assert!(evidence_from_base64_url("file.pdf", "data:application/pdf,notbase64").is_err());
    }

    // =========================================================================
    // ChargebackDispute Tests
    // =========================================================================

    fn make_test_chargeback(cycle: Option<ChargebackCycle>, status: Option<ChargebackStatusValue>) -> Chargeback {
        Chargeback {
            // t1_chb_12345678901234567890123 is exactly 30 characters
            id: "t1_chb_12345678901234567890123".parse().unwrap(),
            created: None,
            modified: None,
            creator: None,
            modifier: None,
            merchant: None,
            txn: None,
            mid: None,
            description: None,
            total: Some(10000),
            represented_total: None,
            cycle,
            currency: Some("USD".to_string()),
            platform: None,
            payment_method: None,
            reference: None,
            reason: Some("Disputed charge".to_string()),
            reason_code: Some("4853".to_string()),
            issued: None,
            received: None,
            reply: Some(20240130),
            bank_ref: None,
            chargeback_ref: None,
            status,
            last_status_change: None,
            actionable: true,
            shadow: false,
            inactive: false,
            frozen: false,
            #[cfg(not(feature = "sqlx"))]
            assessments: None,
            #[cfg(not(feature = "sqlx"))]
            chargeback_documents: None,
            #[cfg(not(feature = "sqlx"))]
            chargeback_messages: None,
            #[cfg(not(feature = "sqlx"))]
            chargeback_statuses: None,
            #[cfg(not(feature = "sqlx"))]
            entries: None,
            #[cfg(not(feature = "sqlx"))]
            pending_entry: None,
        }
    }

    #[test]
    fn test_from_chargeback_first() {
        let cb = make_test_chargeback(Some(ChargebackCycle::First), Some(ChargebackStatusValue::Open));
        let dispute = ChargebackDispute::from_chargeback(cb);

        assert!(dispute.is_active());
        assert!(!dispute.is_terminal());
        assert_eq!(dispute.state_name(), "first");

        if let ChargebackDispute::Active(ActiveDispute::First(_)) = dispute {
            // Good - it's in First state
        } else {
            panic!("Expected First state");
        }
    }

    #[test]
    fn test_from_chargeback_pre_arbitration() {
        let cb = make_test_chargeback(Some(ChargebackCycle::PreArbitration), Some(ChargebackStatusValue::Open));
        let dispute = ChargebackDispute::from_chargeback(cb);

        assert!(dispute.is_active());
        assert_eq!(dispute.state_name(), "preArbitration");

        if let ChargebackDispute::Active(ActiveDispute::PreArbitration(_)) = dispute {
            // Good - it's in PreArbitration state
        } else {
            panic!("Expected PreArbitration state");
        }
    }

    #[test]
    fn test_from_chargeback_terminal_won() {
        let cb = make_test_chargeback(Some(ChargebackCycle::ArbitrationWon), Some(ChargebackStatusValue::Won));
        let dispute = ChargebackDispute::from_chargeback(cb);

        assert!(dispute.is_terminal());
        assert!(!dispute.is_active());
        assert_eq!(dispute.state_name(), "terminal");
    }

    #[test]
    fn test_from_chargeback_terminal_closed() {
        let cb = make_test_chargeback(Some(ChargebackCycle::First), Some(ChargebackStatusValue::Closed));
        let dispute = ChargebackDispute::from_chargeback(cb);

        assert!(dispute.is_terminal());
    }

    #[test]
    fn test_typed_chargeback_accessors() {
        let cb = make_test_chargeback(Some(ChargebackCycle::First), Some(ChargebackStatusValue::Open));
        let dispute = ChargebackDispute::from_chargeback(cb);

        assert_eq!(dispute.inner().total, Some(10000));
        assert_eq!(dispute.inner().reason_code.as_deref(), Some("4853"));
        assert_eq!(dispute.inner().reply, Some(20240130));
    }

    #[test]
    fn test_active_dispute_id() {
        let cb = make_test_chargeback(Some(ChargebackCycle::First), Some(ChargebackStatusValue::Open));
        let id = cb.id.clone();
        let dispute = ChargebackDispute::from_chargeback(cb);

        assert_eq!(dispute.id().as_str(), id.as_str());
    }

    // =========================================================================
    // Mock Data Tests (tests/mock_data/chargebacks.json)
    // =========================================================================

    /// Test that we can deserialize and process real Payrix chargeback responses.
    #[test]
    fn test_from_mock_data_chargebacks() {
        // This is the raw JSON from tests/mock_data/chargebacks.json
        let mock_json = r#"{
            "response": {
                "data": [
                    {
                        "id": "t1_chb_6616a9f7c19a47bea938957",
                        "created": "2024-04-10 11:02:15.8016",
                        "modified": "2024-06-20 13:34:48.1638",
                        "creator": "t1_log_618afcdc2543bcabeaf184e",
                        "modifier": "t1_log_657202cb80bcfc9df78676f",
                        "merchant": "t1_mer_65f097a2848a4ceae39b6ee",
                        "txn": "t1_txn_6616a938dab5e92858d4e0a",
                        "description": "",
                        "total": 30000,
                        "representedTotal": null,
                        "cycle": "first",
                        "currency": "USD",
                        "ref": "j3JeC74OWBL000065",
                        "reason": "Missing Signature",
                        "reasonCode": "F14",
                        "issued": 20240409,
                        "received": null,
                        "reply": 20241231,
                        "bankRef": null,
                        "chargebackRef": null,
                        "status": "closed",
                        "inactive": 0,
                        "frozen": 0,
                        "lastStatusChange": "t1_chs_66746838179377f5d203381",
                        "actionable": 1,
                        "paymentMethod": 4,
                        "shadow": 0
                    },
                    {
                        "id": "t1_chb_6616a9de06fd751e5ae91e5",
                        "created": "2024-04-10 11:01:50.0337",
                        "modified": "2024-04-10 11:01:50.1415",
                        "creator": "t1_log_618afcdc2543bcabeaf184e",
                        "modifier": "t1_log_618afcdc2543bcabeaf184e",
                        "merchant": "t1_mer_65f097a2848a4ceae39b6ee",
                        "txn": "t1_txn_6616a925e796be0ebf69dd9",
                        "description": "",
                        "total": 20000,
                        "representedTotal": null,
                        "cycle": "first",
                        "currency": "USD",
                        "ref": "j3JeC74OWBL000064",
                        "reason": "Missing Signature",
                        "reasonCode": "F14",
                        "issued": 20240409,
                        "received": null,
                        "reply": 20241231,
                        "bankRef": null,
                        "chargebackRef": null,
                        "status": "open",
                        "inactive": 0,
                        "frozen": 0,
                        "lastStatusChange": "t1_chs_6616a9de0caecb0efb2c2e6",
                        "actionable": 1,
                        "paymentMethod": 4,
                        "shadow": 0
                    },
                    {
                        "id": "t1_chb_6616a9b87fce852bab31384",
                        "created": "2024-04-10 11:01:12.5285",
                        "modified": "2024-04-10 21:00:01.8517",
                        "creator": "t1_log_618afcdc2543bcabeaf184e",
                        "modifier": "t1_log_64ee6855b97877780a5bfef",
                        "merchant": "t1_mer_65f097a2848a4ceae39b6ee",
                        "txn": "t1_txn_6616a9113625edd8552a81d",
                        "description": "",
                        "total": 10000,
                        "representedTotal": null,
                        "cycle": "first",
                        "currency": "USD",
                        "ref": "j3JeC74OWBL000063",
                        "reason": "Missing Signature",
                        "reasonCode": "F14",
                        "issued": 20240409,
                        "received": null,
                        "reply": 20241231,
                        "bankRef": null,
                        "chargebackRef": null,
                        "status": "lost",
                        "inactive": 0,
                        "frozen": 0,
                        "lastStatusChange": "t1_chs_66173611ab3e030eb8b9b4e",
                        "actionable": 1,
                        "paymentMethod": 4,
                        "shadow": 0
                    }
                ],
                "details": {
                    "requestId": 1,
                    "totals": [],
                    "page": {
                        "current": 1,
                        "last": 1,
                        "hasMore": false
                    }
                },
                "errors": []
            }
        }"#;

        // Parse the response wrapper
        #[derive(serde::Deserialize)]
        struct Response {
            response: ResponseBody,
        }
        #[derive(serde::Deserialize)]
        struct ResponseBody {
            data: Vec<Chargeback>,
        }

        let response: Response = serde_json::from_str(mock_json).expect("Failed to parse mock JSON");
        let chargebacks = response.response.data;

        assert_eq!(chargebacks.len(), 3);

        // Test first chargeback - closed status should be Terminal
        let dispute1 = ChargebackDispute::from_chargeback(chargebacks[0].clone());
        assert_eq!(dispute1.id().as_str(), "t1_chb_6616a9f7c19a47bea938957");
        assert!(dispute1.is_terminal(), "Closed chargeback should be Terminal");
        assert_eq!(dispute1.inner().total, Some(30000));
        assert_eq!(dispute1.inner().reason_code.as_deref(), Some("F14"));

        // Test second chargeback - open first cycle should be Active(First)
        let dispute2 = ChargebackDispute::from_chargeback(chargebacks[1].clone());
        assert_eq!(dispute2.id().as_str(), "t1_chb_6616a9de06fd751e5ae91e5");
        assert!(dispute2.is_active(), "Open chargeback should be Active");
        assert_eq!(dispute2.state_name(), "first");
        if let ChargebackDispute::Active(ActiveDispute::First(first)) = &dispute2 {
            assert_eq!(first.inner().total, Some(20000));
            assert!(first.inner().actionable, "Should be actionable");
        } else {
            panic!("Expected Active(First) state for open chargeback");
        }

        // Test third chargeback - lost status should be Terminal
        let dispute3 = ChargebackDispute::from_chargeback(chargebacks[2].clone());
        assert_eq!(dispute3.id().as_str(), "t1_chb_6616a9b87fce852bab31384");
        assert!(dispute3.is_terminal(), "Lost chargeback should be Terminal");
        assert_eq!(dispute3.inner().total, Some(10000));
    }

    #[test]
    fn test_mock_data_chargeback_fields() {
        // Test a single chargeback with all fields populated
        let cb_json = r#"{
            "id": "t1_chb_6616a9de06fd751e5ae91e5",
            "created": "2024-04-10 11:01:50.0337",
            "modified": "2024-04-10 11:01:50.1415",
            "creator": "t1_log_618afcdc2543bcabeaf184e",
            "modifier": "t1_log_618afcdc2543bcabeaf184e",
            "merchant": "t1_mer_65f097a2848a4ceae39b6ee",
            "txn": "t1_txn_6616a925e796be0ebf69dd9",
            "description": "",
            "total": 20000,
            "representedTotal": null,
            "cycle": "first",
            "currency": "USD",
            "ref": "j3JeC74OWBL000064",
            "reason": "Missing Signature",
            "reasonCode": "F14",
            "issued": 20240409,
            "received": null,
            "reply": 20241231,
            "bankRef": null,
            "chargebackRef": null,
            "status": "open",
            "inactive": 0,
            "frozen": 0,
            "lastStatusChange": "t1_chs_6616a9de0caecb0efb2c2e6",
            "actionable": 1,
            "paymentMethod": 4,
            "shadow": 0
        }"#;

        let cb: Chargeback = serde_json::from_str(cb_json).expect("Failed to parse chargeback");

        // Verify all important fields
        assert_eq!(cb.id.as_str(), "t1_chb_6616a9de06fd751e5ae91e5");
        assert_eq!(cb.merchant.as_ref().map(|m| m.as_str()), Some("t1_mer_65f097a2848a4ceae39b6ee"));
        assert_eq!(cb.txn.as_ref().map(|t| t.as_str()), Some("t1_txn_6616a925e796be0ebf69dd9"));
        assert_eq!(cb.total, Some(20000));
        assert_eq!(cb.cycle, Some(ChargebackCycle::First));
        assert_eq!(cb.status, Some(ChargebackStatusValue::Open));
        assert_eq!(cb.reason.as_deref(), Some("Missing Signature"));
        assert_eq!(cb.reason_code.as_deref(), Some("F14"));
        assert_eq!(cb.reply, Some(20241231));
        assert!(cb.actionable);
        assert!(!cb.inactive);
        assert!(!cb.frozen);
        assert!(!cb.shadow);

        // Convert to dispute and verify state
        let dispute = ChargebackDispute::from_chargeback(cb);
        assert!(dispute.is_active());
        assert_eq!(dispute.state_name(), "first");
    }

    #[test]
    fn test_mime_type_to_document_type() {
        assert!(matches!(mime_type_to_document_type("application/pdf"), ChargebackDocumentType::Pdf));
        assert!(matches!(mime_type_to_document_type("APPLICATION/PDF"), ChargebackDocumentType::Pdf));
        assert!(matches!(mime_type_to_document_type("image/tiff"), ChargebackDocumentType::Tiff));
        assert!(matches!(mime_type_to_document_type("image/tif"), ChargebackDocumentType::Tiff));
        assert!(matches!(mime_type_to_document_type("image/png"), ChargebackDocumentType::Png));
        assert!(matches!(mime_type_to_document_type("image/jpeg"), ChargebackDocumentType::Jpg));
        assert!(matches!(mime_type_to_document_type("image/jpg"), ChargebackDocumentType::Jpg));
        assert!(matches!(mime_type_to_document_type("image/gif"), ChargebackDocumentType::Image));
        assert!(matches!(mime_type_to_document_type("image/webp"), ChargebackDocumentType::Image));
        assert!(matches!(mime_type_to_document_type("text/plain"), ChargebackDocumentType::Text));
        assert!(matches!(mime_type_to_document_type("application/octet-stream"), ChargebackDocumentType::Other));
    }
}