stateset-core 0.8.1

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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
//! Tax calculation engine types
//!
//! Provides comprehensive tax support including:
//! - Multi-jurisdiction tax rates (US sales tax, EU VAT, etc.)
//! - Product tax categories (taxable, exempt, reduced rate)
//! - Customer tax exemptions (B2B, non-profits)
//! - Tax-inclusive vs tax-exclusive pricing
//! - Compound and tiered tax rules

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

// ============================================================================
// Tax Types and Enums
// ============================================================================

/// Types of taxes supported
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, Display, EnumString, Serialize, Deserialize, Default,
)]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TaxType {
    /// US Sales Tax (state/local)
    #[default]
    SalesTax,
    /// Value Added Tax (EU, UK, etc.)
    Vat,
    /// Goods and Services Tax (Canada, Australia, India)
    Gst,
    /// Harmonized Sales Tax (Canadian provinces)
    Hst,
    /// Provincial Sales Tax (Canadian provinces)
    Pst,
    /// Quebec Sales Tax
    Qst,
    /// Consumption Tax (Japan)
    ConsumptionTax,
    /// Custom/Other tax type
    Custom,
}

impl TaxType {
    /// Return the canonical string representation
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::SalesTax => "sales_tax",
            Self::Vat => "vat",
            Self::Gst => "gst",
            Self::Hst => "hst",
            Self::Pst => "pst",
            Self::Qst => "qst",
            Self::ConsumptionTax => "consumption_tax",
            Self::Custom => "custom",
        }
    }
}

/// Tax calculation method
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Display, EnumString, Serialize, Deserialize, Default,
)]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TaxCalculationMethod {
    /// Tax is calculated on top of the price (US style)
    #[default]
    Exclusive,
    /// Tax is included in the price (EU VAT style)
    Inclusive,
}

/// How to apply multiple tax rates
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TaxCompoundMethod {
    /// Add all taxes together, apply to subtotal
    #[default]
    Combined,
    /// Apply taxes sequentially (tax on tax)
    Compound,
    /// Apply taxes separately to subtotal
    Separate,
}

impl std::fmt::Display for TaxCompoundMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Combined => f.write_str("combined"),
            Self::Compound => f.write_str("compound"),
            Self::Separate => f.write_str("separate"),
        }
    }
}

impl std::str::FromStr for TaxCompoundMethod {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_ascii_lowercase().as_str() {
            "combined" => Ok(Self::Combined),
            "compound" => Ok(Self::Compound),
            "separate" => Ok(Self::Separate),
            _ => Err(format!("Unknown tax compound method: {}", s)),
        }
    }
}

/// Product tax category
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Display, EnumString, Serialize, Deserialize, Default,
)]
#[strum(serialize_all = "snake_case", ascii_case_insensitive)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ProductTaxCategory {
    /// Standard taxable goods
    #[default]
    Standard,
    /// Reduced rate (e.g., food, books in some jurisdictions)
    Reduced,
    /// Super-reduced rate (e.g., essential food)
    SuperReduced,
    /// Zero-rated (taxable at 0%, still reportable)
    ZeroRated,
    /// Exempt from tax entirely
    Exempt,
    /// Digital goods/services (special rules in many jurisdictions)
    Digital,
    /// Clothing (special rules in some US states)
    Clothing,
    /// Food for home consumption
    Food,
    /// Prepared food/restaurant
    PreparedFood,
    /// Medical/health items
    Medical,
    /// Educational materials
    Educational,
    /// Luxury goods (higher rate in some places)
    Luxury,
}

impl ProductTaxCategory {
    /// Return the canonical string representation
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Standard => "standard",
            Self::Reduced => "reduced",
            Self::SuperReduced => "super_reduced",
            Self::ZeroRated => "zero_rated",
            Self::Exempt => "exempt",
            Self::Digital => "digital",
            Self::Clothing => "clothing",
            Self::Food => "food",
            Self::PreparedFood => "prepared_food",
            Self::Medical => "medical",
            Self::Educational => "educational",
            Self::Luxury => "luxury",
        }
    }
}

/// Customer exemption type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ExemptionType {
    /// Wholesale/resale (has resale certificate)
    Resale,
    /// Non-profit organization
    NonProfit,
    /// Government entity
    Government,
    /// Educational institution
    Educational,
    /// Religious organization
    Religious,
    /// Medical/healthcare
    Medical,
    /// Manufacturing (raw materials)
    Manufacturing,
    /// Agricultural
    Agricultural,
    /// Export (zero-rated for export)
    Export,
    /// Diplomatic (embassy, consulate)
    Diplomatic,
    /// Other documented exemption
    Other,
}

impl std::fmt::Display for ExemptionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Resale => f.write_str("resale"),
            Self::NonProfit => f.write_str("non_profit"),
            Self::Government => f.write_str("government"),
            Self::Educational => f.write_str("educational"),
            Self::Religious => f.write_str("religious"),
            Self::Medical => f.write_str("medical"),
            Self::Manufacturing => f.write_str("manufacturing"),
            Self::Agricultural => f.write_str("agricultural"),
            Self::Export => f.write_str("export"),
            Self::Diplomatic => f.write_str("diplomatic"),
            Self::Other => f.write_str("other"),
        }
    }
}

impl std::str::FromStr for ExemptionType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_ascii_lowercase().as_str() {
            "resale" => Ok(Self::Resale),
            "non_profit" | "nonprofit" | "non-profit" => Ok(Self::NonProfit),
            "government" => Ok(Self::Government),
            "educational" => Ok(Self::Educational),
            "religious" => Ok(Self::Religious),
            "medical" => Ok(Self::Medical),
            "manufacturing" => Ok(Self::Manufacturing),
            "agricultural" => Ok(Self::Agricultural),
            "export" => Ok(Self::Export),
            "diplomatic" => Ok(Self::Diplomatic),
            "other" => Ok(Self::Other),
            _ => Err(format!("Unknown exemption type: {}", s)),
        }
    }
}

// ============================================================================
// Core Tax Entities
// ============================================================================

/// A tax jurisdiction (country, state, city, district)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxJurisdiction {
    pub id: Uuid,
    /// Parent jurisdiction (e.g., state is parent of city)
    pub parent_id: Option<Uuid>,
    /// Jurisdiction name
    pub name: String,
    /// Jurisdiction code (e.g., "US-CA", "US-CA-LA")
    pub code: String,
    /// Jurisdiction level
    pub level: JurisdictionLevel,
    /// Country code (ISO 3166-1 alpha-2)
    pub country_code: String,
    /// State/province code (ISO 3166-2)
    pub state_code: Option<String>,
    /// County/region name
    pub county: Option<String>,
    /// City name
    pub city: Option<String>,
    /// Postal codes covered (can be ranges or patterns)
    pub postal_codes: Vec<String>,
    /// Whether this jurisdiction is active
    pub active: bool,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// Level of tax jurisdiction
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum JurisdictionLevel {
    #[default]
    Country,
    State,
    County,
    City,
    District,
    Special,
}

impl std::fmt::Display for JurisdictionLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Country => f.write_str("country"),
            Self::State => f.write_str("state"),
            Self::County => f.write_str("county"),
            Self::City => f.write_str("city"),
            Self::District => f.write_str("district"),
            Self::Special => f.write_str("special"),
        }
    }
}

impl std::str::FromStr for JurisdictionLevel {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_ascii_lowercase().as_str() {
            "country" => Ok(Self::Country),
            "state" => Ok(Self::State),
            "county" => Ok(Self::County),
            "city" => Ok(Self::City),
            "district" => Ok(Self::District),
            "special" => Ok(Self::Special),
            _ => Err(format!("Unknown jurisdiction level: {}", s)),
        }
    }
}

/// A tax rate for a specific jurisdiction and category
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxRate {
    pub id: Uuid,
    /// Jurisdiction this rate applies to
    pub jurisdiction_id: Uuid,
    /// Type of tax
    pub tax_type: TaxType,
    /// Product category this rate applies to
    pub product_category: ProductTaxCategory,
    /// Tax rate as decimal (e.g., 0.0825 for 8.25%)
    pub rate: Decimal,
    /// Rate name for display (e.g., "California State Tax")
    pub name: String,
    /// Description of the tax
    pub description: Option<String>,
    /// Whether rate is compound (applied after other taxes)
    pub is_compound: bool,
    /// Priority for ordering (lower = applied first)
    pub priority: i32,
    /// Minimum amount for tax to apply
    pub threshold_min: Option<Decimal>,
    /// Maximum amount taxed (cap)
    pub threshold_max: Option<Decimal>,
    /// Fixed amount instead of percentage
    pub fixed_amount: Option<Decimal>,
    /// Effective date
    pub effective_from: NaiveDate,
    /// Expiration date
    pub effective_to: Option<NaiveDate>,
    /// Whether this rate is active
    pub active: bool,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// Customer tax exemption certificate
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxExemption {
    pub id: Uuid,
    /// Customer this exemption belongs to
    pub customer_id: Uuid,
    /// Type of exemption
    pub exemption_type: ExemptionType,
    /// Exemption certificate number
    pub certificate_number: Option<String>,
    /// Issuing authority/state
    pub issuing_authority: Option<String>,
    /// Jurisdictions where exemption applies (empty = all)
    pub jurisdiction_ids: Vec<Uuid>,
    /// Product categories exempt (empty = all)
    pub exempt_categories: Vec<ProductTaxCategory>,
    /// Effective date
    pub effective_from: NaiveDate,
    /// Expiration date
    pub expires_at: Option<NaiveDate>,
    /// Whether exemption has been verified
    pub verified: bool,
    /// Verification date
    pub verified_at: Option<DateTime<Utc>>,
    /// Notes about the exemption
    pub notes: Option<String>,
    /// Whether this exemption is active
    pub active: bool,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

// ============================================================================
// Tax Calculation Types
// ============================================================================

/// Input for tax calculation
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TaxCalculationRequest {
    /// Line items to calculate tax for
    pub line_items: Vec<TaxLineItem>,
    /// Shipping address (determines jurisdiction)
    pub shipping_address: TaxAddress,
    /// Optional billing address (for digital goods)
    pub billing_address: Option<TaxAddress>,
    /// Customer ID (for exemption lookup)
    pub customer_id: Option<Uuid>,
    /// Shipping amount (may be taxable)
    pub shipping_amount: Option<Decimal>,
    /// Currency code
    #[serde(default = "default_currency")]
    pub currency: CurrencyCode,
    /// Transaction date (for rate lookup)
    pub transaction_date: Option<NaiveDate>,
    /// Whether prices include tax
    pub prices_include_tax: bool,
}

const fn default_currency() -> CurrencyCode {
    CurrencyCode::USD
}

/// A line item for tax calculation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxLineItem {
    /// Line item identifier
    pub id: String,
    /// Product SKU
    pub sku: Option<String>,
    /// Product ID
    pub product_id: Option<ProductId>,
    /// Quantity
    pub quantity: Decimal,
    /// Unit price
    pub unit_price: Decimal,
    /// Total discount on this line
    pub discount_amount: Decimal,
    /// Product tax category
    pub tax_category: ProductTaxCategory,
    /// Override tax code (e.g., Avalara tax code)
    pub tax_code: Option<String>,
    /// Description for tax reporting
    pub description: Option<String>,
}

impl Default for TaxLineItem {
    fn default() -> Self {
        Self {
            id: String::new(),
            sku: None,
            product_id: None,
            quantity: Decimal::ONE,
            unit_price: Decimal::ZERO,
            discount_amount: Decimal::ZERO,
            tax_category: ProductTaxCategory::Standard,
            tax_code: None,
            description: None,
        }
    }
}

/// Address for tax jurisdiction determination
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TaxAddress {
    /// Street line 1
    pub line1: Option<String>,
    /// Street line 2
    pub line2: Option<String>,
    /// City
    pub city: Option<String>,
    /// State/Province/Region
    pub state: Option<String>,
    /// Postal/ZIP code
    pub postal_code: Option<String>,
    /// Country code (ISO 3166-1 alpha-2)
    pub country: String,
}

/// Result of tax calculation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxCalculationResult {
    /// Unique calculation ID
    pub id: Uuid,
    /// Total tax amount
    pub total_tax: Decimal,
    /// Subtotal before tax
    pub subtotal: Decimal,
    /// Total including tax
    pub total: Decimal,
    /// Tax on shipping
    pub shipping_tax: Decimal,
    /// Breakdown by jurisdiction
    pub tax_breakdown: Vec<TaxBreakdown>,
    /// Per-line-item tax details
    pub line_item_taxes: Vec<LineItemTax>,
    /// Whether any exemptions were applied
    pub exemptions_applied: bool,
    /// Exemption details if applied
    pub exemption_details: Option<ExemptionDetails>,
    /// Jurisdictions involved
    pub jurisdictions: Vec<JurisdictionSummary>,
    /// Calculation timestamp
    pub calculated_at: DateTime<Utc>,
    /// Whether this is an estimate or committed transaction
    pub is_estimate: bool,
}

/// Tax breakdown by jurisdiction
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxBreakdown {
    /// Jurisdiction ID
    pub jurisdiction_id: Uuid,
    /// Jurisdiction name
    pub jurisdiction_name: String,
    /// Tax type
    pub tax_type: TaxType,
    /// Rate name
    pub rate_name: String,
    /// Tax rate applied
    pub rate: Decimal,
    /// Taxable amount
    pub taxable_amount: Decimal,
    /// Tax amount
    pub tax_amount: Decimal,
    /// Whether this is a compound tax
    pub is_compound: bool,
}

/// Tax for a specific line item
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineItemTax {
    /// Line item ID
    pub line_item_id: String,
    /// Taxable amount for this item
    pub taxable_amount: Decimal,
    /// Total tax for this item
    pub tax_amount: Decimal,
    /// Effective tax rate
    pub effective_rate: Decimal,
    /// Whether item was exempt
    pub is_exempt: bool,
    /// Reason for exemption if exempt
    pub exemption_reason: Option<String>,
    /// Breakdown by tax type
    pub tax_details: Vec<TaxDetail>,
}

/// Detailed tax information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxDetail {
    pub tax_type: TaxType,
    pub jurisdiction_name: String,
    pub rate: Decimal,
    pub amount: Decimal,
}

/// Summary of exemptions applied
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExemptionDetails {
    pub exemption_id: Uuid,
    pub exemption_type: ExemptionType,
    pub certificate_number: Option<String>,
    pub amount_exempt: Decimal,
    pub tax_saved: Decimal,
}

/// Summary of a jurisdiction involved in calculation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JurisdictionSummary {
    pub id: Uuid,
    pub name: String,
    pub code: String,
    pub level: JurisdictionLevel,
    pub total_rate: Decimal,
    pub total_tax: Decimal,
}

// ============================================================================
// Tax Configuration
// ============================================================================

/// Store-level tax configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxSettings {
    pub id: Uuid,
    /// Whether tax calculation is enabled
    pub enabled: bool,
    /// Default calculation method
    pub calculation_method: TaxCalculationMethod,
    /// Default compound method
    pub compound_method: TaxCompoundMethod,
    /// Whether to tax shipping
    pub tax_shipping: bool,
    /// Whether to tax handling fees
    pub tax_handling: bool,
    /// Whether to tax gift wrapping
    pub tax_gift_wrap: bool,
    /// Origin address for origin-based tax states
    pub origin_address: Option<TaxAddress>,
    /// Default product tax category
    pub default_product_category: ProductTaxCategory,
    /// Rounding mode (up, down, `half_up`, `half_down`)
    pub rounding_mode: String,
    /// Decimal places for tax amounts
    pub decimal_places: i32,
    /// Whether to validate addresses
    pub validate_addresses: bool,
    /// External tax service provider (avalara, taxjar, vertex, none)
    pub tax_provider: Option<String>,
    /// Provider API credentials (encrypted)
    pub provider_credentials: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

impl Default for TaxSettings {
    fn default() -> Self {
        Self {
            id: Uuid::new_v4(),
            enabled: true,
            calculation_method: TaxCalculationMethod::Exclusive,
            compound_method: TaxCompoundMethod::Combined,
            tax_shipping: true,
            tax_handling: true,
            tax_gift_wrap: true,
            origin_address: None,
            default_product_category: ProductTaxCategory::Standard,
            rounding_mode: "half_up".to_string(),
            decimal_places: 2,
            validate_addresses: false,
            tax_provider: None,
            provider_credentials: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        }
    }
}

// ============================================================================
// Create/Update DTOs
// ============================================================================

/// Create a new tax jurisdiction
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CreateTaxJurisdiction {
    pub parent_id: Option<Uuid>,
    pub name: String,
    pub code: String,
    pub level: JurisdictionLevel,
    pub country_code: String,
    pub state_code: Option<String>,
    pub county: Option<String>,
    pub city: Option<String>,
    pub postal_codes: Vec<String>,
}

/// Create a new tax rate
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateTaxRate {
    pub jurisdiction_id: Uuid,
    pub tax_type: TaxType,
    pub product_category: ProductTaxCategory,
    pub rate: Decimal,
    pub name: String,
    pub description: Option<String>,
    pub is_compound: bool,
    pub priority: i32,
    pub threshold_min: Option<Decimal>,
    pub threshold_max: Option<Decimal>,
    pub fixed_amount: Option<Decimal>,
    pub effective_from: NaiveDate,
    pub effective_to: Option<NaiveDate>,
}

impl Default for CreateTaxRate {
    fn default() -> Self {
        Self {
            jurisdiction_id: Uuid::nil(),
            tax_type: TaxType::SalesTax,
            product_category: ProductTaxCategory::Standard,
            rate: Decimal::ZERO,
            name: String::new(),
            description: None,
            is_compound: false,
            priority: 0,
            threshold_min: None,
            threshold_max: None,
            fixed_amount: None,
            effective_from: Utc::now().date_naive(),
            effective_to: None,
        }
    }
}

/// Create a tax exemption for a customer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateTaxExemption {
    pub customer_id: Uuid,
    pub exemption_type: ExemptionType,
    pub certificate_number: Option<String>,
    pub issuing_authority: Option<String>,
    pub jurisdiction_ids: Vec<Uuid>,
    pub exempt_categories: Vec<ProductTaxCategory>,
    pub effective_from: NaiveDate,
    pub expires_at: Option<NaiveDate>,
    pub notes: Option<String>,
}

/// Filter for querying tax rates
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TaxRateFilter {
    pub jurisdiction_id: Option<Uuid>,
    pub tax_type: Option<TaxType>,
    pub product_category: Option<ProductTaxCategory>,
    pub active_only: bool,
    pub effective_date: Option<NaiveDate>,
}

/// Filter for querying jurisdictions
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TaxJurisdictionFilter {
    pub country_code: Option<String>,
    pub state_code: Option<String>,
    pub level: Option<JurisdictionLevel>,
    pub active_only: bool,
}

// ============================================================================
// US-Specific Tax Helpers
// ============================================================================

/// US State tax information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsStateTaxInfo {
    pub state_code: String,
    pub state_name: String,
    pub state_rate: Decimal,
    pub has_local_taxes: bool,
    pub origin_based: bool,
    pub tax_shipping: bool,
    pub tax_clothing: bool,
    pub tax_food: bool,
    pub tax_digital: bool,
}

/// Pre-configured US state tax data
pub fn get_us_state_tax_info(state_code: &str) -> Option<UsStateTaxInfo> {
    match state_code.to_uppercase().as_str() {
        "AL" => Some(UsStateTaxInfo {
            state_code: "AL".into(),
            state_name: "Alabama".into(),
            state_rate: Decimal::new(4, 2), // 4%
            has_local_taxes: true,
            origin_based: false,
            tax_shipping: true,
            tax_clothing: true,
            tax_food: true,
            tax_digital: true,
        }),
        "AK" => Some(UsStateTaxInfo {
            state_code: "AK".into(),
            state_name: "Alaska".into(),
            state_rate: Decimal::ZERO, // No state tax
            has_local_taxes: true,
            origin_based: false,
            tax_shipping: false,
            tax_clothing: false,
            tax_food: false,
            tax_digital: false,
        }),
        "AZ" => Some(UsStateTaxInfo {
            state_code: "AZ".into(),
            state_name: "Arizona".into(),
            state_rate: Decimal::new(56, 3), // 5.6%
            has_local_taxes: true,
            origin_based: true,
            tax_shipping: true,
            tax_clothing: true,
            tax_food: false,
            tax_digital: true,
        }),
        "CA" => Some(UsStateTaxInfo {
            state_code: "CA".into(),
            state_name: "California".into(),
            state_rate: Decimal::new(725, 4), // 7.25%
            has_local_taxes: true,
            origin_based: true,
            tax_shipping: false,
            tax_clothing: true,
            tax_food: false,
            tax_digital: false,
        }),
        "CO" => Some(UsStateTaxInfo {
            state_code: "CO".into(),
            state_name: "Colorado".into(),
            state_rate: Decimal::new(29, 3), // 2.9%
            has_local_taxes: true,
            origin_based: false,
            tax_shipping: true,
            tax_clothing: true,
            tax_food: false,
            tax_digital: true,
        }),
        "DE" => Some(UsStateTaxInfo {
            state_code: "DE".into(),
            state_name: "Delaware".into(),
            state_rate: Decimal::ZERO, // No sales tax
            has_local_taxes: false,
            origin_based: false,
            tax_shipping: false,
            tax_clothing: false,
            tax_food: false,
            tax_digital: false,
        }),
        "FL" => Some(UsStateTaxInfo {
            state_code: "FL".into(),
            state_name: "Florida".into(),
            state_rate: Decimal::new(6, 2), // 6%
            has_local_taxes: true,
            origin_based: false,
            tax_shipping: true,
            tax_clothing: true,
            tax_food: false,
            tax_digital: true,
        }),
        "MT" => Some(UsStateTaxInfo {
            state_code: "MT".into(),
            state_name: "Montana".into(),
            state_rate: Decimal::ZERO, // No sales tax
            has_local_taxes: false,
            origin_based: false,
            tax_shipping: false,
            tax_clothing: false,
            tax_food: false,
            tax_digital: false,
        }),
        "NH" => Some(UsStateTaxInfo {
            state_code: "NH".into(),
            state_name: "New Hampshire".into(),
            state_rate: Decimal::ZERO, // No sales tax
            has_local_taxes: false,
            origin_based: false,
            tax_shipping: false,
            tax_clothing: false,
            tax_food: false,
            tax_digital: false,
        }),
        "NY" => Some(UsStateTaxInfo {
            state_code: "NY".into(),
            state_name: "New York".into(),
            state_rate: Decimal::new(4, 2), // 4%
            has_local_taxes: true,
            origin_based: false,
            tax_shipping: true,
            tax_clothing: false, // Clothing under $110 exempt
            tax_food: false,
            tax_digital: true,
        }),
        "OR" => Some(UsStateTaxInfo {
            state_code: "OR".into(),
            state_name: "Oregon".into(),
            state_rate: Decimal::ZERO, // No sales tax
            has_local_taxes: false,
            origin_based: false,
            tax_shipping: false,
            tax_clothing: false,
            tax_food: false,
            tax_digital: false,
        }),
        "TX" => Some(UsStateTaxInfo {
            state_code: "TX".into(),
            state_name: "Texas".into(),
            state_rate: Decimal::new(625, 4), // 6.25%
            has_local_taxes: true,
            origin_based: true,
            tax_shipping: true,
            tax_clothing: true,
            tax_food: false,
            tax_digital: true,
        }),
        "WA" => Some(UsStateTaxInfo {
            state_code: "WA".into(),
            state_name: "Washington".into(),
            state_rate: Decimal::new(65, 3), // 6.5%
            has_local_taxes: true,
            origin_based: false,
            tax_shipping: true,
            tax_clothing: true,
            tax_food: false,
            tax_digital: true,
        }),
        _ => None,
    }
}

// ============================================================================
// EU VAT Helpers
// ============================================================================

/// EU VAT rates by country
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EuVatInfo {
    pub country_code: String,
    pub country_name: String,
    pub standard_rate: Decimal,
    pub reduced_rate: Option<Decimal>,
    pub super_reduced_rate: Option<Decimal>,
    pub parking_rate: Option<Decimal>,
}

/// Get EU VAT information for a country
pub fn get_eu_vat_info(country_code: &str) -> Option<EuVatInfo> {
    match country_code.to_uppercase().as_str() {
        "AT" => Some(EuVatInfo {
            country_code: "AT".into(),
            country_name: "Austria".into(),
            standard_rate: Decimal::new(20, 2),
            reduced_rate: Some(Decimal::new(10, 2)),
            super_reduced_rate: None,
            parking_rate: Some(Decimal::new(13, 2)),
        }),
        "BE" => Some(EuVatInfo {
            country_code: "BE".into(),
            country_name: "Belgium".into(),
            standard_rate: Decimal::new(21, 2),
            reduced_rate: Some(Decimal::new(12, 2)),
            super_reduced_rate: Some(Decimal::new(6, 2)),
            parking_rate: Some(Decimal::new(12, 2)),
        }),
        "DE" => Some(EuVatInfo {
            country_code: "DE".into(),
            country_name: "Germany".into(),
            standard_rate: Decimal::new(19, 2),
            reduced_rate: Some(Decimal::new(7, 2)),
            super_reduced_rate: None,
            parking_rate: None,
        }),
        "ES" => Some(EuVatInfo {
            country_code: "ES".into(),
            country_name: "Spain".into(),
            standard_rate: Decimal::new(21, 2),
            reduced_rate: Some(Decimal::new(10, 2)),
            super_reduced_rate: Some(Decimal::new(4, 2)),
            parking_rate: None,
        }),
        "FR" => Some(EuVatInfo {
            country_code: "FR".into(),
            country_name: "France".into(),
            standard_rate: Decimal::new(20, 2),
            reduced_rate: Some(Decimal::new(10, 2)),
            super_reduced_rate: Some(Decimal::new(55, 3)), // 5.5%
            parking_rate: None,
        }),
        "GB" => Some(EuVatInfo {
            country_code: "GB".into(),
            country_name: "United Kingdom".into(),
            standard_rate: Decimal::new(20, 2),
            reduced_rate: Some(Decimal::new(5, 2)),
            super_reduced_rate: None,
            parking_rate: None,
        }),
        "IE" => Some(EuVatInfo {
            country_code: "IE".into(),
            country_name: "Ireland".into(),
            standard_rate: Decimal::new(23, 2),
            reduced_rate: Some(Decimal::new(135, 3)), // 13.5%
            super_reduced_rate: Some(Decimal::new(48, 3)), // 4.8%
            parking_rate: Some(Decimal::new(135, 3)),
        }),
        "IT" => Some(EuVatInfo {
            country_code: "IT".into(),
            country_name: "Italy".into(),
            standard_rate: Decimal::new(22, 2),
            reduced_rate: Some(Decimal::new(10, 2)),
            super_reduced_rate: Some(Decimal::new(4, 2)),
            parking_rate: None,
        }),
        "NL" => Some(EuVatInfo {
            country_code: "NL".into(),
            country_name: "Netherlands".into(),
            standard_rate: Decimal::new(21, 2),
            reduced_rate: Some(Decimal::new(9, 2)),
            super_reduced_rate: None,
            parking_rate: None,
        }),
        "SE" => Some(EuVatInfo {
            country_code: "SE".into(),
            country_name: "Sweden".into(),
            standard_rate: Decimal::new(25, 2),
            reduced_rate: Some(Decimal::new(12, 2)),
            super_reduced_rate: Some(Decimal::new(6, 2)),
            parking_rate: None,
        }),
        _ => None,
    }
}

/// List of EU member state country codes
pub const EU_MEMBER_STATES: &[&str] = &[
    "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LV",
    "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE",
];

/// Check if a country is in the EU
pub fn is_eu_member(country_code: &str) -> bool {
    EU_MEMBER_STATES.contains(&country_code.to_uppercase().as_str())
}

// ============================================================================
// Canadian Tax Helpers
// ============================================================================

/// Canadian province/territory tax information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CanadianTaxInfo {
    pub province_code: String,
    pub province_name: String,
    pub gst_rate: Decimal,
    pub pst_rate: Option<Decimal>,
    pub hst_rate: Option<Decimal>,
    pub qst_rate: Option<Decimal>,
    pub total_rate: Decimal,
}

/// Get Canadian tax information for a province
pub fn get_canadian_tax_info(province_code: &str) -> Option<CanadianTaxInfo> {
    let gst = Decimal::new(5, 2); // Federal GST is 5%

    match province_code.to_uppercase().as_str() {
        "AB" => Some(CanadianTaxInfo {
            province_code: "AB".into(),
            province_name: "Alberta".into(),
            gst_rate: gst,
            pst_rate: None,
            hst_rate: None,
            qst_rate: None,
            total_rate: gst,
        }),
        "BC" => Some(CanadianTaxInfo {
            province_code: "BC".into(),
            province_name: "British Columbia".into(),
            gst_rate: gst,
            pst_rate: Some(Decimal::new(7, 2)),
            hst_rate: None,
            qst_rate: None,
            total_rate: Decimal::new(12, 2),
        }),
        "ON" => Some(CanadianTaxInfo {
            province_code: "ON".into(),
            province_name: "Ontario".into(),
            gst_rate: Decimal::ZERO, // Replaced by HST
            pst_rate: None,
            hst_rate: Some(Decimal::new(13, 2)),
            qst_rate: None,
            total_rate: Decimal::new(13, 2),
        }),
        "QC" => Some(CanadianTaxInfo {
            province_code: "QC".into(),
            province_name: "Quebec".into(),
            gst_rate: gst,
            pst_rate: None,
            hst_rate: None,
            qst_rate: Some(Decimal::new(9975, 4)), // 9.975%
            total_rate: Decimal::new(14975, 4),
        }),
        "SK" => Some(CanadianTaxInfo {
            province_code: "SK".into(),
            province_name: "Saskatchewan".into(),
            gst_rate: gst,
            pst_rate: Some(Decimal::new(6, 2)),
            hst_rate: None,
            qst_rate: None,
            total_rate: Decimal::new(11, 2),
        }),
        "MB" => Some(CanadianTaxInfo {
            province_code: "MB".into(),
            province_name: "Manitoba".into(),
            gst_rate: gst,
            pst_rate: Some(Decimal::new(7, 2)),
            hst_rate: None,
            qst_rate: None,
            total_rate: Decimal::new(12, 2),
        }),
        "NS" => Some(CanadianTaxInfo {
            province_code: "NS".into(),
            province_name: "Nova Scotia".into(),
            gst_rate: Decimal::ZERO,
            pst_rate: None,
            hst_rate: Some(Decimal::new(15, 2)),
            qst_rate: None,
            total_rate: Decimal::new(15, 2),
        }),
        "NB" => Some(CanadianTaxInfo {
            province_code: "NB".into(),
            province_name: "New Brunswick".into(),
            gst_rate: Decimal::ZERO,
            pst_rate: None,
            hst_rate: Some(Decimal::new(15, 2)),
            qst_rate: None,
            total_rate: Decimal::new(15, 2),
        }),
        _ => None,
    }
}

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

    #[test]
    fn tax_type_from_str() {
        assert_eq!(TaxType::from_str("sales_tax").unwrap(), TaxType::SalesTax);
        assert!(TaxType::from_str("unknown").is_err());
    }

    #[test]
    fn tax_calculation_method_from_str() {
        assert_eq!(
            TaxCalculationMethod::from_str("inclusive").unwrap(),
            TaxCalculationMethod::Inclusive
        );
        assert!(TaxCalculationMethod::from_str("other").is_err());
    }

    #[test]
    fn tax_compound_method_from_str() {
        assert_eq!(TaxCompoundMethod::from_str("combined").unwrap(), TaxCompoundMethod::Combined);
        assert!(TaxCompoundMethod::from_str("other").is_err());
    }

    #[test]
    fn product_tax_category_from_str() {
        assert_eq!(
            ProductTaxCategory::from_str("super_reduced").unwrap(),
            ProductTaxCategory::SuperReduced
        );
        assert!(ProductTaxCategory::from_str("other").is_err());
    }

    #[test]
    fn exemption_type_from_str() {
        assert_eq!(ExemptionType::from_str("non_profit").unwrap(), ExemptionType::NonProfit);
        assert!(ExemptionType::from_str("unknown").is_err());
    }

    #[test]
    fn jurisdiction_level_from_str() {
        assert_eq!(JurisdictionLevel::from_str("state").unwrap(), JurisdictionLevel::State);
        assert!(JurisdictionLevel::from_str("unknown").is_err());
    }
}