cedros-login-server 0.0.39

Authentication server for cedros-login with email/password, Google OAuth, and Solana wallet sign-in
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
//! Credit balance and transaction repository trait and implementations

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use std::collections::HashMap;
use tokio::sync::RwLock;
use uuid::Uuid;

use crate::errors::AppError;
use crate::repositories::pagination::{cap_limit, cap_offset};

/// Credit transaction type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CreditTxType {
    /// Credit from deposit
    Deposit,
    /// Debit from spending
    Spend,
    /// Manual adjustment
    Adjustment,
}

impl CreditTxType {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Deposit => "deposit",
            Self::Spend => "spend",
            Self::Adjustment => "adjustment",
        }
    }

    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "deposit" => Some(Self::Deposit),
            "spend" => Some(Self::Spend),
            "adjustment" => Some(Self::Adjustment),
            _ => None,
        }
    }
}

/// Credit balance entity
#[derive(Debug, Clone)]
pub struct CreditBalanceEntity {
    pub id: Uuid,
    pub user_id: Uuid,
    pub balance: i64,
    /// Credits reserved by pending holds (not available for spending)
    pub held_balance: i64,
    pub currency: String,
    pub updated_at: DateTime<Utc>,
}

impl CreditBalanceEntity {
    /// Returns the available balance (total minus held)
    pub fn available(&self) -> i64 {
        self.balance - self.held_balance
    }
}

/// Credit transaction entity (immutable audit log)
#[derive(Debug, Clone)]
pub struct CreditTransactionEntity {
    pub id: Uuid,
    pub user_id: Uuid,
    pub amount: i64,
    pub currency: String,
    pub tx_type: CreditTxType,
    pub deposit_session_id: Option<Uuid>,
    pub privacy_note_id: Option<Uuid>,
    /// Client-provided idempotency key to prevent duplicate charges
    pub idempotency_key: Option<String>,
    /// Type of reference (e.g., "order", "subscription", "refund")
    pub reference_type: Option<String>,
    /// ID of the related entity
    pub reference_id: Option<Uuid>,
    /// Link to original hold if this was a captured hold
    pub hold_id: Option<Uuid>,
    pub metadata: Option<serde_json::Value>,
    /// SOL/USD conversion rate at time of crediting (deposit transactions only)
    pub conversion_rate: Option<f64>,
    pub created_at: DateTime<Utc>,
}

impl CreditTransactionEntity {
    /// Create a new privacy deposit credit transaction (SSS wallet)
    ///
    /// Used for Privacy Cash deposits where the deposit goes to user's
    /// Privacy Cash account and is later withdrawn to company wallet.
    pub fn new_privacy_deposit(
        user_id: Uuid,
        amount: i64,
        currency: &str,
        deposit_session_id: Uuid,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            user_id,
            amount,
            currency: currency.to_string(),
            tx_type: CreditTxType::Deposit,
            deposit_session_id: Some(deposit_session_id),
            privacy_note_id: None,
            idempotency_key: None,
            reference_type: None,
            reference_id: None,
            hold_id: None,
            metadata: None,
            conversion_rate: None,
            created_at: Utc::now(),
        }
    }

    /// Create a new deposit credit transaction (legacy)
    #[allow(dead_code)]
    pub fn new_deposit(
        user_id: Uuid,
        amount: i64,
        currency: &str,
        deposit_session_id: Uuid,
        privacy_note_id: Uuid,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            user_id,
            amount,
            currency: currency.to_string(),
            tx_type: CreditTxType::Deposit,
            deposit_session_id: Some(deposit_session_id),
            privacy_note_id: Some(privacy_note_id),
            idempotency_key: None,
            reference_type: None,
            reference_id: None,
            hold_id: None,
            metadata: None,
            conversion_rate: None,
            created_at: Utc::now(),
        }
    }

    /// Create a new spend debit transaction (simple)
    pub fn new_spend(
        user_id: Uuid,
        amount: i64,
        currency: &str,
        metadata: Option<serde_json::Value>,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            user_id,
            amount: -amount.abs(), // Always negative for spend
            currency: currency.to_string(),
            tx_type: CreditTxType::Spend,
            deposit_session_id: None,
            privacy_note_id: None,
            idempotency_key: None,
            reference_type: None,
            reference_id: None,
            hold_id: None,
            metadata,
            conversion_rate: None,
            created_at: Utc::now(),
        }
    }

    /// Create a new spend transaction with full reference tracking
    ///
    /// Use this for production spends to ensure idempotency and audit trail.
    pub fn new_spend_with_reference(
        user_id: Uuid,
        amount: i64,
        currency: &str,
        idempotency_key: String,
        reference_type: &str,
        reference_id: Uuid,
        metadata: Option<serde_json::Value>,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            user_id,
            amount: -amount.abs(),
            currency: currency.to_string(),
            tx_type: CreditTxType::Spend,
            deposit_session_id: None,
            privacy_note_id: None,
            idempotency_key: Some(idempotency_key),
            reference_type: Some(reference_type.to_string()),
            reference_id: Some(reference_id),
            hold_id: None,
            metadata,
            conversion_rate: None,
            created_at: Utc::now(),
        }
    }

    /// Create a spend transaction from a captured hold
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn from_captured_hold(
        user_id: Uuid,
        amount: i64,
        currency: &str,
        hold_id: Uuid,
        idempotency_key: &str,
        reference_type: Option<&str>,
        reference_id: Option<Uuid>,
        metadata: Option<serde_json::Value>,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            user_id,
            amount: -amount.abs(),
            currency: currency.to_string(),
            tx_type: CreditTxType::Spend,
            deposit_session_id: None,
            privacy_note_id: None,
            idempotency_key: Some(idempotency_key.to_string()),
            reference_type: reference_type.map(String::from),
            reference_id,
            hold_id: Some(hold_id),
            metadata,
            conversion_rate: None,
            created_at: Utc::now(),
        }
    }

    /// Create an adjustment transaction (admin operation)
    ///
    /// Use for refunds, bonuses, promotional credits, or manual corrections.
    /// Amount can be positive (credit) or negative (debit).
    pub fn new_adjustment(
        user_id: Uuid,
        amount: i64,
        currency: &str,
        admin_id: Uuid,
        reason: &str,
        reference_type: Option<&str>,
        reference_id: Option<Uuid>,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            user_id,
            amount,
            currency: currency.to_string(),
            tx_type: CreditTxType::Adjustment,
            deposit_session_id: None,
            privacy_note_id: None,
            idempotency_key: None,
            reference_type: reference_type.map(String::from),
            reference_id,
            hold_id: None,
            metadata: Some(serde_json::json!({
                "admin_id": admin_id.to_string(),
                "reason": reason
            })),
            conversion_rate: None,
            created_at: Utc::now(),
        }
    }

    /// Create an idempotent refund adjustment transaction.
    ///
    /// Uses `idempotency_key` to ensure at-most-once issuance if the admin retries.
    pub fn new_refund_adjustment(
        user_id: Uuid,
        amount: i64,
        currency: &str,
        admin_id: Uuid,
        refund_request_id: Uuid,
        original_transaction_id: Uuid,
        reason: &str,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            user_id,
            amount,
            currency: currency.to_string(),
            tx_type: CreditTxType::Adjustment,
            deposit_session_id: None,
            privacy_note_id: None,
            idempotency_key: Some(format!("refund_request:{}", refund_request_id)),
            reference_type: Some("refund".to_string()),
            reference_id: Some(original_transaction_id),
            hold_id: None,
            metadata: Some(serde_json::json!({
                "admin_id": admin_id.to_string(),
                "refund_request_id": refund_request_id.to_string(),
                "reason": reason
            })),
            conversion_rate: None,
            created_at: Utc::now(),
        }
    }
}

/// Aggregate credit statistics (admin view)
#[derive(Debug, Clone, Default)]
pub struct CreditStats {
    // ============= By Currency =============
    /// Stats for SOL credits
    pub sol: CurrencyCreditStats,
    /// Stats for USD credits (from USDC/USDT deposits)
    pub usd: CurrencyCreditStats,

    // ============= Totals =============
    /// Total number of unique users with any credit balance
    pub total_users_with_balance: u64,
    /// Total outstanding credit value (sum of all balances)
    pub total_outstanding_lamports: i64,
}

/// Credit statistics for a single currency
#[derive(Debug, Clone, Default)]
pub struct CurrencyCreditStats {
    /// Total credited (positive transactions: deposits + positive adjustments)
    pub total_credited: i64,
    /// Total spent (absolute value of spend transactions)
    pub total_spent: i64,
    /// Total positive adjustments (refunds, bonuses)
    pub total_positive_adjustments: i64,
    /// Total negative adjustments (corrections, chargebacks)
    pub total_negative_adjustments: i64,
    /// Current outstanding balance (total_credited - total_spent + net_adjustments)
    pub current_outstanding: i64,
    /// Number of deposit transactions
    pub deposit_count: u64,
    /// Number of spend transactions
    pub spend_count: u64,
    /// Number of adjustment transactions
    pub adjustment_count: u64,
}

/// User credit statistics (user-facing analytics)
#[derive(Debug, Clone, Default)]
pub struct UserCreditStats {
    /// Total deposited in lamports
    pub total_deposited: i64,
    /// Total spent in lamports
    pub total_spent: i64,
    /// Total positive adjustments (refunds, bonuses)
    pub total_refunds: i64,
    /// Current balance in lamports
    pub current_balance: i64,
    /// Number of deposit transactions
    pub deposit_count: u64,
    /// Number of spend transactions
    pub spend_count: u64,
    /// Currency
    pub currency: String,
}

/// Credit repository trait
#[async_trait]
pub trait CreditRepository: Send + Sync {
    /// Get balance for a user and currency
    async fn get_balance(&self, user_id: Uuid, currency: &str) -> Result<i64, AppError>;

    /// Get balances for many users in one call (missing users default to 0 by caller).
    async fn get_balances(
        &self,
        user_ids: &[Uuid],
        currency: &str,
    ) -> Result<HashMap<Uuid, i64>, AppError>;

    /// Get or create balance entity for a user and currency
    async fn get_or_create_balance(
        &self,
        user_id: Uuid,
        currency: &str,
    ) -> Result<CreditBalanceEntity, AppError>;

    /// Add credit to a user's balance (atomic operation)
    /// Returns the new balance
    async fn add_credit(
        &self,
        user_id: Uuid,
        amount: i64,
        currency: &str,
        tx: CreditTransactionEntity,
    ) -> Result<i64, AppError>;

    /// Deduct credit from a user's balance (atomic operation)
    /// Returns the new balance or error if insufficient funds
    async fn deduct_credit(
        &self,
        user_id: Uuid,
        amount: i64,
        currency: &str,
        tx: CreditTransactionEntity,
    ) -> Result<i64, AppError>;

    /// Get transaction history for a user
    async fn get_transactions(
        &self,
        user_id: Uuid,
        currency: Option<&str>,
        tx_type: Option<&str>,
        limit: u32,
        offset: u32,
    ) -> Result<Vec<CreditTransactionEntity>, AppError>;

    /// Get total transaction count for a user
    async fn count_transactions(
        &self,
        user_id: Uuid,
        currency: Option<&str>,
        tx_type: Option<&str>,
    ) -> Result<u64, AppError>;

    /// Get aggregate credit statistics (admin)
    async fn get_stats(&self) -> Result<CreditStats, AppError>;

    /// Get user credit statistics (user-facing analytics)
    async fn get_user_stats(
        &self,
        user_id: Uuid,
        currency: &str,
    ) -> Result<UserCreditStats, AppError>;

    /// Get all balances for a user (all currencies)
    async fn get_all_balances(&self, user_id: Uuid) -> Result<Vec<CreditBalanceEntity>, AppError>;

    /// Find a transaction by ID
    async fn find_transaction_by_id(
        &self,
        id: Uuid,
    ) -> Result<Option<CreditTransactionEntity>, AppError>;

    /// Find a transaction by idempotency key (user-scoped)
    async fn find_transaction_by_idempotency_key(
        &self,
        user_id: Uuid,
        idempotency_key: &str,
    ) -> Result<Option<CreditTransactionEntity>, AppError>;

    /// Sum positive adjustment amounts for a specific reference
    async fn sum_positive_adjustments_by_reference(
        &self,
        user_id: Uuid,
        currency: &str,
        reference_type: &str,
        reference_id: Uuid,
    ) -> Result<i64, AppError>;

    /// Sum positive adjustment amounts where reference_type starts with the given prefix.
    /// Used for referral reward cap enforcement across all referral subtypes.
    async fn sum_adjustments_by_reference_type_prefix(
        &self,
        user_id: Uuid,
        currency: &str,
        prefix: &str,
    ) -> Result<i64, AppError>;

    /// List transactions where reference_type starts with the given prefix.
    ///
    /// Returns up to `limit` transactions for `user_id` and `currency`, sorted newest-first,
    /// with `offset` for pagination.
    async fn list_by_reference_type_prefix(
        &self,
        user_id: Uuid,
        currency: &str,
        prefix: &str,
        limit: u32,
        offset: u32,
    ) -> Result<Vec<CreditTransactionEntity>, AppError>;

    /// Count transactions where reference_type starts with the given prefix.
    async fn count_by_reference_type_prefix(
        &self,
        user_id: Uuid,
        currency: &str,
        prefix: &str,
    ) -> Result<u64, AppError>;
}

/// In-memory credit repository for development/testing
pub struct InMemoryCreditRepository {
    balances: RwLock<HashMap<(Uuid, String), CreditBalanceEntity>>,
    transactions: RwLock<Vec<CreditTransactionEntity>>,
}

impl InMemoryCreditRepository {
    pub fn new() -> Self {
        Self {
            balances: RwLock::new(HashMap::new()),
            transactions: RwLock::new(Vec::new()),
        }
    }
}

impl Default for InMemoryCreditRepository {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl CreditRepository for InMemoryCreditRepository {
    async fn get_balance(&self, user_id: Uuid, currency: &str) -> Result<i64, AppError> {
        let balances = self.balances.read().await;
        Ok(balances
            .get(&(user_id, currency.to_string()))
            .map(|b| b.balance)
            .unwrap_or(0))
    }

    async fn get_balances(
        &self,
        user_ids: &[Uuid],
        currency: &str,
    ) -> Result<HashMap<Uuid, i64>, AppError> {
        let balances = self.balances.read().await;
        let mut out = HashMap::with_capacity(user_ids.len());
        let currency = currency.to_string();

        for user_id in user_ids {
            if let Some(balance) = balances.get(&(*user_id, currency.clone())) {
                out.insert(*user_id, balance.balance);
            }
        }

        Ok(out)
    }

    async fn get_or_create_balance(
        &self,
        user_id: Uuid,
        currency: &str,
    ) -> Result<CreditBalanceEntity, AppError> {
        let mut balances = self.balances.write().await;
        let key = (user_id, currency.to_string());

        if let Some(balance) = balances.get(&key) {
            return Ok(balance.clone());
        }

        let balance = CreditBalanceEntity {
            id: Uuid::new_v4(),
            user_id,
            balance: 0,
            held_balance: 0,
            currency: currency.to_string(),
            updated_at: Utc::now(),
        };

        balances.insert(key, balance.clone());
        Ok(balance)
    }

    async fn add_credit(
        &self,
        user_id: Uuid,
        amount: i64,
        currency: &str,
        tx: CreditTransactionEntity,
    ) -> Result<i64, AppError> {
        let mut balances = self.balances.write().await;
        let mut transactions = self.transactions.write().await;

        let key = (user_id, currency.to_string());

        let balance = balances.entry(key).or_insert_with(|| CreditBalanceEntity {
            id: Uuid::new_v4(),
            user_id,
            balance: 0,
            held_balance: 0,
            currency: currency.to_string(),
            updated_at: Utc::now(),
        });

        balance.balance += amount;
        balance.updated_at = Utc::now();

        transactions.push(tx);

        Ok(balance.balance)
    }

    async fn deduct_credit(
        &self,
        user_id: Uuid,
        amount: i64,
        currency: &str,
        tx: CreditTransactionEntity,
    ) -> Result<i64, AppError> {
        let mut balances = self.balances.write().await;
        let mut transactions = self.transactions.write().await;

        let key = (user_id, currency.to_string());

        let balance = balances
            .get_mut(&key)
            .ok_or_else(|| AppError::Validation("Insufficient credit balance".into()))?;

        // Check available balance (total - held)
        let available = balance.available();
        if available < amount {
            return Err(AppError::Validation(format!(
                "Insufficient credit balance: available {}, need {} (total: {}, held: {})",
                available, amount, balance.balance, balance.held_balance
            )));
        }

        balance.balance -= amount;
        balance.updated_at = Utc::now();

        transactions.push(tx);

        Ok(balance.balance)
    }

    async fn get_transactions(
        &self,
        user_id: Uuid,
        currency: Option<&str>,
        tx_type: Option<&str>,
        limit: u32,
        offset: u32,
    ) -> Result<Vec<CreditTransactionEntity>, AppError> {
        let limit = cap_limit(limit);
        let offset = cap_offset(offset);

        let transactions = self.transactions.read().await;
        let mut filtered: Vec<_> = transactions
            .iter()
            .filter(|t| {
                t.user_id == user_id
                    && currency.map_or(true, |c| t.currency == c)
                    && tx_type.map_or(true, |tt| t.tx_type.as_str() == tt)
            })
            .cloned()
            .collect();

        // Sort by created_at descending (newest first)
        filtered.sort_by(|a, b| b.created_at.cmp(&a.created_at));

        Ok(filtered
            .into_iter()
            .skip(offset as usize)
            .take(limit as usize)
            .collect())
    }

    async fn count_transactions(
        &self,
        user_id: Uuid,
        currency: Option<&str>,
        tx_type: Option<&str>,
    ) -> Result<u64, AppError> {
        let transactions = self.transactions.read().await;
        Ok(transactions
            .iter()
            .filter(|t| {
                t.user_id == user_id
                    && currency.map_or(true, |c| t.currency == c)
                    && tx_type.map_or(true, |tt| t.tx_type.as_str() == tt)
            })
            .count() as u64)
    }

    async fn get_stats(&self) -> Result<CreditStats, AppError> {
        let balances = self.balances.read().await;
        let transactions = self.transactions.read().await;

        let mut stats = CreditStats::default();

        // Count unique users with balance
        let users: std::collections::HashSet<_> = balances.keys().map(|(uid, _)| *uid).collect();
        stats.total_users_with_balance = users.len() as u64;

        // Sum all balances
        stats.total_outstanding_lamports = balances.values().map(|b| b.balance).sum();

        // Process transactions by currency
        for tx in transactions.iter() {
            let currency_stats = match tx.currency.to_uppercase().as_str() {
                "SOL" => &mut stats.sol,
                "USD" => &mut stats.usd,
                _ => continue, // Skip unknown currencies
            };

            match tx.tx_type {
                CreditTxType::Deposit => {
                    currency_stats.deposit_count += 1;
                    currency_stats.total_credited += tx.amount;
                }
                CreditTxType::Spend => {
                    currency_stats.spend_count += 1;
                    currency_stats.total_spent += tx.amount.abs();
                }
                CreditTxType::Adjustment => {
                    currency_stats.adjustment_count += 1;
                    if tx.amount >= 0 {
                        currency_stats.total_positive_adjustments += tx.amount;
                    } else {
                        currency_stats.total_negative_adjustments += tx.amount.abs();
                    }
                }
            }
        }

        // Calculate current outstanding for each currency
        for ((_user_id, currency), balance) in balances.iter() {
            let currency_stats = match currency.to_uppercase().as_str() {
                "SOL" => &mut stats.sol,
                "USD" => &mut stats.usd,
                _ => continue,
            };
            currency_stats.current_outstanding += balance.balance;
        }

        Ok(stats)
    }

    async fn get_user_stats(
        &self,
        user_id: Uuid,
        currency: &str,
    ) -> Result<UserCreditStats, AppError> {
        let balances = self.balances.read().await;
        let transactions = self.transactions.read().await;

        let mut stats = UserCreditStats {
            currency: currency.to_string(),
            ..Default::default()
        };

        // Get current balance
        if let Some(balance) = balances.get(&(user_id, currency.to_string())) {
            stats.current_balance = balance.balance;
        }

        // Process user's transactions for this currency
        for tx in transactions.iter() {
            if tx.user_id != user_id || tx.currency.to_uppercase() != currency.to_uppercase() {
                continue;
            }

            match tx.tx_type {
                CreditTxType::Deposit => {
                    stats.deposit_count += 1;
                    stats.total_deposited += tx.amount;
                }
                CreditTxType::Spend => {
                    stats.spend_count += 1;
                    stats.total_spent += tx.amount.abs();
                }
                CreditTxType::Adjustment => {
                    if tx.amount > 0 {
                        stats.total_refunds += tx.amount;
                    }
                }
            }
        }

        Ok(stats)
    }

    async fn get_all_balances(&self, user_id: Uuid) -> Result<Vec<CreditBalanceEntity>, AppError> {
        let balances = self.balances.read().await;
        Ok(balances
            .iter()
            .filter(|((uid, _), _)| *uid == user_id)
            .map(|(_, b)| b.clone())
            .collect())
    }

    async fn find_transaction_by_id(
        &self,
        id: Uuid,
    ) -> Result<Option<CreditTransactionEntity>, AppError> {
        let transactions = self.transactions.read().await;
        Ok(transactions.iter().find(|t| t.id == id).cloned())
    }

    async fn find_transaction_by_idempotency_key(
        &self,
        user_id: Uuid,
        idempotency_key: &str,
    ) -> Result<Option<CreditTransactionEntity>, AppError> {
        let transactions = self.transactions.read().await;
        Ok(transactions
            .iter()
            .find(|t| {
                t.user_id == user_id
                    && t.idempotency_key
                        .as_deref()
                        .map(|k| k == idempotency_key)
                        .unwrap_or(false)
            })
            .cloned())
    }

    async fn sum_positive_adjustments_by_reference(
        &self,
        user_id: Uuid,
        currency: &str,
        reference_type: &str,
        reference_id: Uuid,
    ) -> Result<i64, AppError> {
        let transactions = self.transactions.read().await;
        let sum = transactions
            .iter()
            .filter(|t| {
                t.user_id == user_id
                    && t.tx_type == CreditTxType::Adjustment
                    && t.amount > 0
                    && t.currency.eq_ignore_ascii_case(currency)
                    && t.reference_type
                        .as_deref()
                        .map(|rt| rt == reference_type)
                        .unwrap_or(false)
                    && t.reference_id == Some(reference_id)
            })
            .map(|t| t.amount)
            .sum();
        Ok(sum)
    }

    async fn sum_adjustments_by_reference_type_prefix(
        &self,
        user_id: Uuid,
        currency: &str,
        prefix: &str,
    ) -> Result<i64, AppError> {
        let transactions = self.transactions.read().await;
        let sum = transactions
            .iter()
            .filter(|t| {
                t.user_id == user_id
                    && t.tx_type == CreditTxType::Adjustment
                    && t.amount > 0
                    && t.currency.eq_ignore_ascii_case(currency)
                    && t.reference_type
                        .as_deref()
                        .map(|rt| rt.starts_with(prefix))
                        .unwrap_or(false)
            })
            .map(|t| t.amount)
            .sum();
        Ok(sum)
    }

    async fn list_by_reference_type_prefix(
        &self,
        user_id: Uuid,
        currency: &str,
        prefix: &str,
        limit: u32,
        offset: u32,
    ) -> Result<Vec<CreditTransactionEntity>, AppError> {
        let limit = cap_limit(limit);
        let offset = cap_offset(offset);

        let transactions = self.transactions.read().await;
        let mut filtered: Vec<_> = transactions
            .iter()
            .filter(|t| {
                t.user_id == user_id
                    && t.currency.eq_ignore_ascii_case(currency)
                    && t.reference_type
                        .as_deref()
                        .map(|rt| rt.starts_with(prefix))
                        .unwrap_or(false)
            })
            .cloned()
            .collect();

        filtered.sort_by(|a, b| b.created_at.cmp(&a.created_at));

        Ok(filtered
            .into_iter()
            .skip(offset as usize)
            .take(limit as usize)
            .collect())
    }

    async fn count_by_reference_type_prefix(
        &self,
        user_id: Uuid,
        currency: &str,
        prefix: &str,
    ) -> Result<u64, AppError> {
        let transactions = self.transactions.read().await;
        Ok(transactions
            .iter()
            .filter(|t| {
                t.user_id == user_id
                    && t.currency.eq_ignore_ascii_case(currency)
                    && t.reference_type
                        .as_deref()
                        .map(|rt| rt.starts_with(prefix))
                        .unwrap_or(false)
            })
            .count() as u64)
    }
}

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

    #[tokio::test]
    async fn test_get_balance_empty() {
        let repo = InMemoryCreditRepository::new();
        let user_id = Uuid::new_v4();

        let balance = repo.get_balance(user_id, "SOL").await.unwrap();
        assert_eq!(balance, 0);
    }

    #[tokio::test]
    async fn test_add_credit() {
        let repo = InMemoryCreditRepository::new();
        let user_id = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let note_id = Uuid::new_v4();

        let tx = CreditTransactionEntity::new_deposit(user_id, 1000000, "SOL", session_id, note_id);
        let new_balance = repo.add_credit(user_id, 1000000, "SOL", tx).await.unwrap();

        assert_eq!(new_balance, 1000000);

        let balance = repo.get_balance(user_id, "SOL").await.unwrap();
        assert_eq!(balance, 1000000);
    }

    #[tokio::test]
    async fn test_get_balances_returns_existing_users() {
        let repo = InMemoryCreditRepository::new();
        let user_a = Uuid::new_v4();
        let user_b = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let note_id = Uuid::new_v4();

        let tx = CreditTransactionEntity::new_deposit(user_a, 500, "SOL", session_id, note_id);
        repo.add_credit(user_a, 500, "SOL", tx).await.unwrap();

        let balances = repo.get_balances(&[user_a, user_b], "SOL").await.unwrap();
        assert_eq!(balances.get(&user_a), Some(&500));
        assert!(!balances.contains_key(&user_b));
    }

    #[tokio::test]
    async fn test_get_balances_empty_input() {
        let repo = InMemoryCreditRepository::new();
        let balances = repo.get_balances(&[], "SOL").await.unwrap();
        assert!(balances.is_empty());
    }

    #[tokio::test]
    async fn test_deduct_credit() {
        let repo = InMemoryCreditRepository::new();
        let user_id = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let note_id = Uuid::new_v4();

        // Add credit first
        let add_tx =
            CreditTransactionEntity::new_deposit(user_id, 1000000, "SOL", session_id, note_id);
        repo.add_credit(user_id, 1000000, "SOL", add_tx)
            .await
            .unwrap();

        // Deduct credit
        let spend_tx = CreditTransactionEntity::new_spend(user_id, 300000, "SOL", None);
        let new_balance = repo
            .deduct_credit(user_id, 300000, "SOL", spend_tx)
            .await
            .unwrap();

        assert_eq!(new_balance, 700000);
    }

    #[tokio::test]
    async fn test_deduct_insufficient_balance() {
        let repo = InMemoryCreditRepository::new();
        let user_id = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let note_id = Uuid::new_v4();

        // Add credit first
        let add_tx =
            CreditTransactionEntity::new_deposit(user_id, 1000000, "SOL", session_id, note_id);
        repo.add_credit(user_id, 1000000, "SOL", add_tx)
            .await
            .unwrap();

        // Try to deduct more than balance
        let spend_tx = CreditTransactionEntity::new_spend(user_id, 2000000, "SOL", None);
        let result = repo.deduct_credit(user_id, 2000000, "SOL", spend_tx).await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_transaction_history() {
        let repo = InMemoryCreditRepository::new();
        let user_id = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let note_id = Uuid::new_v4();

        // Add multiple transactions
        let tx1 =
            CreditTransactionEntity::new_deposit(user_id, 1000000, "SOL", session_id, note_id);
        repo.add_credit(user_id, 1000000, "SOL", tx1).await.unwrap();

        let tx2 = CreditTransactionEntity::new_spend(user_id, 100000, "SOL", None);
        repo.deduct_credit(user_id, 100000, "SOL", tx2)
            .await
            .unwrap();

        let transactions = repo
            .get_transactions(user_id, Some("SOL"), None, 10, 0)
            .await
            .unwrap();
        assert_eq!(transactions.len(), 2);

        let count = repo
            .count_transactions(user_id, Some("SOL"), None)
            .await
            .unwrap();
        assert_eq!(count, 2);
    }

    #[tokio::test]
    async fn test_transaction_history_caps_limit() {
        use crate::repositories::pagination::DEFAULT_MAX_PAGE_SIZE;

        let repo = InMemoryCreditRepository::new();
        let user_id = Uuid::new_v4();
        let session_id = Uuid::new_v4();
        let note_id = Uuid::new_v4();

        for _ in 0..(DEFAULT_MAX_PAGE_SIZE + 10) {
            let tx = CreditTransactionEntity::new_deposit(user_id, 1, "SOL", session_id, note_id);
            repo.add_credit(user_id, 1, "SOL", tx).await.unwrap();
        }

        let transactions = repo
            .get_transactions(user_id, Some("SOL"), None, 10_000, 0)
            .await
            .unwrap();
        assert_eq!(transactions.len() as u32, DEFAULT_MAX_PAGE_SIZE);
    }
}