syrup-rail 0.5.0

Validated domain types and lifecycle policy for Syrup Rail billing
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
use std::{fmt, num::NonZeroU32, sync::Arc};

use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use thiserror::Error;

use crate::{
    BillingContact, ChargeAmount, GatewayDiagnostic, GatewayLifecycleCursorKey, GatewayOrderId,
    GatewayPaymentMethodReference, GatewayTransactionId, PaymentAttemptId, PaymentAttemptKind,
    PaymentToken,
};

/// Cooldown applied after a determinate account- or provider-scoped mutation
/// rate limit.
pub const GATEWAY_MUTATION_RATE_LIMIT_RETRY_AFTER_SECONDS: i64 = 60;

pub use self::lifecycle::{
    GatewayLifecycleEvidence, GatewayLifecycleEvidenceError, GatewayLifecycleQuarantine,
    GatewayLifecycleQuarantineError, GatewayLifecycleQuarantineReason,
    GatewayLifecycleQuarantineResolutionReason, GatewayLifecycleQuarantineResolutionReasonError,
    GatewayLifecycleState, GatewayTransactionReport, PaymentReversalKind,
};

mod lifecycle;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GatewayAccountMode {
    Live,
    Test,
}

impl GatewayAccountMode {
    /// Canonical provider-neutral storage representation.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Live => "live",
            Self::Test => "test",
        }
    }
}

impl fmt::Display for GatewayAccountMode {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
#[error("gateway account mode is not recognized")]
pub struct GatewayAccountModeParseError;

impl std::str::FromStr for GatewayAccountMode {
    type Err = GatewayAccountModeParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "live" => Ok(Self::Live),
            "test" => Ok(Self::Test),
            _ => Err(GatewayAccountModeParseError),
        }
    }
}

#[derive(Clone)]
pub enum GatewaySaleIntent {
    OneTime {
        payment_token: PaymentToken,
    },
    InitialStoredCredential {
        payment_token: PaymentToken,
    },
    RecurringStoredCredential {
        payment_method_reference: GatewayPaymentMethodReference,
        initial_transaction_id: GatewayTransactionId,
    },
}

impl fmt::Debug for GatewaySaleIntent {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::OneTime { payment_token } => formatter
                .debug_struct("OneTime")
                .field("payment_token", payment_token)
                .finish(),
            Self::InitialStoredCredential { payment_token } => formatter
                .debug_struct("InitialStoredCredential")
                .field("payment_token", payment_token)
                .finish(),
            Self::RecurringStoredCredential {
                payment_method_reference,
                initial_transaction_id,
            } => formatter
                .debug_struct("RecurringStoredCredential")
                .field("payment_method_reference", payment_method_reference)
                .field("initial_transaction_id", initial_transaction_id)
                .finish(),
        }
    }
}

#[derive(Clone, Debug)]
pub struct GatewaySaleRequest {
    charge: ChargeAmount,
    order_id: GatewayOrderId,
    intent: GatewaySaleIntent,
    billing_contact: Option<BillingContact>,
}

impl GatewaySaleRequest {
    pub const fn new(
        charge: ChargeAmount,
        order_id: GatewayOrderId,
        intent: GatewaySaleIntent,
        billing_contact: Option<BillingContact>,
    ) -> Self {
        Self {
            charge,
            order_id,
            intent,
            billing_contact,
        }
    }

    pub const fn charge(&self) -> ChargeAmount {
        self.charge
    }

    pub const fn order_id(&self) -> &GatewayOrderId {
        &self.order_id
    }

    pub const fn intent(&self) -> &GatewaySaleIntent {
        &self.intent
    }

    pub const fn billing_contact(&self) -> Option<&BillingContact> {
        self.billing_contact.as_ref()
    }

    pub fn into_parts(
        self,
    ) -> (
        ChargeAmount,
        GatewayOrderId,
        GatewaySaleIntent,
        Option<BillingContact>,
    ) {
        (
            self.charge,
            self.order_id,
            self.intent,
            self.billing_contact,
        )
    }
}

#[derive(Clone, Debug)]
pub struct GatewayStorePaymentMethodRequest {
    payment_token: PaymentToken,
    order_id: GatewayOrderId,
    billing_contact: Option<BillingContact>,
}

impl GatewayStorePaymentMethodRequest {
    pub const fn new(
        payment_token: PaymentToken,
        order_id: GatewayOrderId,
        billing_contact: Option<BillingContact>,
    ) -> Self {
        Self {
            payment_token,
            order_id,
            billing_contact,
        }
    }

    pub const fn payment_token(&self) -> &PaymentToken {
        &self.payment_token
    }

    pub const fn order_id(&self) -> &GatewayOrderId {
        &self.order_id
    }

    pub const fn billing_contact(&self) -> Option<&BillingContact> {
        self.billing_contact.as_ref()
    }

    pub fn into_parts(self) -> (PaymentToken, GatewayOrderId, Option<BillingContact>) {
        (self.payment_token, self.order_id, self.billing_contact)
    }
}

#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
pub enum GatewayRequestError {
    #[error("gateway query requires a transaction ID or order ID")]
    MissingQuerySelector,
    #[error("gateway report window end must be after its start")]
    InvalidReportWindow,
    #[error("gateway report page size must be positive")]
    InvalidPageSize,
}

#[derive(Clone, Debug)]
pub struct GatewayQueryRequest {
    transaction_id: Option<GatewayTransactionId>,
    order_id: Option<GatewayOrderId>,
}

impl GatewayQueryRequest {
    pub fn new(
        transaction_id: Option<GatewayTransactionId>,
        order_id: Option<GatewayOrderId>,
    ) -> Result<Self, GatewayRequestError> {
        if transaction_id.is_none() && order_id.is_none() {
            return Err(GatewayRequestError::MissingQuerySelector);
        }
        Ok(Self {
            transaction_id,
            order_id,
        })
    }

    pub const fn transaction_id(&self) -> Option<&GatewayTransactionId> {
        self.transaction_id.as_ref()
    }

    pub const fn order_id(&self) -> Option<&GatewayOrderId> {
        self.order_id.as_ref()
    }

    pub fn into_parts(self) -> (Option<GatewayTransactionId>, Option<GatewayOrderId>) {
        (self.transaction_id, self.order_id)
    }
}

#[derive(Clone, Debug)]
pub struct GatewayTransactionReportRequest {
    start_at: DateTime<Utc>,
    end_at: DateTime<Utc>,
    page_size: NonZeroU32,
    page_index: u32,
}

impl GatewayTransactionReportRequest {
    pub fn new(
        start_at: DateTime<Utc>,
        end_at: DateTime<Utc>,
        page_size: u32,
        page_index: u32,
    ) -> Result<Self, GatewayRequestError> {
        if end_at <= start_at {
            return Err(GatewayRequestError::InvalidReportWindow);
        }
        let page_size = NonZeroU32::new(page_size).ok_or(GatewayRequestError::InvalidPageSize)?;
        Ok(Self {
            start_at,
            end_at,
            page_size,
            page_index,
        })
    }

    pub const fn start_at(&self) -> &DateTime<Utc> {
        &self.start_at
    }

    pub const fn end_at(&self) -> &DateTime<Utc> {
        &self.end_at
    }

    pub const fn page_size(&self) -> NonZeroU32 {
        self.page_size
    }

    pub const fn page_index(&self) -> u32 {
        self.page_index
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GatewayPaymentStatus {
    Approved,
    Declined,
    Unknown,
    Failed,
}

/// Provider-neutral diagnostics that require host policy beyond the payment
/// status alone.
///
/// These diagnostics intentionally contain no provider payload. Exact gateway
/// response fields remain available through [`ProcessorEvidence`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GatewayPaymentDiagnostic {
    /// The processor reported the payment as a duplicate.
    ///
    /// This does not prove that the current attempt was submitted or identify
    /// an earlier transaction. Reconcile the durable attempt before retrying.
    ProcessorReportedDuplicate,
}

#[derive(Clone, Eq, PartialEq)]
pub struct CardLastFour(String);

impl CardLastFour {
    pub fn from_provider(value: &str) -> Option<Self> {
        let value = value.trim();
        (value.len() == 4 && value.bytes().all(|byte| byte.is_ascii_digit()))
            .then(|| Self(value.to_owned()))
    }

    pub fn expose(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for CardLastFour {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("CardLastFour([redacted])")
    }
}

impl fmt::Display for CardLastFour {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("[redacted]")
    }
}

/// Canonical provider-neutral card brand retained for masked presentation.
///
/// Provider text is mapped into this closed vocabulary before it can enter a
/// consumer-facing projection or host event. Unrecognized nonempty values
/// become [`Self::Other`]; their original text is not retained by this value.
#[non_exhaustive]
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub enum PaymentCardBrand {
    /// Visa.
    Visa,
    /// Mastercard.
    Mastercard,
    /// American Express.
    AmericanExpress,
    /// Discover.
    Discover,
    /// Japan Credit Bureau.
    Jcb,
    /// Diners Club.
    DinersClub,
    /// UnionPay.
    UnionPay,
    /// Maestro.
    Maestro,
    /// A nonempty provider value outside the recognized vocabulary.
    Other,
}

const PAYMENT_CARD_BRAND_ALIASES: &[(&str, PaymentCardBrand)] = &[
    ("visa", PaymentCardBrand::Visa),
    ("mastercard", PaymentCardBrand::Mastercard),
    ("master card", PaymentCardBrand::Mastercard),
    ("american express", PaymentCardBrand::AmericanExpress),
    ("amex", PaymentCardBrand::AmericanExpress),
    ("discover", PaymentCardBrand::Discover),
    ("jcb", PaymentCardBrand::Jcb),
    ("diners", PaymentCardBrand::DinersClub),
    ("diners club", PaymentCardBrand::DinersClub),
    ("dinersclub", PaymentCardBrand::DinersClub),
    ("unionpay", PaymentCardBrand::UnionPay),
    ("union pay", PaymentCardBrand::UnionPay),
    ("maestro", PaymentCardBrand::Maestro),
];

impl PaymentCardBrand {
    /// Canonicalizes an untrusted provider value without retaining unknown
    /// text.
    pub fn from_provider(value: &str) -> Option<Self> {
        let value = value.trim();
        if value.is_empty() {
            return None;
        }
        let brand = PAYMENT_CARD_BRAND_ALIASES
            .iter()
            .find_map(|(alias, brand)| value.eq_ignore_ascii_case(alias).then_some(*brand))
            .unwrap_or(Self::Other);
        Some(brand)
    }

    /// Explicitly exposes the stable provider-neutral wire label.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Visa => "visa",
            Self::Mastercard => "mastercard",
            Self::AmericanExpress => "american_express",
            Self::Discover => "discover",
            Self::Jcb => "jcb",
            Self::DinersClub => "diners_club",
            Self::UnionPay => "union_pay",
            Self::Maestro => "maestro",
            Self::Other => "other",
        }
    }
}

impl fmt::Debug for PaymentCardBrand {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("PaymentCardBrand([redacted])")
    }
}

impl fmt::Display for PaymentCardBrand {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("[redacted]")
    }
}

#[derive(Clone, Default, Eq, PartialEq)]
pub struct GatewayPaymentDescriptor {
    payment_type: Option<GatewayDiagnostic>,
    card_brand: Option<GatewayDiagnostic>,
    card_last_four: Option<CardLastFour>,
    card_exp_month: Option<i16>,
    card_exp_year: Option<i16>,
}

impl GatewayPaymentDescriptor {
    pub fn from_provider_parts(
        payment_type: Option<GatewayDiagnostic>,
        card_brand: Option<GatewayDiagnostic>,
        card_last_four: Option<&str>,
        card_exp_month: Option<i16>,
        card_exp_year: Option<i16>,
    ) -> Self {
        Self {
            payment_type,
            card_brand,
            card_last_four: card_last_four.and_then(CardLastFour::from_provider),
            card_exp_month: card_exp_month.filter(|month| (1..=12).contains(month)),
            card_exp_year: card_exp_year.filter(|year| (2000..=2100).contains(year)),
        }
    }

    /// Returns provider payment-type evidence for explicit boundary use.
    pub const fn payment_type(&self) -> Option<&GatewayDiagnostic> {
        self.payment_type.as_ref()
    }

    /// Returns provider card-brand evidence for explicit persistence or
    /// reconciliation use.
    pub const fn card_brand(&self) -> Option<&GatewayDiagnostic> {
        self.card_brand.as_ref()
    }

    /// Reduces provider card-brand evidence to the presentation vocabulary.
    ///
    /// Unknown provider text becomes [`PaymentCardBrand::Other`] and is not
    /// retained in the returned value. Use this method for customer displays
    /// and host events; use [`Self::card_brand`] only where exact provider
    /// evidence is required.
    pub fn canonical_card_brand(&self) -> Option<PaymentCardBrand> {
        self.card_brand
            .as_ref()
            .and_then(|brand| PaymentCardBrand::from_provider(brand.expose()))
    }

    /// Returns the validated masked last four digits.
    pub const fn card_last_four(&self) -> Option<&CardLastFour> {
        self.card_last_four.as_ref()
    }

    /// Returns the validated card expiration month.
    pub const fn card_exp_month(&self) -> Option<i16> {
        self.card_exp_month
    }

    /// Returns the validated card expiration year.
    pub const fn card_exp_year(&self) -> Option<i16> {
        self.card_exp_year
    }
}

impl fmt::Debug for GatewayPaymentDescriptor {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GatewayPaymentDescriptor")
            .field("has_payment_type", &self.payment_type.is_some())
            .field("has_card_brand", &self.card_brand.is_some())
            .field("has_card_last_four", &self.card_last_four.is_some())
            .field("card_exp_month", &self.card_exp_month)
            .field("card_exp_year", &self.card_exp_year)
            .finish()
    }
}

#[derive(Clone, Default, Eq, PartialEq)]
pub struct ProcessorEvidence {
    transaction_id: Option<GatewayTransactionId>,
    payment_method_reference: Option<GatewayPaymentMethodReference>,
    response: Option<GatewayDiagnostic>,
    response_code: Option<GatewayDiagnostic>,
    response_text: Option<GatewayDiagnostic>,
    condition: Option<GatewayDiagnostic>,
    descriptor: GatewayPaymentDescriptor,
}

impl ProcessorEvidence {
    #[allow(clippy::too_many_arguments)]
    pub const fn new(
        transaction_id: Option<GatewayTransactionId>,
        payment_method_reference: Option<GatewayPaymentMethodReference>,
        response: Option<GatewayDiagnostic>,
        response_code: Option<GatewayDiagnostic>,
        response_text: Option<GatewayDiagnostic>,
        condition: Option<GatewayDiagnostic>,
        descriptor: GatewayPaymentDescriptor,
    ) -> Self {
        Self {
            transaction_id,
            payment_method_reference,
            response,
            response_code,
            response_text,
            condition,
            descriptor,
        }
    }

    pub const fn transaction_id(&self) -> Option<&GatewayTransactionId> {
        self.transaction_id.as_ref()
    }

    pub const fn payment_method_reference(&self) -> Option<&GatewayPaymentMethodReference> {
        self.payment_method_reference.as_ref()
    }

    pub const fn response(&self) -> Option<&GatewayDiagnostic> {
        self.response.as_ref()
    }

    pub const fn response_code(&self) -> Option<&GatewayDiagnostic> {
        self.response_code.as_ref()
    }

    pub const fn response_text(&self) -> Option<&GatewayDiagnostic> {
        self.response_text.as_ref()
    }

    pub const fn condition(&self) -> Option<&GatewayDiagnostic> {
        self.condition.as_ref()
    }

    pub const fn descriptor(&self) -> &GatewayPaymentDescriptor {
        &self.descriptor
    }

    pub const fn has_gateway_reference(&self) -> bool {
        self.transaction_id.is_some() || self.payment_method_reference.is_some()
    }

    /// Returns whether the evidence conservatively identifies an approved
    /// payment at the processor.
    ///
    /// A transaction identity is required in addition to an approved response,
    /// response code, or lifecycle condition. Free-form response text is not
    /// treated as authoritative approval evidence.
    pub fn indicates_approved_payment(&self) -> bool {
        self.transaction_id.is_some()
            && (crate::gateway_response_is_approved(
                self.response.as_ref().map(GatewayDiagnostic::expose),
            ) || crate::gateway_response_is_approved(
                self.response_code.as_ref().map(GatewayDiagnostic::expose),
            ) || self
                .condition
                .as_ref()
                .is_some_and(|value| crate::gateway_state_is_approved(value.expose())))
    }
}

/// Processor evidence refined by an authoritative approved gateway outcome.
///
/// Raw processor fields are intentionally not reclassified here: some valid
/// approved outcomes carry incomplete evidence until exact reconciliation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ApprovedProcessorEvidence {
    evidence: ProcessorEvidence,
}

impl ApprovedProcessorEvidence {
    pub const fn evidence(&self) -> &ProcessorEvidence {
        &self.evidence
    }

    pub fn into_evidence(self) -> ProcessorEvidence {
        self.evidence
    }
}

impl fmt::Debug for ProcessorEvidence {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ProcessorEvidence")
            .field("has_transaction_id", &self.transaction_id.is_some())
            .field(
                "has_payment_method_reference",
                &self.payment_method_reference.is_some(),
            )
            .field("has_response", &self.response.is_some())
            .field("has_response_code", &self.response_code.is_some())
            .field("has_response_text", &self.response_text.is_some())
            .field("has_condition", &self.condition.is_some())
            .field("descriptor", &self.descriptor)
            .finish()
    }
}

#[derive(Clone, Debug)]
#[must_use = "gateway payment outcomes contain authoritative provider decisions"]
pub struct GatewayPaymentOutcome {
    status: GatewayPaymentStatus,
    evidence: ProcessorEvidence,
    diagnostics: Vec<GatewayPaymentDiagnostic>,
}

impl GatewayPaymentOutcome {
    pub const fn new(status: GatewayPaymentStatus, evidence: ProcessorEvidence) -> Self {
        Self {
            status,
            evidence,
            diagnostics: Vec::new(),
        }
    }

    /// Attaches provider-neutral diagnostics derived by a gateway adapter.
    pub fn with_diagnostics(mut self, diagnostics: Vec<GatewayPaymentDiagnostic>) -> Self {
        self.diagnostics = diagnostics;
        self
    }

    pub const fn status(&self) -> GatewayPaymentStatus {
        self.status
    }

    pub const fn evidence(&self) -> &ProcessorEvidence {
        &self.evidence
    }

    /// Returns payload-free diagnostics suitable for host policy and routing.
    pub fn diagnostics(&self) -> &[GatewayPaymentDiagnostic] {
        &self.diagnostics
    }

    /// Refines this outcome's evidence only when the provider decision is
    /// authoritatively approved.
    pub fn approved_evidence(&self) -> Option<ApprovedProcessorEvidence> {
        (self.status == GatewayPaymentStatus::Approved).then(|| ApprovedProcessorEvidence {
            evidence: self.evidence.clone(),
        })
    }

    /// Consumes the outcome into its original durable decision parts.
    ///
    /// This compatibility method does not return provider-neutral diagnostics;
    /// use [`Self::into_parts_with_diagnostics`] when routing them matters.
    #[deprecated(
        note = "this drops gateway diagnostics; use GatewayPaymentOutcome::into_parts_with_diagnostics"
    )]
    pub fn into_parts(self) -> (GatewayPaymentStatus, ProcessorEvidence) {
        (self.status, self.evidence)
    }

    /// Consumes the outcome without discarding provider-neutral diagnostics.
    pub fn into_parts_with_diagnostics(
        self,
    ) -> (
        GatewayPaymentStatus,
        ProcessorEvidence,
        Vec<GatewayPaymentDiagnostic>,
    ) {
        (self.status, self.evidence, self.diagnostics)
    }

    pub const fn transaction_id(&self) -> Option<&GatewayTransactionId> {
        self.evidence.transaction_id()
    }

    pub const fn payment_method_reference(&self) -> Option<&GatewayPaymentMethodReference> {
        self.evidence.payment_method_reference()
    }

    pub const fn response(&self) -> Option<&GatewayDiagnostic> {
        self.evidence.response()
    }

    pub const fn response_code(&self) -> Option<&GatewayDiagnostic> {
        self.evidence.response_code()
    }

    pub const fn response_text(&self) -> Option<&GatewayDiagnostic> {
        self.evidence.response_text()
    }

    pub const fn condition(&self) -> Option<&GatewayDiagnostic> {
        self.evidence.condition()
    }

    pub const fn descriptor(&self) -> &GatewayPaymentDescriptor {
        self.evidence.descriptor()
    }
}

#[derive(Error)]
pub enum GatewayError {
    #[error("gateway rejected the request before processing")]
    RequestRejected(GatewayDiagnostic),
    #[error("gateway response was malformed")]
    Malformed(GatewayDiagnostic),
    #[error("gateway configuration is invalid")]
    Configuration(GatewayDiagnostic),
    #[error("gateway is unavailable")]
    Unavailable(GatewayDiagnostic),
    #[error("gateway rate limit exceeded")]
    RateLimited(GatewayDiagnostic),
}

impl fmt::Debug for GatewayError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (variant, detail) = match self {
            Self::RequestRejected(detail) => ("RequestRejected", detail),
            Self::Malformed(detail) => ("Malformed", detail),
            Self::Configuration(detail) => ("Configuration", detail),
            Self::Unavailable(detail) => ("Unavailable", detail),
            Self::RateLimited(detail) => ("RateLimited", detail),
        };
        formatter
            .debug_struct(variant)
            .field("has_detail", &(!detail.is_empty()))
            .finish()
    }
}

impl GatewayError {
    pub const fn detail(&self) -> &GatewayDiagnostic {
        match self {
            Self::RequestRejected(detail)
            | Self::Malformed(detail)
            | Self::Configuration(detail)
            | Self::Unavailable(detail)
            | Self::RateLimited(detail) => detail,
        }
    }
}

/// Proof from a gateway adapter that the provider never received a mutation.
///
/// Returning any variant authorizes ledger-aware callers to restore prepared
/// work and retry the same provider mutation when policy permits. Adapters must
/// use [`GatewayMutationError::Indeterminate`] once request transmission may
/// have begun. Misclassifying an in-flight request as not submitted can cause a
/// duplicate provider mutation on same-key retry.
///
/// This enum is intentionally exhaustive: adding a variant must break every
/// persistence adapter at compile time so retry safety, durable resolution,
/// cooldown scope, and host-target consequences are classified together.
#[derive(Error)]
pub enum GatewayNotSubmittedError {
    #[error("gateway rejected the mutation request")]
    RequestRejected(GatewayDiagnostic),
    #[error("gateway mutation request is malformed")]
    Malformed(GatewayDiagnostic),
    #[error("gateway mutation configuration is invalid")]
    Configuration(GatewayDiagnostic),
    /// Transport failed before request transmission began. This is not a
    /// generic transient transport error: returning it certifies that the
    /// provider could not have received the mutation.
    #[error("gateway mutation was not transmitted")]
    NotTransmitted(GatewayDiagnostic),
    #[error("gateway mutation was rate limited before submission")]
    RateLimited(GatewayDiagnostic),
    /// Reserved for a caller-owned account-mode check performed immediately
    /// before invoking the mutation endpoint.
    ///
    /// Gateway adapters must not return this variant from `sale` or
    /// `store_payment_method`; verified submission wrappers normalize any such
    /// adapter response to an ordinary terminal not-submitted error.
    #[error("gateway account mode changed before mutation submission")]
    AccountModeMismatch {
        required: GatewayAccountMode,
        observed: GatewayAccountMode,
        detail: GatewayDiagnostic,
    },
    /// Reserved for a caller-owned account-mode query performed immediately
    /// before invoking the mutation endpoint. Gateway adapters must not return
    /// this variant from mutation methods.
    #[error("gateway account mode could not be verified before mutation submission")]
    AccountModeVerification(#[source] GatewayError),
}

impl fmt::Debug for GatewayNotSubmittedError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (variant, detail) = match self {
            Self::RequestRejected(detail) => ("RequestRejected", detail),
            Self::Malformed(detail) => ("Malformed", detail),
            Self::Configuration(detail) => ("Configuration", detail),
            Self::NotTransmitted(detail) => ("NotTransmitted", detail),
            Self::RateLimited(detail) => ("RateLimited", detail),
            Self::AccountModeMismatch {
                required,
                observed,
                detail,
            } => {
                return formatter
                    .debug_struct("AccountModeMismatch")
                    .field("required", required)
                    .field("observed", observed)
                    .field("has_detail", &(!detail.is_empty()))
                    .finish();
            }
            Self::AccountModeVerification(error) => {
                return formatter
                    .debug_tuple("AccountModeVerification")
                    .field(error)
                    .finish();
            }
        };
        formatter
            .debug_struct(variant)
            .field("has_detail", &(!detail.is_empty()))
            .finish()
    }
}

impl GatewayNotSubmittedError {
    pub const fn detail(&self) -> &GatewayDiagnostic {
        match self {
            Self::RequestRejected(detail)
            | Self::Malformed(detail)
            | Self::Configuration(detail)
            | Self::NotTransmitted(detail)
            | Self::RateLimited(detail) => detail,
            Self::AccountModeMismatch { detail, .. } => detail,
            Self::AccountModeVerification(error) => error.detail(),
        }
    }
}

/// Gateway mutation failure classified by whether provider receipt is possible.
///
/// Adapter implementations must return `NotSubmitted` only with proof that no
/// request bytes could have reached the provider. Once transmission may have
/// begun, return an indeterminate variant even if the transport later reports
/// an ordinary unavailable or rate-limit error.
#[derive(Error)]
pub enum GatewayMutationError {
    #[error("gateway mutation was not submitted")]
    NotSubmitted(#[source] GatewayNotSubmittedError),
    #[error("gateway mutation was rate limited with an indeterminate outcome")]
    RateLimitedIndeterminate(GatewayDiagnostic),
    #[error("gateway mutation outcome is indeterminate")]
    Indeterminate(GatewayDiagnostic),
}

impl fmt::Debug for GatewayMutationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotSubmitted(error) => {
                formatter.debug_tuple("NotSubmitted").field(error).finish()
            }
            Self::RateLimitedIndeterminate(detail) => formatter
                .debug_struct("RateLimitedIndeterminate")
                .field("has_detail", &(!detail.is_empty()))
                .finish(),
            Self::Indeterminate(detail) => formatter
                .debug_struct("Indeterminate")
                .field("has_detail", &(!detail.is_empty()))
                .finish(),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MutationCertainty {
    /// The adapter certifies that the provider never received the request.
    /// Ledger-aware callers may use this proof to permit same-key resubmission.
    NotSubmitted,
    Indeterminate,
}

impl GatewayMutationError {
    pub const fn detail(&self) -> &GatewayDiagnostic {
        match self {
            Self::NotSubmitted(error) => error.detail(),
            Self::RateLimitedIndeterminate(detail) | Self::Indeterminate(detail) => detail,
        }
    }

    pub const fn certainty(&self) -> MutationCertainty {
        match self {
            Self::NotSubmitted(_) => MutationCertainty::NotSubmitted,
            Self::RateLimitedIndeterminate(_) | Self::Indeterminate(_) => {
                MutationCertainty::Indeterminate
            }
        }
    }
}

#[async_trait]
pub trait PaymentGateway: Send + Sync {
    async fn account_mode(&self) -> Result<GatewayAccountMode, GatewayError>;

    async fn sale(
        &self,
        request: GatewaySaleRequest,
    ) -> Result<GatewayPaymentOutcome, GatewayMutationError>;

    async fn store_payment_method(
        &self,
        request: GatewayStorePaymentMethodRequest,
    ) -> Result<GatewayPaymentOutcome, GatewayMutationError>;

    async fn query_transaction(
        &self,
        request: GatewayQueryRequest,
    ) -> Result<Option<GatewayPaymentOutcome>, GatewayError>;

    async fn query_transaction_reports(
        &self,
        request: GatewayTransactionReportRequest,
    ) -> Result<Vec<GatewayTransactionReport>, GatewayError>;
}

pub trait GatewayMutationReferenceFactory: Send + Sync {
    fn for_attempt(&self, kind: PaymentAttemptKind, attempt_id: PaymentAttemptId)
    -> GatewayOrderId;
}

pub type SharedPaymentGateway = Arc<dyn PaymentGateway>;
pub type SharedGatewayMutationReferenceFactory = Arc<dyn GatewayMutationReferenceFactory>;

#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum GatewayLifecycleQueryPolicyError {
    #[error("gateway lifecycle query overlap must be positive")]
    NonPositiveOverlap,
    #[error("gateway lifecycle query limit must be positive")]
    NonPositiveLimit,
    #[error("gateway lifecycle query limits overflow their bounded work calculation")]
    Overflow,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GatewayLifecycleQueryPolicy {
    cursor_key: GatewayLifecycleCursorKey,
    overlap: Duration,
    page_size: NonZeroU32,
    ordinary_page_limit: NonZeroU32,
    max_window_splits: NonZeroU32,
    narrow_window_drain_page_limit: NonZeroU32,
}

impl GatewayLifecycleQueryPolicy {
    pub fn new(
        cursor_key: GatewayLifecycleCursorKey,
        overlap: Duration,
        page_size: u32,
        ordinary_page_limit: u32,
        max_window_splits: u32,
        narrow_window_drain_page_limit: u32,
    ) -> Result<Self, GatewayLifecycleQueryPolicyError> {
        if overlap <= Duration::zero() {
            return Err(GatewayLifecycleQueryPolicyError::NonPositiveOverlap);
        }
        let page_size =
            NonZeroU32::new(page_size).ok_or(GatewayLifecycleQueryPolicyError::NonPositiveLimit)?;
        let ordinary_page_limit = NonZeroU32::new(ordinary_page_limit)
            .ok_or(GatewayLifecycleQueryPolicyError::NonPositiveLimit)?;
        let max_window_splits = NonZeroU32::new(max_window_splits)
            .ok_or(GatewayLifecycleQueryPolicyError::NonPositiveLimit)?;
        let narrow_window_drain_page_limit = NonZeroU32::new(narrow_window_drain_page_limit)
            .ok_or(GatewayLifecycleQueryPolicyError::NonPositiveLimit)?;
        page_size
            .get()
            .checked_mul(ordinary_page_limit.get())
            .and_then(|value| value.checked_mul(max_window_splits.get()))
            .and_then(|_| {
                page_size
                    .get()
                    .checked_mul(narrow_window_drain_page_limit.get())
            })
            .ok_or(GatewayLifecycleQueryPolicyError::Overflow)?;
        Ok(Self {
            cursor_key,
            overlap,
            page_size,
            ordinary_page_limit,
            max_window_splits,
            narrow_window_drain_page_limit,
        })
    }

    pub const fn cursor_key(&self) -> &GatewayLifecycleCursorKey {
        &self.cursor_key
    }

    pub const fn overlap(&self) -> Duration {
        self.overlap
    }

    pub const fn page_size(&self) -> NonZeroU32 {
        self.page_size
    }

    pub const fn ordinary_page_limit(&self) -> NonZeroU32 {
        self.ordinary_page_limit
    }

    pub const fn max_window_splits(&self) -> NonZeroU32 {
        self.max_window_splits
    }

    pub const fn narrow_window_drain_page_limit(&self) -> NonZeroU32 {
        self.narrow_window_drain_page_limit
    }
}

#[cfg(test)]
mod tests;