datasynth-generators 2.4.0

50+ data generators covering GL, P2P, O2C, S2C, HR, manufacturing, audit, tax, treasury, and ESG
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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
//! Enhanced customer generator with credit management and payment behavior.
//!
//! Also supports customer segmentation with:
//! - Value segments (Enterprise, Mid-Market, SMB, Consumer)
//! - Customer lifecycle stages
//! - Referral networks and corporate hierarchies
//! - Engagement metrics and churn analysis

use std::collections::HashSet;

use chrono::NaiveDate;
use datasynth_core::models::{
    ChurnReason, CreditRating, Customer, CustomerEngagement, CustomerLifecycleStage,
    CustomerPaymentBehavior, CustomerPool, CustomerValueSegment, PaymentTerms, RiskTrigger,
    SegmentedCustomer, SegmentedCustomerPool,
};
use datasynth_core::utils::seeded_rng;
use rand::prelude::*;
use rand_chacha::ChaCha8Rng;
use rust_decimal::Decimal;
use tracing::debug;

use crate::coa_generator::CoAFramework;

/// Configuration for customer generation.
#[derive(Debug, Clone)]
pub struct CustomerGeneratorConfig {
    /// Distribution of credit ratings (rating, probability)
    pub credit_rating_distribution: Vec<(CreditRating, f64)>,
    /// Distribution of payment behaviors (behavior, probability)
    pub payment_behavior_distribution: Vec<(CustomerPaymentBehavior, f64)>,
    /// Distribution of payment terms (terms, probability)
    pub payment_terms_distribution: Vec<(PaymentTerms, f64)>,
    /// Probability of customer being intercompany
    pub intercompany_rate: f64,
    /// Default country for customers
    pub default_country: String,
    /// Default currency
    pub default_currency: String,
    /// Credit limit ranges by rating (min, max)
    pub credit_limits: Vec<(CreditRating, Decimal, Decimal)>,
}

impl Default for CustomerGeneratorConfig {
    fn default() -> Self {
        Self {
            credit_rating_distribution: vec![
                (CreditRating::AAA, 0.05),
                (CreditRating::AA, 0.10),
                (CreditRating::A, 0.25),
                (CreditRating::BBB, 0.30),
                (CreditRating::BB, 0.15),
                (CreditRating::B, 0.10),
                (CreditRating::CCC, 0.04),
                (CreditRating::D, 0.01),
            ],
            payment_behavior_distribution: vec![
                (CustomerPaymentBehavior::EarlyPayer, 0.15),
                (CustomerPaymentBehavior::OnTime, 0.45),
                (CustomerPaymentBehavior::SlightlyLate, 0.25),
                (CustomerPaymentBehavior::OftenLate, 0.10),
                (CustomerPaymentBehavior::HighRisk, 0.05),
            ],
            payment_terms_distribution: vec![
                (PaymentTerms::Net30, 0.50),
                (PaymentTerms::Net60, 0.20),
                (PaymentTerms::TwoTenNet30, 0.20),
                (PaymentTerms::Net15, 0.05),
                (PaymentTerms::Immediate, 0.05),
            ],
            intercompany_rate: 0.05,
            default_country: "US".to_string(),
            default_currency: "USD".to_string(),
            credit_limits: vec![
                (
                    CreditRating::AAA,
                    Decimal::from(1_000_000),
                    Decimal::from(10_000_000),
                ),
                (
                    CreditRating::AA,
                    Decimal::from(500_000),
                    Decimal::from(2_000_000),
                ),
                (
                    CreditRating::A,
                    Decimal::from(250_000),
                    Decimal::from(1_000_000),
                ),
                (
                    CreditRating::BBB,
                    Decimal::from(100_000),
                    Decimal::from(500_000),
                ),
                (
                    CreditRating::BB,
                    Decimal::from(50_000),
                    Decimal::from(250_000),
                ),
                (
                    CreditRating::B,
                    Decimal::from(25_000),
                    Decimal::from(100_000),
                ),
                (
                    CreditRating::CCC,
                    Decimal::from(10_000),
                    Decimal::from(50_000),
                ),
                (CreditRating::D, Decimal::from(0), Decimal::from(10_000)),
            ],
        }
    }
}

/// Configuration for customer segmentation.
#[derive(Debug, Clone)]
pub struct CustomerSegmentationConfig {
    /// Enable customer segmentation
    pub enabled: bool,
    /// Value segment distribution
    pub segment_distribution: SegmentDistribution,
    /// Lifecycle stage distribution
    pub lifecycle_distribution: LifecycleDistribution,
    /// Referral network configuration
    pub referral_config: ReferralConfig,
    /// Corporate hierarchy configuration
    pub hierarchy_config: HierarchyConfig,
    /// Industry distribution
    pub industry_distribution: Vec<(String, f64)>,
}

impl Default for CustomerSegmentationConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            segment_distribution: SegmentDistribution::default(),
            lifecycle_distribution: LifecycleDistribution::default(),
            referral_config: ReferralConfig::default(),
            hierarchy_config: HierarchyConfig::default(),
            industry_distribution: vec![
                ("Technology".to_string(), 0.20),
                ("Manufacturing".to_string(), 0.15),
                ("Retail".to_string(), 0.15),
                ("Healthcare".to_string(), 0.12),
                ("Financial".to_string(), 0.12),
                ("Energy".to_string(), 0.08),
                ("Transportation".to_string(), 0.08),
                ("Construction".to_string(), 0.10),
            ],
        }
    }
}

/// Distribution of customer value segments.
#[derive(Debug, Clone)]
pub struct SegmentDistribution {
    /// Enterprise segment (customer share)
    pub enterprise: f64,
    /// Mid-market segment (customer share)
    pub mid_market: f64,
    /// SMB segment (customer share)
    pub smb: f64,
    /// Consumer segment (customer share)
    pub consumer: f64,
}

impl Default for SegmentDistribution {
    fn default() -> Self {
        Self {
            enterprise: 0.05,
            mid_market: 0.20,
            smb: 0.50,
            consumer: 0.25,
        }
    }
}

impl SegmentDistribution {
    /// Validate that distribution sums to 1.0.
    pub fn validate(&self) -> Result<(), String> {
        let sum = self.enterprise + self.mid_market + self.smb + self.consumer;
        if (sum - 1.0).abs() > 0.01 {
            Err(format!("Segment distribution must sum to 1.0, got {sum}"))
        } else {
            Ok(())
        }
    }

    /// Select a segment based on the distribution.
    pub fn select(&self, roll: f64) -> CustomerValueSegment {
        let mut cumulative = 0.0;

        cumulative += self.enterprise;
        if roll < cumulative {
            return CustomerValueSegment::Enterprise;
        }

        cumulative += self.mid_market;
        if roll < cumulative {
            return CustomerValueSegment::MidMarket;
        }

        cumulative += self.smb;
        if roll < cumulative {
            return CustomerValueSegment::Smb;
        }

        CustomerValueSegment::Consumer
    }
}

/// Distribution of lifecycle stages.
#[derive(Debug, Clone)]
pub struct LifecycleDistribution {
    /// Prospect rate
    pub prospect: f64,
    /// New customer rate
    pub new: f64,
    /// Growth stage rate
    pub growth: f64,
    /// Mature stage rate
    pub mature: f64,
    /// At-risk rate
    pub at_risk: f64,
    /// Churned rate
    pub churned: f64,
}

impl Default for LifecycleDistribution {
    fn default() -> Self {
        Self {
            prospect: 0.0, // Prospects not typically in active pool
            new: 0.10,
            growth: 0.15,
            mature: 0.60,
            at_risk: 0.10,
            churned: 0.05,
        }
    }
}

impl LifecycleDistribution {
    /// Validate that distribution sums to 1.0.
    pub fn validate(&self) -> Result<(), String> {
        let sum =
            self.prospect + self.new + self.growth + self.mature + self.at_risk + self.churned;
        if (sum - 1.0).abs() > 0.01 {
            Err(format!("Lifecycle distribution must sum to 1.0, got {sum}"))
        } else {
            Ok(())
        }
    }
}

/// Configuration for referral networks.
#[derive(Debug, Clone)]
pub struct ReferralConfig {
    /// Enable referral generation
    pub enabled: bool,
    /// Rate of customers acquired via referral
    pub referral_rate: f64,
    /// Maximum referrals per customer
    pub max_referrals_per_customer: usize,
}

impl Default for ReferralConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            referral_rate: 0.15,
            max_referrals_per_customer: 5,
        }
    }
}

/// Configuration for corporate hierarchies.
#[derive(Debug, Clone)]
pub struct HierarchyConfig {
    /// Enable corporate hierarchy generation
    pub enabled: bool,
    /// Rate of customers in hierarchies
    pub hierarchy_rate: f64,
    /// Maximum hierarchy depth
    pub max_depth: usize,
    /// Rate of billing consolidation
    pub billing_consolidation_rate: f64,
}

impl Default for HierarchyConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            hierarchy_rate: 0.30,
            max_depth: 3,
            billing_consolidation_rate: 0.50,
        }
    }
}

/// Customer name templates by industry.
const CUSTOMER_NAME_TEMPLATES: &[(&str, &[&str])] = &[
    (
        "Retail",
        &[
            "Consumer Goods Corp.",
            "Retail Solutions Inc.",
            "Shop Direct Ltd.",
            "Market Leaders LLC",
            "Consumer Brands Group",
            "Retail Partners Co.",
            "Shopping Networks Inc.",
            "Direct Sales Corp.",
        ],
    ),
    (
        "Manufacturing",
        &[
            "Industrial Manufacturing Inc.",
            "Production Systems Corp.",
            "Assembly Technologies LLC",
            "Manufacturing Partners Group",
            "Factory Solutions Ltd.",
            "Production Line Inc.",
            "Industrial Works Corp.",
            "Manufacturing Excellence Co.",
        ],
    ),
    (
        "Healthcare",
        &[
            "Healthcare Systems Inc.",
            "Medical Solutions Corp.",
            "Health Partners LLC",
            "Medical Equipment Group",
            "Healthcare Providers Ltd.",
            "Clinical Services Inc.",
            "Health Networks Corp.",
            "Medical Supplies Co.",
        ],
    ),
    (
        "Technology",
        &[
            "Tech Innovations Inc.",
            "Digital Solutions Corp.",
            "Software Systems LLC",
            "Technology Partners Group",
            "IT Solutions Ltd.",
            "Tech Enterprises Inc.",
            "Digital Networks Corp.",
            "Innovation Labs Co.",
        ],
    ),
    (
        "Financial",
        &[
            "Financial Services Inc.",
            "Banking Solutions Corp.",
            "Investment Partners LLC",
            "Financial Networks Group",
            "Capital Services Ltd.",
            "Banking Partners Inc.",
            "Finance Solutions Corp.",
            "Investment Group Co.",
        ],
    ),
    (
        "Energy",
        &[
            "Energy Solutions Inc.",
            "Power Systems Corp.",
            "Renewable Partners LLC",
            "Energy Networks Group",
            "Utility Services Ltd.",
            "Power Generation Inc.",
            "Energy Partners Corp.",
            "Sustainable Energy Co.",
        ],
    ),
    (
        "Transportation",
        &[
            "Transport Solutions Inc.",
            "Logistics Systems Corp.",
            "Freight Partners LLC",
            "Transportation Networks Group",
            "Shipping Services Ltd.",
            "Fleet Management Inc.",
            "Logistics Partners Corp.",
            "Transport Dynamics Co.",
        ],
    ),
    (
        "Construction",
        &[
            "Construction Solutions Inc.",
            "Building Systems Corp.",
            "Development Partners LLC",
            "Construction Group Ltd.",
            "Building Services Inc.",
            "Property Development Corp.",
            "Construction Partners Co.",
            "Infrastructure Systems LLC",
        ],
    ),
];

/// Generator for customer master data.
pub struct CustomerGenerator {
    rng: ChaCha8Rng,
    seed: u64,
    config: CustomerGeneratorConfig,
    customer_counter: usize,
    /// Segmentation configuration
    segmentation_config: CustomerSegmentationConfig,
    /// Optional country pack for locale-aware generation
    country_pack: Option<datasynth_core::CountryPack>,
    /// Accounting framework for auxiliary GL account generation
    coa_framework: CoAFramework,
    /// Tracks used customer names for deduplication
    used_names: HashSet<String>,
}

impl CustomerGenerator {
    /// Create a new customer generator.
    pub fn new(seed: u64) -> Self {
        Self::with_config(seed, CustomerGeneratorConfig::default())
    }

    /// Create a new customer generator with custom configuration.
    pub fn with_config(seed: u64, config: CustomerGeneratorConfig) -> Self {
        Self {
            rng: seeded_rng(seed, 0),
            seed,
            config,
            customer_counter: 0,
            segmentation_config: CustomerSegmentationConfig::default(),
            country_pack: None,
            coa_framework: CoAFramework::UsGaap,
            used_names: HashSet::new(),
        }
    }

    /// Create a new customer generator with segmentation configuration.
    pub fn with_segmentation_config(
        seed: u64,
        config: CustomerGeneratorConfig,
        segmentation_config: CustomerSegmentationConfig,
    ) -> Self {
        Self {
            rng: seeded_rng(seed, 0),
            seed,
            config,
            customer_counter: 0,
            segmentation_config,
            country_pack: None,
            coa_framework: CoAFramework::UsGaap,
            used_names: HashSet::new(),
        }
    }

    /// Set the accounting framework for auxiliary GL account generation.
    pub fn set_coa_framework(&mut self, framework: CoAFramework) {
        self.coa_framework = framework;
    }

    /// Set segmentation configuration.
    pub fn set_segmentation_config(&mut self, segmentation_config: CustomerSegmentationConfig) {
        self.segmentation_config = segmentation_config;
    }

    /// Set the country pack for locale-aware generation.
    pub fn set_country_pack(&mut self, pack: datasynth_core::CountryPack) {
        self.country_pack = Some(pack);
    }

    /// Set a counter offset so that generated IDs start after a given value.
    ///
    /// This is used when generating customers for multiple companies in parallel
    /// to ensure globally unique IDs. For example, if company 0 generates 100
    /// customers (C-000001..C-000100), company 1 should set offset=100 so its
    /// customers start at C-000101.
    pub fn set_counter_offset(&mut self, offset: usize) {
        self.customer_counter = offset;
    }

    /// Generate a single customer.
    pub fn generate_customer(
        &mut self,
        company_code: &str,
        _effective_date: NaiveDate,
    ) -> Customer {
        self.customer_counter += 1;

        let customer_id = format!("C-{:06}", self.customer_counter);
        let (_industry, name) = self.select_customer_name_unique();

        let mut customer = Customer::new(
            &customer_id,
            &name,
            datasynth_core::models::CustomerType::Corporate,
        );

        customer.country = self.config.default_country.clone();
        customer.currency = self.config.default_currency.clone();
        // Note: industry and effective_date are not fields on Customer

        // Set credit rating and limit
        customer.credit_rating = self.select_credit_rating();
        customer.credit_limit = self.generate_credit_limit(&customer.credit_rating);

        // Set payment behavior
        customer.payment_behavior = self.select_payment_behavior();

        // Set payment terms
        customer.payment_terms = self.select_payment_terms();

        // Set auxiliary GL account based on accounting framework
        customer.auxiliary_gl_account = self.generate_auxiliary_gl_account();

        // Check if intercompany
        if self.rng.random::<f64>() < self.config.intercompany_rate {
            customer.is_intercompany = true;
            customer.intercompany_code = Some(format!("IC-{company_code}"));
        }

        // Note: address, contact_name, contact_email are not fields on Customer

        customer
    }

    /// Generate an intercompany customer (always intercompany).
    pub fn generate_intercompany_customer(
        &mut self,
        company_code: &str,
        partner_company_code: &str,
        effective_date: NaiveDate,
    ) -> Customer {
        let mut customer = self.generate_customer(company_code, effective_date);
        customer.is_intercompany = true;
        customer.intercompany_code = Some(partner_company_code.to_string());
        customer.name = format!("{partner_company_code} - IC");
        customer.credit_rating = CreditRating::AAA; // IC always highest rating
        customer.credit_limit = Decimal::from(100_000_000); // High limit for IC
        customer.payment_behavior = CustomerPaymentBehavior::OnTime;
        customer
    }

    /// Generate a customer with specific credit profile.
    pub fn generate_customer_with_credit(
        &mut self,
        company_code: &str,
        credit_rating: CreditRating,
        credit_limit: Decimal,
        effective_date: NaiveDate,
    ) -> Customer {
        let mut customer = self.generate_customer(company_code, effective_date);
        customer.credit_rating = credit_rating;
        customer.credit_limit = credit_limit;

        // Adjust payment behavior based on credit rating
        customer.payment_behavior = match credit_rating {
            CreditRating::AAA | CreditRating::AA => {
                if self.rng.random::<f64>() < 0.7 {
                    CustomerPaymentBehavior::EarlyPayer
                } else {
                    CustomerPaymentBehavior::OnTime
                }
            }
            CreditRating::A | CreditRating::BBB => CustomerPaymentBehavior::OnTime,
            CreditRating::BB | CreditRating::B => CustomerPaymentBehavior::SlightlyLate,
            CreditRating::CCC | CreditRating::CC => CustomerPaymentBehavior::OftenLate,
            CreditRating::C | CreditRating::D => CustomerPaymentBehavior::HighRisk,
        };

        customer
    }

    /// Generate a customer pool with specified count.
    pub fn generate_customer_pool(
        &mut self,
        count: usize,
        company_code: &str,
        effective_date: NaiveDate,
    ) -> CustomerPool {
        debug!(count, company_code, %effective_date, "Generating customer pool");
        let mut pool = CustomerPool::new();

        for _ in 0..count {
            let customer = self.generate_customer(company_code, effective_date);
            pool.add_customer(customer);
        }

        pool
    }

    /// Generate a customer pool with intercompany customers.
    pub fn generate_customer_pool_with_ic(
        &mut self,
        count: usize,
        company_code: &str,
        partner_company_codes: &[String],
        effective_date: NaiveDate,
    ) -> CustomerPool {
        let mut pool = CustomerPool::new();

        // Generate regular customers
        let regular_count = count.saturating_sub(partner_company_codes.len());
        for _ in 0..regular_count {
            let customer = self.generate_customer(company_code, effective_date);
            pool.add_customer(customer);
        }

        // Generate IC customers for each partner
        for partner in partner_company_codes {
            let customer =
                self.generate_intercompany_customer(company_code, partner, effective_date);
            pool.add_customer(customer);
        }

        pool
    }

    /// Generate a diverse customer pool with various credit profiles.
    pub fn generate_diverse_pool(
        &mut self,
        count: usize,
        company_code: &str,
        effective_date: NaiveDate,
    ) -> CustomerPool {
        let mut pool = CustomerPool::new();

        // Generate customers with varied credit ratings ensuring coverage
        let rating_counts = [
            (CreditRating::AAA, (count as f64 * 0.05) as usize),
            (CreditRating::AA, (count as f64 * 0.10) as usize),
            (CreditRating::A, (count as f64 * 0.20) as usize),
            (CreditRating::BBB, (count as f64 * 0.30) as usize),
            (CreditRating::BB, (count as f64 * 0.15) as usize),
            (CreditRating::B, (count as f64 * 0.10) as usize),
            (CreditRating::CCC, (count as f64 * 0.07) as usize),
            (CreditRating::D, (count as f64 * 0.03) as usize),
        ];

        for (rating, rating_count) in rating_counts {
            for _ in 0..rating_count {
                let credit_limit = self.generate_credit_limit(&rating);
                let customer = self.generate_customer_with_credit(
                    company_code,
                    rating,
                    credit_limit,
                    effective_date,
                );
                pool.add_customer(customer);
            }
        }

        // Fill any remaining slots
        while pool.customers.len() < count {
            let customer = self.generate_customer(company_code, effective_date);
            pool.add_customer(customer);
        }

        pool
    }

    /// Select a customer name from templates.
    fn select_customer_name(&mut self) -> (&'static str, &'static str) {
        let industry_idx = self.rng.random_range(0..CUSTOMER_NAME_TEMPLATES.len());
        let (industry, names) = CUSTOMER_NAME_TEMPLATES[industry_idx];
        let name_idx = self.rng.random_range(0..names.len());
        (industry, names[name_idx])
    }

    /// Select a unique customer name, appending a suffix if collision detected.
    fn select_customer_name_unique(&mut self) -> (&'static str, String) {
        let (industry, name) = self.select_customer_name();
        let mut name = name.to_string();

        if self.used_names.contains(&name) {
            let suffixes = [
                " II",
                " III",
                " & Partners",
                " Group",
                " Holdings",
                " International",
            ];
            let mut found_unique = false;
            for suffix in &suffixes {
                let candidate = format!("{name}{suffix}");
                if !self.used_names.contains(&candidate) {
                    name = candidate;
                    found_unique = true;
                    break;
                }
            }
            if !found_unique {
                name = format!("{} #{}", name, self.customer_counter);
            }
        }

        self.used_names.insert(name.clone());
        (industry, name)
    }

    /// Generate auxiliary GL account based on accounting framework.
    fn generate_auxiliary_gl_account(&self) -> Option<String> {
        match self.coa_framework {
            CoAFramework::FrenchPcg => {
                // French PCG: 411XXXX sub-accounts under clients
                Some(format!("411{:04}", self.customer_counter))
            }
            CoAFramework::GermanSkr04 => {
                // German SKR04: AR control (1200) + sequential number
                Some(format!(
                    "{}{:04}",
                    datasynth_core::skr::control_accounts::AR_CONTROL,
                    self.customer_counter
                ))
            }
            CoAFramework::UsGaap => None,
        }
    }

    /// Select credit rating based on distribution.
    fn select_credit_rating(&mut self) -> CreditRating {
        let roll: f64 = self.rng.random();
        let mut cumulative = 0.0;

        for (rating, prob) in &self.config.credit_rating_distribution {
            cumulative += prob;
            if roll < cumulative {
                return *rating;
            }
        }

        CreditRating::BBB
    }

    /// Generate credit limit for rating.
    fn generate_credit_limit(&mut self, rating: &CreditRating) -> Decimal {
        for (r, min, max) in &self.config.credit_limits {
            if r == rating {
                let range = (*max - *min).to_string().parse::<f64>().unwrap_or(0.0);
                let offset = Decimal::from_f64_retain(self.rng.random::<f64>() * range)
                    .unwrap_or(Decimal::ZERO);
                return *min + offset;
            }
        }

        Decimal::from(100_000)
    }

    /// Select payment behavior based on distribution.
    fn select_payment_behavior(&mut self) -> CustomerPaymentBehavior {
        let roll: f64 = self.rng.random();
        let mut cumulative = 0.0;

        for (behavior, prob) in &self.config.payment_behavior_distribution {
            cumulative += prob;
            if roll < cumulative {
                return *behavior;
            }
        }

        CustomerPaymentBehavior::OnTime
    }

    /// Select payment terms based on distribution.
    fn select_payment_terms(&mut self) -> PaymentTerms {
        let roll: f64 = self.rng.random();
        let mut cumulative = 0.0;

        for (terms, prob) in &self.config.payment_terms_distribution {
            cumulative += prob;
            if roll < cumulative {
                return *terms;
            }
        }

        PaymentTerms::Net30
    }

    /// Reset the generator.
    pub fn reset(&mut self) {
        self.rng = seeded_rng(self.seed, 0);
        self.customer_counter = 0;
        self.used_names.clear();
    }

    // ===== Customer Segmentation Generation =====

    /// Generate a segmented customer pool with value segments, lifecycle stages, and networks.
    pub fn generate_segmented_pool(
        &mut self,
        count: usize,
        company_code: &str,
        effective_date: NaiveDate,
        total_annual_revenue: Decimal,
    ) -> SegmentedCustomerPool {
        let mut pool = SegmentedCustomerPool::new();

        if !self.segmentation_config.enabled {
            return pool;
        }

        // Calculate counts by segment
        let segment_counts = self.calculate_segment_counts(count);

        // Generate customers by segment
        let mut all_customer_ids: Vec<String> = Vec::new();
        let mut parent_candidates: Vec<String> = Vec::new();

        for (segment, segment_count) in segment_counts {
            for _ in 0..segment_count {
                let customer = self.generate_customer(company_code, effective_date);
                let customer_id = customer.customer_id.clone();

                let mut segmented =
                    self.create_segmented_customer(&customer, segment, effective_date);

                // Assign industry
                segmented.industry = Some(self.select_industry());

                // Assign annual contract value based on segment
                segmented.annual_contract_value =
                    self.generate_acv(segment, total_annual_revenue, count);

                // Enterprise customers are candidates for parent relationships
                if segment == CustomerValueSegment::Enterprise {
                    parent_candidates.push(customer_id.clone());
                }

                all_customer_ids.push(customer_id);
                pool.add_customer(segmented);
            }
        }

        // Build referral networks
        if self.segmentation_config.referral_config.enabled {
            self.build_referral_networks(&mut pool, &all_customer_ids);
        }

        // Build corporate hierarchies
        if self.segmentation_config.hierarchy_config.enabled {
            self.build_corporate_hierarchies(&mut pool, &all_customer_ids, &parent_candidates);
        }

        // Calculate engagement metrics and churn risk
        self.populate_engagement_metrics(&mut pool, effective_date);

        // Calculate statistics
        pool.calculate_statistics();

        pool
    }

    /// Calculate customer counts by segment.
    fn calculate_segment_counts(
        &mut self,
        total_count: usize,
    ) -> Vec<(CustomerValueSegment, usize)> {
        let dist = &self.segmentation_config.segment_distribution;
        vec![
            (
                CustomerValueSegment::Enterprise,
                (total_count as f64 * dist.enterprise) as usize,
            ),
            (
                CustomerValueSegment::MidMarket,
                (total_count as f64 * dist.mid_market) as usize,
            ),
            (
                CustomerValueSegment::Smb,
                (total_count as f64 * dist.smb) as usize,
            ),
            (
                CustomerValueSegment::Consumer,
                (total_count as f64 * dist.consumer) as usize,
            ),
        ]
    }

    /// Create a segmented customer from a base customer.
    fn create_segmented_customer(
        &mut self,
        customer: &Customer,
        segment: CustomerValueSegment,
        effective_date: NaiveDate,
    ) -> SegmentedCustomer {
        let lifecycle_stage = self.generate_lifecycle_stage(effective_date);

        SegmentedCustomer::new(
            &customer.customer_id,
            &customer.name,
            segment,
            effective_date,
        )
        .with_lifecycle_stage(lifecycle_stage)
    }

    /// Generate lifecycle stage based on distribution.
    fn generate_lifecycle_stage(&mut self, effective_date: NaiveDate) -> CustomerLifecycleStage {
        let dist = &self.segmentation_config.lifecycle_distribution;
        let roll: f64 = self.rng.random();
        let mut cumulative = 0.0;

        cumulative += dist.prospect;
        if roll < cumulative {
            return CustomerLifecycleStage::Prospect {
                conversion_probability: self.rng.random_range(0.1..0.4),
                source: Some("Marketing".to_string()),
                first_contact_date: effective_date
                    - chrono::Duration::days(self.rng.random_range(1..90)),
            };
        }

        cumulative += dist.new;
        if roll < cumulative {
            return CustomerLifecycleStage::New {
                first_order_date: effective_date
                    - chrono::Duration::days(self.rng.random_range(1..90)),
                onboarding_complete: self.rng.random::<f64>() > 0.3,
            };
        }

        cumulative += dist.growth;
        if roll < cumulative {
            return CustomerLifecycleStage::Growth {
                since: effective_date - chrono::Duration::days(self.rng.random_range(90..365)),
                growth_rate: self.rng.random_range(0.10..0.50),
            };
        }

        cumulative += dist.mature;
        if roll < cumulative {
            return CustomerLifecycleStage::Mature {
                stable_since: effective_date
                    - chrono::Duration::days(self.rng.random_range(365..1825)),
                avg_annual_spend: Decimal::from(self.rng.random_range(10000..500000)),
            };
        }

        cumulative += dist.at_risk;
        if roll < cumulative {
            let triggers = self.generate_risk_triggers();
            return CustomerLifecycleStage::AtRisk {
                triggers,
                flagged_date: effective_date - chrono::Duration::days(self.rng.random_range(7..60)),
                churn_probability: self.rng.random_range(0.3..0.8),
            };
        }

        // Churned
        CustomerLifecycleStage::Churned {
            last_activity: effective_date - chrono::Duration::days(self.rng.random_range(90..365)),
            win_back_probability: self.rng.random_range(0.05..0.25),
            reason: Some(self.generate_churn_reason()),
        }
    }

    /// Generate risk triggers for at-risk customers.
    fn generate_risk_triggers(&mut self) -> Vec<RiskTrigger> {
        let all_triggers = [
            RiskTrigger::DecliningOrderFrequency,
            RiskTrigger::DecliningOrderValue,
            RiskTrigger::PaymentIssues,
            RiskTrigger::Complaints,
            RiskTrigger::ReducedEngagement,
            RiskTrigger::ContractExpiring,
        ];

        let count = self.rng.random_range(1..=3);
        let mut triggers = Vec::new();

        for _ in 0..count {
            let idx = self.rng.random_range(0..all_triggers.len());
            triggers.push(all_triggers[idx].clone());
        }

        triggers
    }

    /// Generate churn reason.
    fn generate_churn_reason(&mut self) -> ChurnReason {
        let roll: f64 = self.rng.random();
        if roll < 0.30 {
            ChurnReason::Competitor
        } else if roll < 0.50 {
            ChurnReason::Price
        } else if roll < 0.65 {
            ChurnReason::ServiceQuality
        } else if roll < 0.75 {
            ChurnReason::BudgetConstraints
        } else if roll < 0.85 {
            ChurnReason::ProductFit
        } else if roll < 0.92 {
            ChurnReason::Consolidation
        } else {
            ChurnReason::Unknown
        }
    }

    /// Select an industry based on distribution.
    fn select_industry(&mut self) -> String {
        let roll: f64 = self.rng.random();
        let mut cumulative = 0.0;

        for (industry, prob) in &self.segmentation_config.industry_distribution {
            cumulative += prob;
            if roll < cumulative {
                return industry.clone();
            }
        }

        "Other".to_string()
    }

    /// Generate annual contract value based on segment.
    fn generate_acv(
        &mut self,
        segment: CustomerValueSegment,
        total_revenue: Decimal,
        total_customers: usize,
    ) -> Decimal {
        // Calculate expected revenue per customer in this segment
        let segment_revenue_share = segment.revenue_share();
        let segment_customer_share = segment.customer_share();
        let expected_customers_in_segment =
            (total_customers as f64 * segment_customer_share) as usize;
        let segment_total_revenue = total_revenue
            * Decimal::from_f64_retain(segment_revenue_share).unwrap_or(Decimal::ZERO);

        let avg_acv = if expected_customers_in_segment > 0 {
            segment_total_revenue / Decimal::from(expected_customers_in_segment)
        } else {
            Decimal::from(10000)
        };

        // Add variance (±50%)
        let variance = self.rng.random_range(0.5..1.5);
        avg_acv * Decimal::from_f64_retain(variance).unwrap_or(Decimal::ONE)
    }

    /// Build referral networks among customers.
    fn build_referral_networks(
        &mut self,
        pool: &mut SegmentedCustomerPool,
        customer_ids: &[String],
    ) {
        let referral_rate = self.segmentation_config.referral_config.referral_rate;
        let max_referrals = self
            .segmentation_config
            .referral_config
            .max_referrals_per_customer;

        // Track referral counts per customer
        let mut referral_counts: std::collections::HashMap<String, usize> =
            std::collections::HashMap::new();

        // Create customer ID to index mapping
        let id_to_idx: std::collections::HashMap<String, usize> = customer_ids
            .iter()
            .enumerate()
            .map(|(idx, id)| (id.clone(), idx))
            .collect();

        for i in 0..pool.customers.len() {
            if self.rng.random::<f64>() < referral_rate {
                // This customer was referred - find a referrer
                let potential_referrers: Vec<usize> = customer_ids
                    .iter()
                    .enumerate()
                    .filter(|(j, id)| {
                        *j != i && referral_counts.get(*id).copied().unwrap_or(0) < max_referrals
                    })
                    .map(|(j, _)| j)
                    .collect();

                if !potential_referrers.is_empty() {
                    let referrer_idx =
                        potential_referrers[self.rng.random_range(0..potential_referrers.len())];
                    let referrer_id = customer_ids[referrer_idx].clone();
                    let customer_id = pool.customers[i].customer_id.clone();

                    // Update the referred customer
                    pool.customers[i].network_position.referred_by = Some(referrer_id.clone());

                    // Update the referrer's referral list
                    if let Some(&ref_idx) = id_to_idx.get(&referrer_id) {
                        pool.customers[ref_idx]
                            .network_position
                            .referrals_made
                            .push(customer_id.clone());
                    }

                    *referral_counts.entry(referrer_id).or_insert(0) += 1;
                }
            }
        }
    }

    /// Build corporate hierarchies among customers.
    fn build_corporate_hierarchies(
        &mut self,
        pool: &mut SegmentedCustomerPool,
        customer_ids: &[String],
        parent_candidates: &[String],
    ) {
        let hierarchy_rate = self.segmentation_config.hierarchy_config.hierarchy_rate;
        let billing_consolidation_rate = self
            .segmentation_config
            .hierarchy_config
            .billing_consolidation_rate;

        // Create customer ID to index mapping
        let id_to_idx: std::collections::HashMap<String, usize> = customer_ids
            .iter()
            .enumerate()
            .map(|(idx, id)| (id.clone(), idx))
            .collect();

        for i in 0..pool.customers.len() {
            // Skip enterprise customers (they are parents) and already-hierarchied customers
            if pool.customers[i].segment == CustomerValueSegment::Enterprise
                || pool.customers[i].network_position.parent_customer.is_some()
            {
                continue;
            }

            if self.rng.random::<f64>() < hierarchy_rate && !parent_candidates.is_empty() {
                // Assign a parent
                let parent_idx = self.rng.random_range(0..parent_candidates.len());
                let parent_id = parent_candidates[parent_idx].clone();
                let customer_id = pool.customers[i].customer_id.clone();

                // Update the child
                pool.customers[i].network_position.parent_customer = Some(parent_id.clone());
                pool.customers[i].network_position.billing_consolidation =
                    self.rng.random::<f64>() < billing_consolidation_rate;

                // Update the parent's child list
                if let Some(&parent_idx) = id_to_idx.get(&parent_id) {
                    pool.customers[parent_idx]
                        .network_position
                        .child_customers
                        .push(customer_id);
                }
            }
        }
    }

    /// Populate engagement metrics for customers.
    fn populate_engagement_metrics(
        &mut self,
        pool: &mut SegmentedCustomerPool,
        effective_date: NaiveDate,
    ) {
        for customer in &mut pool.customers {
            // Generate engagement based on lifecycle stage and segment
            let (base_orders, base_revenue) = match customer.lifecycle_stage {
                CustomerLifecycleStage::Mature {
                    avg_annual_spend, ..
                } => {
                    let orders = self.rng.random_range(12..48);
                    (orders, avg_annual_spend)
                }
                CustomerLifecycleStage::Growth { growth_rate, .. } => {
                    let orders = self.rng.random_range(6..24);
                    let rev = Decimal::from(orders * self.rng.random_range(5000..20000));
                    (
                        orders,
                        rev * Decimal::from_f64_retain(1.0 + growth_rate).unwrap_or(Decimal::ONE),
                    )
                }
                CustomerLifecycleStage::New { .. } => {
                    let orders = self.rng.random_range(1..6);
                    (
                        orders,
                        Decimal::from(orders * self.rng.random_range(2000..10000)),
                    )
                }
                CustomerLifecycleStage::AtRisk { .. } => {
                    let orders = self.rng.random_range(2..12);
                    (
                        orders,
                        Decimal::from(orders * self.rng.random_range(3000..15000)),
                    )
                }
                CustomerLifecycleStage::Churned { .. } => (0, Decimal::ZERO),
                _ => (0, Decimal::ZERO),
            };

            customer.engagement = CustomerEngagement {
                total_orders: base_orders as u32,
                orders_last_12_months: (base_orders as f64 * 0.5) as u32,
                lifetime_revenue: base_revenue,
                revenue_last_12_months: base_revenue
                    * Decimal::from_f64_retain(0.5).unwrap_or(Decimal::ZERO),
                average_order_value: if base_orders > 0 {
                    base_revenue / Decimal::from(base_orders)
                } else {
                    Decimal::ZERO
                },
                days_since_last_order: match &customer.lifecycle_stage {
                    CustomerLifecycleStage::Churned { last_activity, .. } => {
                        (effective_date - *last_activity).num_days().max(0) as u32
                    }
                    CustomerLifecycleStage::AtRisk { .. } => self.rng.random_range(30..120),
                    _ => self.rng.random_range(1..30),
                },
                last_order_date: Some(
                    effective_date - chrono::Duration::days(self.rng.random_range(1..90)),
                ),
                first_order_date: Some(
                    effective_date - chrono::Duration::days(self.rng.random_range(180..1825)),
                ),
                products_purchased: base_orders as u32 * self.rng.random_range(1..5),
                support_tickets: self.rng.random_range(0..10),
                nps_score: Some(self.rng.random_range(-20..80) as i8),
            };

            // Calculate churn risk
            customer.calculate_churn_risk();

            // Calculate upsell potential based on segment and engagement
            customer.upsell_potential = match customer.segment {
                CustomerValueSegment::Enterprise => 0.3 + self.rng.random_range(0.0..0.2),
                CustomerValueSegment::MidMarket => 0.4 + self.rng.random_range(0.0..0.3),
                CustomerValueSegment::Smb => 0.5 + self.rng.random_range(0.0..0.3),
                CustomerValueSegment::Consumer => 0.2 + self.rng.random_range(0.0..0.3),
            };
        }
    }

    /// Generate a combined output of CustomerPool and SegmentedCustomerPool.
    pub fn generate_pool_with_segmentation(
        &mut self,
        count: usize,
        company_code: &str,
        effective_date: NaiveDate,
        total_annual_revenue: Decimal,
    ) -> (CustomerPool, SegmentedCustomerPool) {
        let segmented_pool =
            self.generate_segmented_pool(count, company_code, effective_date, total_annual_revenue);

        // Create a regular CustomerPool from the segmented customers
        let mut pool = CustomerPool::new();
        for _segmented in &segmented_pool.customers {
            let customer = self.generate_customer(company_code, effective_date);
            pool.add_customer(customer);
        }

        (pool, segmented_pool)
    }
}

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

    #[test]
    fn test_customer_generation() {
        let mut gen = CustomerGenerator::new(42);
        let customer = gen.generate_customer("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());

        assert!(!customer.customer_id.is_empty());
        assert!(!customer.name.is_empty());
        assert!(customer.credit_limit > Decimal::ZERO);
    }

    #[test]
    fn test_customer_pool_generation() {
        let mut gen = CustomerGenerator::new(42);
        let pool =
            gen.generate_customer_pool(20, "1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());

        assert_eq!(pool.customers.len(), 20);
    }

    #[test]
    fn test_intercompany_customer() {
        let mut gen = CustomerGenerator::new(42);
        let customer = gen.generate_intercompany_customer(
            "1000",
            "2000",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
        );

        assert!(customer.is_intercompany);
        assert_eq!(customer.intercompany_code, Some("2000".to_string()));
        assert_eq!(customer.credit_rating, CreditRating::AAA);
    }

    #[test]
    fn test_diverse_pool() {
        let mut gen = CustomerGenerator::new(42);
        let pool =
            gen.generate_diverse_pool(100, "1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());

        // Should have customers with various credit ratings
        let aaa_count = pool
            .customers
            .iter()
            .filter(|c| c.credit_rating == CreditRating::AAA)
            .count();
        let d_count = pool
            .customers
            .iter()
            .filter(|c| c.credit_rating == CreditRating::D)
            .count();

        assert!(aaa_count > 0);
        assert!(d_count > 0);
    }

    #[test]
    fn test_deterministic_generation() {
        let mut gen1 = CustomerGenerator::new(42);
        let mut gen2 = CustomerGenerator::new(42);

        let customer1 =
            gen1.generate_customer("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());
        let customer2 =
            gen2.generate_customer("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());

        assert_eq!(customer1.customer_id, customer2.customer_id);
        assert_eq!(customer1.name, customer2.name);
        assert_eq!(customer1.credit_rating, customer2.credit_rating);
    }

    #[test]
    fn test_customer_with_specific_credit() {
        let mut gen = CustomerGenerator::new(42);
        let customer = gen.generate_customer_with_credit(
            "1000",
            CreditRating::D,
            Decimal::from(5000),
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
        );

        assert_eq!(customer.credit_rating, CreditRating::D);
        assert_eq!(customer.credit_limit, Decimal::from(5000));
        assert_eq!(customer.payment_behavior, CustomerPaymentBehavior::HighRisk);
    }

    // ===== Customer Segmentation Tests =====

    #[test]
    fn test_segmented_pool_generation() {
        let segmentation_config = CustomerSegmentationConfig {
            enabled: true,
            ..Default::default()
        };

        let mut gen = CustomerGenerator::with_segmentation_config(
            42,
            CustomerGeneratorConfig::default(),
            segmentation_config,
        );

        let pool = gen.generate_segmented_pool(
            100,
            "1000",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            Decimal::from(10_000_000),
        );

        assert_eq!(pool.customers.len(), 100);
        assert!(!pool.customers.is_empty());
    }

    #[test]
    fn test_segment_distribution() {
        let segmentation_config = CustomerSegmentationConfig {
            enabled: true,
            segment_distribution: SegmentDistribution {
                enterprise: 0.05,
                mid_market: 0.20,
                smb: 0.50,
                consumer: 0.25,
            },
            ..Default::default()
        };

        let mut gen = CustomerGenerator::with_segmentation_config(
            42,
            CustomerGeneratorConfig::default(),
            segmentation_config,
        );

        let pool = gen.generate_segmented_pool(
            200,
            "1000",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            Decimal::from(10_000_000),
        );

        // Count by segment
        let enterprise_count = pool
            .customers
            .iter()
            .filter(|c| c.segment == CustomerValueSegment::Enterprise)
            .count();
        let smb_count = pool
            .customers
            .iter()
            .filter(|c| c.segment == CustomerValueSegment::Smb)
            .count();

        // Enterprise should be ~5% (10 of 200)
        assert!((5..=20).contains(&enterprise_count));
        // SMB should be ~50% (100 of 200)
        assert!((80..=120).contains(&smb_count));
    }

    #[test]
    fn test_referral_network() {
        let segmentation_config = CustomerSegmentationConfig {
            enabled: true,
            referral_config: ReferralConfig {
                enabled: true,
                referral_rate: 0.30, // Higher rate for testing
                max_referrals_per_customer: 5,
            },
            ..Default::default()
        };

        let mut gen = CustomerGenerator::with_segmentation_config(
            42,
            CustomerGeneratorConfig::default(),
            segmentation_config,
        );

        let pool = gen.generate_segmented_pool(
            50,
            "1000",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            Decimal::from(5_000_000),
        );

        // Count customers who were referred
        let referred_count = pool
            .customers
            .iter()
            .filter(|c| c.network_position.was_referred())
            .count();

        // Should have some referred customers
        assert!(referred_count > 0);
    }

    #[test]
    fn test_corporate_hierarchy() {
        let segmentation_config = CustomerSegmentationConfig {
            enabled: true,
            segment_distribution: SegmentDistribution {
                enterprise: 0.10, // More enterprise for testing
                mid_market: 0.30,
                smb: 0.40,
                consumer: 0.20,
            },
            hierarchy_config: HierarchyConfig {
                enabled: true,
                hierarchy_rate: 0.50, // Higher rate for testing
                max_depth: 3,
                billing_consolidation_rate: 0.50,
            },
            ..Default::default()
        };

        let mut gen = CustomerGenerator::with_segmentation_config(
            42,
            CustomerGeneratorConfig::default(),
            segmentation_config,
        );

        let pool = gen.generate_segmented_pool(
            50,
            "1000",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            Decimal::from(5_000_000),
        );

        // Count customers in hierarchies (have a parent)
        let in_hierarchy_count = pool
            .customers
            .iter()
            .filter(|c| c.network_position.parent_customer.is_some())
            .count();

        // Should have some customers in hierarchies
        assert!(in_hierarchy_count > 0);

        // Count enterprise customers with children
        let parents_with_children = pool
            .customers
            .iter()
            .filter(|c| {
                c.segment == CustomerValueSegment::Enterprise
                    && !c.network_position.child_customers.is_empty()
            })
            .count();

        assert!(parents_with_children > 0);
    }

    #[test]
    fn test_lifecycle_stages() {
        let segmentation_config = CustomerSegmentationConfig {
            enabled: true,
            lifecycle_distribution: LifecycleDistribution {
                prospect: 0.0,
                new: 0.20,
                growth: 0.20,
                mature: 0.40,
                at_risk: 0.15,
                churned: 0.05,
            },
            ..Default::default()
        };

        let mut gen = CustomerGenerator::with_segmentation_config(
            42,
            CustomerGeneratorConfig::default(),
            segmentation_config,
        );

        let pool = gen.generate_segmented_pool(
            100,
            "1000",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            Decimal::from(10_000_000),
        );

        // Count at-risk customers
        let at_risk_count = pool
            .customers
            .iter()
            .filter(|c| matches!(c.lifecycle_stage, CustomerLifecycleStage::AtRisk { .. }))
            .count();

        // Should be roughly 15%
        assert!((5..=30).contains(&at_risk_count));

        // Count mature customers
        let mature_count = pool
            .customers
            .iter()
            .filter(|c| matches!(c.lifecycle_stage, CustomerLifecycleStage::Mature { .. }))
            .count();

        // Should be roughly 40%
        assert!((25..=55).contains(&mature_count));
    }

    #[test]
    fn test_engagement_metrics() {
        let segmentation_config = CustomerSegmentationConfig {
            enabled: true,
            ..Default::default()
        };

        let mut gen = CustomerGenerator::with_segmentation_config(
            42,
            CustomerGeneratorConfig::default(),
            segmentation_config,
        );

        let pool = gen.generate_segmented_pool(
            20,
            "1000",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            Decimal::from(2_000_000),
        );

        // All customers should have engagement data populated
        for customer in &pool.customers {
            // Churned customers may have 0 orders
            if !matches!(
                customer.lifecycle_stage,
                CustomerLifecycleStage::Churned { .. }
            ) {
                // Active customers should have some orders
                assert!(
                    customer.engagement.total_orders > 0
                        || matches!(
                            customer.lifecycle_stage,
                            CustomerLifecycleStage::Prospect { .. }
                        )
                );
            }

            // Churn risk should be calculated
            assert!(customer.churn_risk_score >= 0.0 && customer.churn_risk_score <= 1.0);
        }
    }

    #[test]
    fn test_segment_distribution_validation() {
        let valid = SegmentDistribution::default();
        assert!(valid.validate().is_ok());

        let invalid = SegmentDistribution {
            enterprise: 0.5,
            mid_market: 0.5,
            smb: 0.5,
            consumer: 0.5,
        };
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn test_segmentation_disabled() {
        let segmentation_config = CustomerSegmentationConfig {
            enabled: false,
            ..Default::default()
        };

        let mut gen = CustomerGenerator::with_segmentation_config(
            42,
            CustomerGeneratorConfig::default(),
            segmentation_config,
        );

        let pool = gen.generate_segmented_pool(
            20,
            "1000",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            Decimal::from(2_000_000),
        );

        // Should return empty pool when disabled
        assert!(pool.customers.is_empty());
    }

    #[test]
    fn test_customer_auxiliary_gl_account_french() {
        let mut gen = CustomerGenerator::new(42);
        gen.set_coa_framework(CoAFramework::FrenchPcg);
        let customer = gen.generate_customer("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());

        assert!(customer.auxiliary_gl_account.is_some());
        let aux = customer.auxiliary_gl_account.unwrap();
        assert!(
            aux.starts_with("411"),
            "French PCG customer auxiliary should start with 411, got {}",
            aux
        );
    }

    #[test]
    fn test_customer_auxiliary_gl_account_german() {
        let mut gen = CustomerGenerator::new(42);
        gen.set_coa_framework(CoAFramework::GermanSkr04);
        let customer = gen.generate_customer("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());

        assert!(customer.auxiliary_gl_account.is_some());
        let aux = customer.auxiliary_gl_account.unwrap();
        assert!(
            aux.starts_with("1200"),
            "German SKR04 customer auxiliary should start with 1200, got {}",
            aux
        );
    }

    #[test]
    fn test_customer_auxiliary_gl_account_us_gaap() {
        let mut gen = CustomerGenerator::new(42);
        let customer = gen.generate_customer("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());
        assert!(customer.auxiliary_gl_account.is_none());
    }

    #[test]
    fn test_customer_name_dedup() {
        let mut gen = CustomerGenerator::new(42);
        let mut names = HashSet::new();

        for _ in 0..200 {
            let customer =
                gen.generate_customer("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());
            assert!(
                names.insert(customer.name.clone()),
                "Duplicate customer name found: {}",
                customer.name
            );
        }
    }
}