stateset-core 1.22.0

Core domain models and business logic for StateSet iCommerce
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
//! Subscription domain models
//!
//! Comprehensive subscription management supporting:
//! - Subscription plans with flexible billing intervals
//! - Customer subscriptions with lifecycle management
//! - Billing cycles and payment tracking
//! - Pause, resume, skip, and cancel functionality
//! - Trial periods and promotional pricing
//! - Product swapping and quantity changes

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use stateset_primitives::{CurrencyCode, CustomerId, OrderId, ProductId, SubscriptionId};
use strum::{Display, EnumString};
use uuid::Uuid;

use super::Address;

// ============================================================================
// Subscription Enums
// ============================================================================

/// Billing interval for subscriptions
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, Display, EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[non_exhaustive]
pub enum BillingInterval {
    /// Weekly billing
    Weekly,
    /// Every two weeks
    #[strum(serialize = "biweekly", serialize = "bi_weekly", serialize = "bi-weekly")]
    Biweekly,
    /// Monthly billing
    #[default]
    Monthly,
    /// Every two months
    #[strum(serialize = "bimonthly", serialize = "bi_monthly", serialize = "bi-monthly")]
    Bimonthly,
    /// Quarterly (every 3 months)
    Quarterly,
    /// Every 6 months
    #[strum(serialize = "semiannual", serialize = "semi_annual", serialize = "semi-annual")]
    Semiannual,
    /// Annual billing
    #[strum(serialize = "annual", serialize = "yearly")]
    Annual,
    /// Custom interval in days
    Custom,
}

impl BillingInterval {
    /// Get the number of days in this interval
    #[must_use]
    pub const fn days(&self) -> i64 {
        match self {
            Self::Weekly => 7,
            Self::Biweekly => 14,
            Self::Monthly => 30,
            Self::Bimonthly => 60,
            Self::Quarterly => 90,
            Self::Semiannual => 180,
            Self::Annual => 365,
            Self::Custom => 30, // Default, should use custom_interval_days
        }
    }
}

/// Status of a subscription
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, Display, EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[non_exhaustive]
pub enum SubscriptionStatus {
    /// Trial period (no charge yet)
    Trial,
    /// Active and billing normally
    #[default]
    Active,
    /// Paused by customer (no billing, can resume)
    Paused,
    /// Past due - payment failed, in retry period
    #[strum(serialize = "past_due", serialize = "pastdue")]
    PastDue,
    /// Cancelled - will end at period end
    #[strum(serialize = "cancelled", serialize = "canceled")]
    Cancelled,
    /// Expired - subscription has ended
    Expired,
    /// Pending - awaiting initial payment/activation
    Pending,
}

impl SubscriptionStatus {
    /// Check if a status transition is allowed.
    #[must_use]
    pub fn can_transition_to(self, next: Self) -> bool {
        if self == next {
            return true;
        }
        match self {
            Self::Pending => matches!(next, Self::Trial | Self::Active | Self::Cancelled),
            Self::Trial => matches!(next, Self::Active | Self::Cancelled | Self::Expired),
            Self::Active => {
                matches!(next, Self::Paused | Self::PastDue | Self::Cancelled | Self::Expired)
            }
            Self::Paused => matches!(next, Self::Active | Self::Cancelled),
            Self::PastDue => matches!(next, Self::Active | Self::Cancelled | Self::Expired),
            Self::Cancelled | Self::Expired => false,
        }
    }

    /// Returns true if this status is a terminal state.
    #[must_use]
    pub const fn is_terminal(self) -> bool {
        matches!(self, Self::Cancelled | Self::Expired)
    }
}

/// Status of a subscription plan
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, Display, EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[non_exhaustive]
pub enum PlanStatus {
    /// Draft - not yet available
    Draft,
    /// Active - available for new subscriptions
    #[default]
    Active,
    /// Archived - no new subscriptions, existing continue
    Archived,
}

/// Status of a billing cycle
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, Display, EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[non_exhaustive]
pub enum BillingCycleStatus {
    /// Scheduled for future billing
    #[default]
    Scheduled,
    /// Payment is being processed
    Processing,
    /// Successfully billed
    Paid,
    /// Payment failed
    Failed,
    /// Skipped by customer request
    Skipped,
    /// Refunded
    Refunded,
    /// Voided/cancelled
    Voided,
}

/// Type of subscription event
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Display, EnumString)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[non_exhaustive]
pub enum SubscriptionEventType {
    /// Subscription created
    Created,
    /// Subscription activated
    Activated,
    /// Trial started
    #[strum(serialize = "trial_started", serialize = "trialstarted")]
    TrialStarted,
    /// Trial ended
    #[strum(serialize = "trial_ended", serialize = "trialended")]
    TrialEnded,
    /// Successfully renewed/billed
    Renewed,
    /// Payment failed
    #[strum(serialize = "payment_failed", serialize = "paymentfailed")]
    PaymentFailed,
    /// Payment retry succeeded
    #[strum(serialize = "payment_retry_succeeded", serialize = "paymentretrysucceeded")]
    PaymentRetrySucceeded,
    /// Subscription paused
    Paused,
    /// Subscription resumed
    Resumed,
    /// Upcoming renewal skipped
    Skipped,
    /// Subscription cancelled
    #[strum(serialize = "cancelled", serialize = "canceled")]
    Cancelled,
    /// Subscription expired
    Expired,
    /// Plan changed
    #[strum(serialize = "plan_changed", serialize = "planchanged")]
    PlanChanged,
    /// Items modified
    #[strum(serialize = "items_modified", serialize = "itemsmodified")]
    ItemsModified,
    /// Quantity changed
    #[strum(serialize = "quantity_changed", serialize = "quantitychanged")]
    QuantityChanged,
    /// Address updated
    #[strum(serialize = "address_updated", serialize = "addressupdated")]
    AddressUpdated,
    /// Payment method updated
    #[strum(serialize = "payment_method_updated", serialize = "paymentmethodupdated")]
    PaymentMethodUpdated,
    /// Discount applied
    #[strum(serialize = "discount_applied", serialize = "discountapplied")]
    DiscountApplied,
    /// Discount removed
    #[strum(serialize = "discount_removed", serialize = "discountremoved")]
    DiscountRemoved,
    /// Refund issued
    Refunded,
}

// ============================================================================
// Subscription Plan Model
// ============================================================================

/// A subscription plan template
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubscriptionPlan {
    pub id: Uuid,
    /// Unique code for the plan
    pub code: String,
    /// Display name
    pub name: String,
    /// Description
    pub description: Option<String>,
    pub status: PlanStatus,

    // Billing configuration
    pub billing_interval: BillingInterval,
    /// Custom interval in days (when `billing_interval` is Custom)
    pub custom_interval_days: Option<i32>,
    /// Base price per billing cycle
    pub price: Decimal,
    /// Setup/activation fee (charged once)
    pub setup_fee: Option<Decimal>,
    pub currency: CurrencyCode,

    // Trial configuration
    /// Trial period in days (0 = no trial)
    pub trial_days: i32,
    /// Whether payment method is required for trial
    pub trial_requires_payment_method: bool,

    // Limits
    /// Minimum number of billing cycles
    pub min_cycles: Option<i32>,
    /// Maximum number of billing cycles (None = unlimited)
    pub max_cycles: Option<i32>,

    // Included products/items
    pub items: Vec<SubscriptionPlanItem>,

    // Discounts
    /// Percentage discount for this plan
    pub discount_percent: Option<Decimal>,
    /// Fixed discount amount
    pub discount_amount: Option<Decimal>,

    // Metadata
    pub metadata: Option<serde_json::Value>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// An item included in a subscription plan
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubscriptionPlanItem {
    pub id: Uuid,
    pub plan_id: Uuid,
    pub product_id: ProductId,
    pub variant_id: Option<Uuid>,
    pub sku: String,
    pub name: String,
    /// Default quantity
    pub quantity: i32,
    /// Minimum quantity (for customizable plans)
    pub min_quantity: Option<i32>,
    /// Maximum quantity (for customizable plans)
    pub max_quantity: Option<i32>,
    /// Whether customer can remove this item
    pub is_required: bool,
    /// Unit price override (None = use plan price)
    pub unit_price: Option<Decimal>,
}

// ============================================================================
// Subscription Model
// ============================================================================

/// A customer's subscription
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Subscription {
    pub id: SubscriptionId,
    /// Human-readable subscription number
    pub subscription_number: String,
    pub customer_id: CustomerId,
    pub plan_id: Uuid,
    /// Snapshot of plan name at time of subscription
    pub plan_name: String,
    pub status: SubscriptionStatus,

    // Billing
    pub billing_interval: BillingInterval,
    pub custom_interval_days: Option<i32>,
    /// Current price per cycle
    pub price: Decimal,
    pub currency: CurrencyCode,
    /// Payment method ID (from payment provider)
    pub payment_method_id: Option<String>,

    // Dates
    /// When the subscription started
    pub started_at: DateTime<Utc>,
    /// When current billing period started
    pub current_period_start: DateTime<Utc>,
    /// When current billing period ends
    pub current_period_end: DateTime<Utc>,
    /// Next billing date
    pub next_billing_date: Option<DateTime<Utc>>,
    /// Trial end date (if applicable)
    pub trial_ends_at: Option<DateTime<Utc>>,
    /// When subscription was cancelled (if applicable)
    pub cancelled_at: Option<DateTime<Utc>>,
    /// When subscription ends (for cancelled subscriptions)
    pub ends_at: Option<DateTime<Utc>>,
    /// When subscription was paused
    pub paused_at: Option<DateTime<Utc>>,
    /// When to auto-resume (if paused with a date)
    pub resume_at: Option<DateTime<Utc>>,

    // Cycle tracking
    /// Number of completed billing cycles
    pub billing_cycle_count: i32,
    /// Number of failed payment attempts in current cycle
    pub failed_payment_attempts: i32,

    // Items
    pub items: Vec<SubscriptionItem>,

    // Addresses
    pub shipping_address: Option<Address>,
    pub billing_address: Option<Address>,

    // Applied discounts
    pub discount_percent: Option<Decimal>,
    pub discount_amount: Option<Decimal>,
    /// Coupon code applied (if any)
    pub coupon_code: Option<String>,

    // Metadata
    pub metadata: Option<serde_json::Value>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// A line item in a subscription
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubscriptionItem {
    pub id: Uuid,
    pub subscription_id: SubscriptionId,
    pub product_id: ProductId,
    pub variant_id: Option<Uuid>,
    pub sku: String,
    pub name: String,
    pub quantity: i32,
    /// Price per unit
    pub unit_price: Decimal,
    /// Line total (quantity * `unit_price`)
    pub line_total: Decimal,
}

// ============================================================================
// Billing Cycle Model
// ============================================================================

/// A billing cycle/period for a subscription
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BillingCycle {
    pub id: Uuid,
    pub subscription_id: SubscriptionId,
    /// Cycle number (1, 2, 3, ...)
    pub cycle_number: i32,
    pub status: BillingCycleStatus,

    // Period
    pub period_start: DateTime<Utc>,
    pub period_end: DateTime<Utc>,
    /// When billing was attempted
    pub billed_at: Option<DateTime<Utc>>,

    // Amounts
    pub subtotal: Decimal,
    pub discount: Decimal,
    pub tax: Decimal,
    pub total: Decimal,
    pub currency: CurrencyCode,

    // Payment
    /// Payment ID from payment provider
    pub payment_id: Option<String>,
    /// Order ID if an order was created
    pub order_id: Option<OrderId>,
    /// Invoice ID if an invoice was created
    pub invoice_id: Option<Uuid>,

    // Failure tracking
    pub failure_reason: Option<String>,
    pub retry_count: i32,
    pub next_retry_at: Option<DateTime<Utc>>,

    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

// ============================================================================
// Subscription Event (Audit Log)
// ============================================================================

/// An event in a subscription's history
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubscriptionEvent {
    pub id: Uuid,
    pub subscription_id: SubscriptionId,
    pub event_type: SubscriptionEventType,
    /// Human-readable description
    pub description: String,
    /// Detailed event data
    pub data: Option<serde_json::Value>,
    /// Who triggered this event (`customer_id`, "system", "admin")
    pub triggered_by: Option<String>,
    pub created_at: DateTime<Utc>,
}

// ============================================================================
// CRUD DTOs
// ============================================================================

/// Create a new subscription plan
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CreateSubscriptionPlan {
    pub code: Option<String>,
    pub name: String,
    pub description: Option<String>,
    pub billing_interval: BillingInterval,
    pub custom_interval_days: Option<i32>,
    pub price: Decimal,
    pub setup_fee: Option<Decimal>,
    pub currency: Option<CurrencyCode>,
    pub trial_days: Option<i32>,
    pub trial_requires_payment_method: Option<bool>,
    pub min_cycles: Option<i32>,
    pub max_cycles: Option<i32>,
    pub items: Option<Vec<CreateSubscriptionPlanItem>>,
    pub discount_percent: Option<Decimal>,
    pub discount_amount: Option<Decimal>,
    pub metadata: Option<serde_json::Value>,
}

/// Item definition for creating a subscription plan
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateSubscriptionPlanItem {
    pub product_id: ProductId,
    pub variant_id: Option<Uuid>,
    pub sku: String,
    pub name: String,
    pub quantity: i32,
    pub min_quantity: Option<i32>,
    pub max_quantity: Option<i32>,
    pub is_required: Option<bool>,
    pub unit_price: Option<Decimal>,
}

/// Update a subscription plan
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UpdateSubscriptionPlan {
    pub name: Option<String>,
    pub description: Option<String>,
    pub status: Option<PlanStatus>,
    pub price: Option<Decimal>,
    pub setup_fee: Option<Decimal>,
    pub trial_days: Option<i32>,
    pub trial_requires_payment_method: Option<bool>,
    pub min_cycles: Option<i32>,
    pub max_cycles: Option<i32>,
    pub discount_percent: Option<Decimal>,
    pub discount_amount: Option<Decimal>,
    pub metadata: Option<serde_json::Value>,
}

/// Create a new subscription
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateSubscription {
    pub customer_id: CustomerId,
    pub plan_id: Uuid,
    /// Override plan items with custom items
    pub items: Option<Vec<CreateSubscriptionItem>>,
    /// Override plan price
    pub price: Option<Decimal>,
    pub payment_method_id: Option<String>,
    pub shipping_address: Option<Address>,
    pub billing_address: Option<Address>,
    /// Skip trial period
    pub skip_trial: Option<bool>,
    /// Start date (default: now)
    pub start_date: Option<DateTime<Utc>>,
    /// Coupon code to apply
    pub coupon_code: Option<String>,
    pub metadata: Option<serde_json::Value>,
}

impl Default for CreateSubscription {
    fn default() -> Self {
        Self {
            customer_id: CustomerId::nil(),
            plan_id: Uuid::nil(),
            items: None,
            price: None,
            payment_method_id: None,
            shipping_address: None,
            billing_address: None,
            skip_trial: None,
            start_date: None,
            coupon_code: None,
            metadata: None,
        }
    }
}

/// Item override when creating a subscription
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateSubscriptionItem {
    pub product_id: ProductId,
    pub variant_id: Option<Uuid>,
    pub sku: String,
    pub name: String,
    pub quantity: i32,
    pub unit_price: Option<Decimal>,
}

/// Update a subscription
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UpdateSubscription {
    pub status: Option<SubscriptionStatus>,
    pub price: Option<Decimal>,
    pub payment_method_id: Option<String>,
    pub shipping_address: Option<Address>,
    pub billing_address: Option<Address>,
    pub next_billing_date: Option<DateTime<Utc>>,
    pub discount_percent: Option<Decimal>,
    pub discount_amount: Option<Decimal>,
    pub coupon_code: Option<String>,
    pub metadata: Option<serde_json::Value>,
}

/// Pause subscription request
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PauseSubscription {
    /// Optional resume date
    pub resume_at: Option<DateTime<Utc>>,
    pub reason: Option<String>,
}

/// Cancel subscription request
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CancelSubscription {
    /// Cancel immediately or at period end
    pub immediate: Option<bool>,
    pub reason: Option<String>,
    /// Feedback for cancellation
    pub feedback: Option<String>,
}

/// Skip next billing cycle
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SkipBillingCycle {
    pub reason: Option<String>,
}

/// Create a billing cycle for a subscription.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateBillingCycle {
    pub subscription_id: SubscriptionId,
    pub cycle_number: i32,
    pub period_start: DateTime<Utc>,
    pub period_end: DateTime<Utc>,
}

/// Change subscription plan
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChangeSubscriptionPlan {
    pub new_plan_id: Uuid,
    /// Prorate charges (default: true)
    pub prorate: Option<bool>,
    /// Apply immediately or at next billing
    pub immediate: Option<bool>,
}

/// Modify subscription items
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModifySubscriptionItems {
    /// Items to add
    pub add: Option<Vec<CreateSubscriptionItem>>,
    /// Item IDs to remove
    pub remove: Option<Vec<Uuid>>,
    /// Items to update (id -> new quantity)
    pub update_quantities: Option<Vec<UpdateItemQuantity>>,
}

/// Update quantity for an existing subscription item
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateItemQuantity {
    pub item_id: Uuid,
    pub quantity: i32,
}

// ============================================================================
// Filter DTOs
// ============================================================================

/// Filter for listing subscription plans
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SubscriptionPlanFilter {
    pub status: Option<PlanStatus>,
    pub billing_interval: Option<BillingInterval>,
    pub search: Option<String>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

/// Filter for listing subscriptions
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SubscriptionFilter {
    pub customer_id: Option<CustomerId>,
    pub plan_id: Option<Uuid>,
    pub status: Option<SubscriptionStatus>,
    pub from_date: Option<DateTime<Utc>>,
    pub to_date: Option<DateTime<Utc>>,
    pub search: Option<String>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;
    use std::str::FromStr;

    #[test]
    fn test_billing_interval_from_str() {
        assert_eq!(BillingInterval::from_str("biweekly").unwrap(), BillingInterval::Biweekly);
        assert_eq!(BillingInterval::from_str("semi-annual").unwrap(), BillingInterval::Semiannual);
    }

    #[test]
    fn test_subscription_status_from_str() {
        assert_eq!(SubscriptionStatus::from_str("past_due").unwrap(), SubscriptionStatus::PastDue);
        assert_eq!(SubscriptionStatus::from_str("pastdue").unwrap(), SubscriptionStatus::PastDue);
        assert_eq!(
            SubscriptionStatus::from_str("canceled").unwrap(),
            SubscriptionStatus::Cancelled
        );
    }

    #[test]
    fn test_plan_status_from_str() {
        assert_eq!(PlanStatus::from_str("draft").unwrap(), PlanStatus::Draft);
        assert_eq!(PlanStatus::from_str("archived").unwrap(), PlanStatus::Archived);
    }

    #[test]
    fn test_billing_cycle_status_from_str() {
        assert_eq!(
            BillingCycleStatus::from_str("processing").unwrap(),
            BillingCycleStatus::Processing
        );
        assert_eq!(BillingCycleStatus::from_str("voided").unwrap(), BillingCycleStatus::Voided);
    }

    #[test]
    fn test_subscription_event_type_from_str() {
        assert_eq!(
            SubscriptionEventType::from_str("trial_started").unwrap(),
            SubscriptionEventType::TrialStarted
        );
        assert_eq!(
            SubscriptionEventType::from_str("trialstarted").unwrap(),
            SubscriptionEventType::TrialStarted
        );
        assert_eq!(
            SubscriptionEventType::from_str("payment_retry_succeeded").unwrap(),
            SubscriptionEventType::PaymentRetrySucceeded
        );
    }

    #[test]
    fn test_generate_subscription_number_prefix_and_shape() {
        let generated = generate_subscription_number();
        assert!(generated.starts_with("SUB-"));
        assert!(generated.len() > 12);
    }

    #[test]
    fn test_generate_subscription_number_sample_uniqueness() {
        let mut generated = HashSet::new();
        for _ in 0..1000 {
            generated.insert(generate_subscription_number());
        }
        assert_eq!(generated.len(), 1000);
    }

    #[test]
    fn subscription_status_valid_transitions() {
        use SubscriptionStatus::*;
        assert!(Pending.can_transition_to(Trial));
        assert!(Pending.can_transition_to(Active));
        assert!(Pending.can_transition_to(Cancelled));
        assert!(Trial.can_transition_to(Active));
        assert!(Trial.can_transition_to(Cancelled));
        assert!(Trial.can_transition_to(Expired));
        assert!(Active.can_transition_to(Paused));
        assert!(Active.can_transition_to(PastDue));
        assert!(Active.can_transition_to(Cancelled));
        assert!(Active.can_transition_to(Expired));
        assert!(Paused.can_transition_to(Active));
        assert!(Paused.can_transition_to(Cancelled));
        assert!(PastDue.can_transition_to(Active));
        assert!(PastDue.can_transition_to(Cancelled));
        assert!(PastDue.can_transition_to(Expired));
    }

    #[test]
    fn subscription_status_invalid_transitions() {
        use SubscriptionStatus::*;
        assert!(!Pending.can_transition_to(Paused));
        assert!(!Pending.can_transition_to(PastDue));
        assert!(!Trial.can_transition_to(Paused));
        assert!(!Paused.can_transition_to(Trial));
        assert!(!Cancelled.can_transition_to(Active));
        assert!(!Expired.can_transition_to(Active));
    }

    #[test]
    fn subscription_status_terminal_states() {
        use SubscriptionStatus::*;
        assert!(Cancelled.is_terminal());
        assert!(Expired.is_terminal());
        assert!(!Pending.is_terminal());
        assert!(!Trial.is_terminal());
        assert!(!Active.is_terminal());
        assert!(!Paused.is_terminal());
        assert!(!PastDue.is_terminal());
    }
}

/// Filter for listing billing cycles
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BillingCycleFilter {
    pub subscription_id: Option<SubscriptionId>,
    pub status: Option<BillingCycleStatus>,
    pub from_date: Option<DateTime<Utc>>,
    pub to_date: Option<DateTime<Utc>>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Generate a unique subscription number
#[must_use]
pub fn generate_subscription_number() -> String {
    let timestamp_ms = Utc::now().timestamp_millis();
    let id = Uuid::new_v4();
    let bytes = id.as_bytes();
    let random = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
    format!("SUB-{timestamp_ms}-{random:08X}")
}

/// Generate a unique plan code
#[must_use]
pub fn generate_plan_code(name: &str) -> String {
    let slug: String = name
        .to_uppercase()
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == ' ')
        .take(20)
        .collect::<String>()
        .trim()
        .replace(' ', "-");

    let id = Uuid::new_v4();
    let bytes = id.as_bytes();
    let random = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) % 10000;

    if slug.is_empty() { format!("PLAN-{random:04}") } else { format!("{slug}-{random:04}") }
}

impl Subscription {
    /// Check if subscription is in an active billing state
    #[must_use]
    pub const fn is_active(&self) -> bool {
        matches!(self.status, SubscriptionStatus::Active | SubscriptionStatus::Trial)
    }

    /// Check if subscription can be paused
    #[must_use]
    pub const fn can_pause(&self) -> bool {
        matches!(self.status, SubscriptionStatus::Active | SubscriptionStatus::Trial)
    }

    /// Check if subscription can be resumed
    #[must_use]
    pub fn can_resume(&self) -> bool {
        self.status == SubscriptionStatus::Paused
    }

    /// Check if subscription can be cancelled
    #[must_use]
    pub const fn can_cancel(&self) -> bool {
        !matches!(self.status, SubscriptionStatus::Cancelled | SubscriptionStatus::Expired)
    }

    /// Check if subscription is in trial period
    #[must_use]
    pub fn is_in_trial(&self) -> bool {
        if self.status != SubscriptionStatus::Trial {
            return false;
        }

        if let Some(trial_ends) = self.trial_ends_at {
            return Utc::now() < trial_ends;
        }

        false
    }

    /// Calculate remaining trial days
    #[must_use]
    pub fn trial_days_remaining(&self) -> Option<i64> {
        if !self.is_in_trial() {
            return None;
        }

        self.trial_ends_at.map(|ends| {
            let now = Utc::now();
            if ends > now { (ends - now).num_days() } else { 0 }
        })
    }

    /// Calculate total subscription value
    #[must_use]
    pub fn calculate_total(&self) -> Decimal {
        self.items.iter().map(|item| item.line_total).sum()
    }

    /// Get next billing amount (after discounts)
    #[must_use]
    pub fn next_billing_amount(&self) -> Decimal {
        let subtotal = self.calculate_total();
        let mut total = subtotal;

        if let Some(pct) = self.discount_percent {
            total -= subtotal * pct;
        }
        if let Some(amt) = self.discount_amount {
            total -= amt;
        }

        if total < Decimal::ZERO { Decimal::ZERO } else { total }
    }
}

impl SubscriptionItem {
    /// Calculate line total
    #[must_use]
    pub fn calculate_total(quantity: i32, unit_price: Decimal) -> Decimal {
        unit_price * Decimal::from(quantity)
    }
}

impl BillingCycle {
    /// Check if cycle can be refunded
    #[must_use]
    pub fn can_refund(&self) -> bool {
        self.status == BillingCycleStatus::Paid
    }

    /// Check if cycle can be retried
    #[must_use]
    pub fn can_retry(&self) -> bool {
        self.status == BillingCycleStatus::Failed
    }
}

// ============================================================================
// Validation
// ============================================================================

use crate::validation::{Validate, ValidationBuilder};

/// Shared pricing checks: money fields non-negative, `discount_percent` a
/// fraction in `[0, 1]` (the billing computation multiplies it directly by
/// the subtotal, so `10` would mean 1000%).
fn pricing_checks(
    builder: ValidationBuilder,
    price: Option<Decimal>,
    setup_fee: Option<Decimal>,
    discount_percent: Option<Decimal>,
    discount_amount: Option<Decimal>,
) -> ValidationBuilder {
    builder
        .check("price", price.is_none_or(|p| p >= Decimal::ZERO), "cannot be negative")
        .check("setup_fee", setup_fee.is_none_or(|f| f >= Decimal::ZERO), "cannot be negative")
        .check(
            "discount_percent",
            discount_percent.is_none_or(|p| p >= Decimal::ZERO && p <= Decimal::ONE),
            "must be a fraction between 0 and 1",
        )
        .check(
            "discount_amount",
            discount_amount.is_none_or(|a| a >= Decimal::ZERO),
            "cannot be negative",
        )
}

impl Validate for CreateSubscriptionPlan {
    fn validate(&self) -> crate::Result<()> {
        pricing_checks(
            ValidationBuilder::new(),
            Some(self.price),
            self.setup_fee,
            self.discount_percent,
            self.discount_amount,
        )
        .build()
    }
}

impl Validate for UpdateSubscriptionPlan {
    fn validate(&self) -> crate::Result<()> {
        pricing_checks(
            ValidationBuilder::new(),
            self.price,
            self.setup_fee,
            self.discount_percent,
            self.discount_amount,
        )
        .build()
    }
}

impl Validate for CreateSubscription {
    fn validate(&self) -> crate::Result<()> {
        pricing_checks(ValidationBuilder::new(), self.price, None, None, None).build()
    }
}

impl Validate for UpdateSubscription {
    fn validate(&self) -> crate::Result<()> {
        pricing_checks(
            ValidationBuilder::new(),
            self.price,
            None,
            self.discount_percent,
            self.discount_amount,
        )
        .build()
    }
}