datasynth-generators 2.2.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
//! Payroll generator for the Hire-to-Retire (H2R) process.
//!
//! Generates payroll runs with individual employee line items, computing
//! gross pay (base salary + overtime + bonus), deductions (tax, social security,
//! health insurance, retirement), and net pay.

use chrono::NaiveDate;
use datasynth_config::schema::PayrollConfig;
use datasynth_core::country::schema::TaxBracket;
use datasynth_core::models::{PayrollLineItem, PayrollRun, PayrollRunStatus};
use datasynth_core::utils::{sample_decimal_range, seeded_rng};
use datasynth_core::uuid_factory::{DeterministicUuidFactory, GeneratorType};
use datasynth_core::CountryPack;
use rand::prelude::*;
use rand_chacha::ChaCha8Rng;
use rust_decimal::Decimal;
use tracing::debug;

/// Resolved payroll deduction rates used during generation.
#[derive(Debug, Clone)]
struct PayrollRates {
    /// Combined income tax rate (federal + state, or equivalent).
    income_tax_rate: Decimal,
    /// Progressive income tax brackets from country pack (if available).
    income_tax_brackets: Vec<TaxBracket>,
    /// Social security / FICA rate.
    fica_rate: Decimal,
    /// Employee health insurance rate.
    health_rate: Decimal,
    /// Employee retirement / pension rate.
    retirement_rate: Decimal,
    /// Employer-side social security matching rate.
    employer_fica_rate: Decimal,
}

/// Country-pack-derived deduction labels applied to every line item in a run.
#[derive(Debug, Clone, Default)]
struct DeductionLabels {
    tax_withholding: Option<String>,
    social_security: Option<String>,
    health_insurance: Option<String>,
    retirement_contribution: Option<String>,
    employer_contribution: Option<String>,
}

/// Generates [`PayrollRun`] and [`PayrollLineItem`] records from employee data.
pub struct PayrollGenerator {
    rng: ChaCha8Rng,
    uuid_factory: DeterministicUuidFactory,
    line_uuid_factory: DeterministicUuidFactory,
    config: PayrollConfig,
    country_pack: Option<CountryPack>,
    /// Pool of real employee IDs for approved_by / posted_by references.
    employee_ids_pool: Vec<String>,
    /// Pool of real cost center IDs (unused directly here since cost_center
    /// comes from the employee tuple, but kept for consistency).
    cost_center_ids_pool: Vec<String>,
}

impl PayrollGenerator {
    /// Create a new payroll generator with default configuration.
    pub fn new(seed: u64) -> Self {
        Self {
            rng: seeded_rng(seed, 0),
            uuid_factory: DeterministicUuidFactory::new(seed, GeneratorType::PayrollRun),
            line_uuid_factory: DeterministicUuidFactory::with_sub_discriminator(
                seed,
                GeneratorType::PayrollRun,
                1,
            ),
            config: PayrollConfig::default(),
            country_pack: None,
            employee_ids_pool: Vec::new(),
            cost_center_ids_pool: Vec::new(),
        }
    }

    /// Create a payroll generator with custom configuration.
    pub fn with_config(seed: u64, config: PayrollConfig) -> Self {
        Self {
            rng: seeded_rng(seed, 0),
            uuid_factory: DeterministicUuidFactory::new(seed, GeneratorType::PayrollRun),
            line_uuid_factory: DeterministicUuidFactory::with_sub_discriminator(
                seed,
                GeneratorType::PayrollRun,
                1,
            ),
            config,
            country_pack: None,
            employee_ids_pool: Vec::new(),
            cost_center_ids_pool: Vec::new(),
        }
    }

    /// Set ID pools for cross-reference coherence.
    ///
    /// When pools are non-empty, the generator selects `approved_by` and
    /// `posted_by` from `employee_ids` instead of fabricating placeholder IDs.
    pub fn with_pools(mut self, employee_ids: Vec<String>, cost_center_ids: Vec<String>) -> Self {
        self.employee_ids_pool = employee_ids;
        self.cost_center_ids_pool = cost_center_ids;
        self
    }

    /// Set the country pack for localized deduction labels.
    ///
    /// When a country pack is set, generated [`PayrollLineItem`] records will
    /// carry localized deduction labels derived from the pack's
    /// `payroll.statutory_deductions` and `payroll.employer_contributions`.
    /// The stored pack is also used by [`generate`] to resolve deduction rates,
    /// so callers no longer need to pass the pack explicitly.
    pub fn set_country_pack(&mut self, pack: CountryPack) {
        self.country_pack = Some(pack);
    }

    /// Generate a payroll run and line items for the given employees and period.
    ///
    /// Uses tax rates from the [`PayrollConfig`] (defaults: 22% federal, 5% state,
    /// 7.65% FICA, 3% health, 5% retirement).  If a country pack has been set via
    /// [`set_country_pack`], the stored pack is used to resolve both rates and
    /// localized deduction labels automatically.
    ///
    /// # Arguments
    ///
    /// * `company_code` - Company code owning the payroll
    /// * `employees` - Slice of (employee_id, base_salary, cost_center, department)
    /// * `period_start` - Start of the pay period (inclusive)
    /// * `period_end` - End of the pay period (inclusive)
    /// * `currency` - ISO 4217 currency code
    pub fn generate(
        &mut self,
        company_code: &str,
        employees: &[(String, Decimal, Option<String>, Option<String>)],
        period_start: NaiveDate,
        period_end: NaiveDate,
        currency: &str,
    ) -> (PayrollRun, Vec<PayrollLineItem>) {
        debug!(company_code, employee_count = employees.len(), %period_start, %period_end, currency, "Generating payroll run");
        if let Some(pack) = self.country_pack.as_ref() {
            let rates = self.rates_from_country_pack(pack);
            let labels = Self::labels_from_country_pack(pack);
            self.generate_with_rates_and_labels(
                company_code,
                employees,
                period_start,
                period_end,
                currency,
                &rates,
                &labels,
            )
        } else {
            let rates = self.rates_from_config();
            self.generate_with_rates_and_labels(
                company_code,
                employees,
                period_start,
                period_end,
                currency,
                &rates,
                &DeductionLabels::default(),
            )
        }
    }

    /// Generate a payroll run using statutory deduction rates from a country pack.
    ///
    /// Iterates over `pack.payroll.statutory_deductions` to resolve rates by
    /// deduction code / English name.  Any rate not found in the pack falls back
    /// to the corresponding value from the generator's [`PayrollConfig`].
    ///
    /// # Deduction mapping
    ///
    /// | Pack code / `name_en` pattern              | Resolves to         |
    /// |--------------------------------------------|---------------------|
    /// | `FIT`, `LOHNST`, or `*Income Tax*` (not state) | federal income tax  |
    /// | `SIT` or `*State Income Tax*`              | state income tax    |
    /// | `FICA` or `*Social Security*`              | FICA / social security |
    /// | `*Health Insurance*`                       | health insurance    |
    /// | `*Pension*` or `*Retirement*`              | retirement / pension |
    ///
    /// For packs that have many small deductions (e.g. DE with pension, health,
    /// unemployment, long-term care, solidarity surcharge, church tax), the rates
    /// are summed into the closest category. Deductions not matching any category
    /// above are accumulated into the FICA/social-security bucket.
    pub fn generate_with_country_pack(
        &mut self,
        company_code: &str,
        employees: &[(String, Decimal, Option<String>, Option<String>)],
        period_start: NaiveDate,
        period_end: NaiveDate,
        currency: &str,
        pack: &CountryPack,
    ) -> (PayrollRun, Vec<PayrollLineItem>) {
        let rates = self.rates_from_country_pack(pack);
        let labels = Self::labels_from_country_pack(pack);
        self.generate_with_rates_and_labels(
            company_code,
            employees,
            period_start,
            period_end,
            currency,
            &rates,
            &labels,
        )
    }

    // ------------------------------------------------------------------
    // Private helpers
    // ------------------------------------------------------------------

    /// Build [`PayrollRates`] from the generator's config (original behaviour).
    fn rates_from_config(&self) -> PayrollRates {
        let federal_rate = Decimal::from_f64_retain(self.config.tax_rates.federal_effective)
            .unwrap_or(Decimal::ZERO);
        let state_rate = Decimal::from_f64_retain(self.config.tax_rates.state_effective)
            .unwrap_or(Decimal::ZERO);
        let fica_rate =
            Decimal::from_f64_retain(self.config.tax_rates.fica).unwrap_or(Decimal::ZERO);

        PayrollRates {
            income_tax_rate: federal_rate + state_rate,
            income_tax_brackets: Vec::new(),
            fica_rate,
            health_rate: Decimal::from_f64_retain(0.03).unwrap_or(Decimal::ZERO),
            retirement_rate: Decimal::from_f64_retain(0.05).unwrap_or(Decimal::ZERO),
            employer_fica_rate: fica_rate,
        }
    }

    /// Compute progressive tax using marginal brackets.
    ///
    /// Iterates brackets in ascending order. Each bracket taxes only the
    /// portion of income within that bracket at the bracket's rate. The
    /// terminal bracket (no `up_to`) taxes all remaining income.
    fn compute_progressive_tax(annual_income: Decimal, brackets: &[TaxBracket]) -> Decimal {
        let mut total_tax = Decimal::ZERO;
        let mut taxed_up_to = Decimal::ZERO;

        for bracket in brackets {
            let bracket_floor = bracket
                .above
                .and_then(Decimal::from_f64_retain)
                .unwrap_or(taxed_up_to);
            let bracket_rate = Decimal::from_f64_retain(bracket.rate).unwrap_or(Decimal::ZERO);

            if annual_income <= bracket_floor {
                break;
            }

            let taxable_in_bracket = if let Some(ceiling) = bracket.up_to {
                let ceiling = Decimal::from_f64_retain(ceiling).unwrap_or(Decimal::ZERO);
                (annual_income.min(ceiling) - bracket_floor).max(Decimal::ZERO)
            } else {
                // Terminal bracket — tax all remaining income
                (annual_income - bracket_floor).max(Decimal::ZERO)
            };

            total_tax += (taxable_in_bracket * bracket_rate).round_dp(2);
            taxed_up_to = bracket
                .up_to
                .and_then(Decimal::from_f64_retain)
                .unwrap_or(annual_income);
        }

        total_tax.round_dp(2)
    }

    /// Build [`PayrollRates`] from a [`CountryPack`], falling back to config
    /// values for any category not found.
    fn rates_from_country_pack(&self, pack: &CountryPack) -> PayrollRates {
        let fallback = self.rates_from_config();

        // Accumulators – start at zero; we only use the fallback when a
        // category has *no* matching deduction in the pack at all.
        let mut federal_tax = Decimal::ZERO;
        let mut state_tax = Decimal::ZERO;
        let mut fica = Decimal::ZERO;
        let mut health = Decimal::ZERO;
        let mut retirement = Decimal::ZERO;

        // Track which categories were populated from the pack.
        let mut found_federal = false;
        let mut found_state = false;
        let mut found_fica = false;
        let mut found_health = false;
        let mut found_retirement = false;

        for ded in &pack.payroll.statutory_deductions {
            let code_upper = ded.code.to_uppercase();
            let name_en_lower = ded.name_en.to_lowercase();
            let rate = Decimal::from_f64_retain(ded.rate).unwrap_or(Decimal::ZERO);

            // Progressive (bracket-based) income taxes have rate 0.0 as a
            // placeholder. Mark the category as found so the config fallback
            // is skipped — the actual tax will be computed per-employee from
            // the bracket table in generate_with_rates_and_labels().
            if (ded.deduction_type == "progressive" || ded.type_field == "progressive")
                && ded.rate == 0.0
            {
                if code_upper == "FIT"
                    || code_upper == "LOHNST"
                    || (name_en_lower.contains("income tax") && !name_en_lower.contains("state"))
                {
                    found_federal = true;
                }
                continue;
            }

            if code_upper == "FIT"
                || code_upper == "LOHNST"
                || (name_en_lower.contains("income tax") && !name_en_lower.contains("state"))
            {
                federal_tax += rate;
                found_federal = true;
            } else if code_upper == "SIT" || name_en_lower.contains("state income tax") {
                state_tax += rate;
                found_state = true;
            } else if code_upper == "FICA" || name_en_lower.contains("social security") {
                fica += rate;
                found_fica = true;
            } else if name_en_lower.contains("health insurance") {
                health += rate;
                found_health = true;
            } else if name_en_lower.contains("pension") || name_en_lower.contains("retirement") {
                retirement += rate;
                found_retirement = true;
            } else {
                // Unrecognised statutory deductions (solidarity surcharge,
                // church tax, unemployment insurance, long-term care, etc.)
                // are accumulated into the social-security / FICA bucket so
                // that total deductions still reflect the country's burden.
                fica += rate;
                found_fica = true;
            }
        }

        PayrollRates {
            income_tax_rate: if found_federal || found_state {
                let f = if found_federal {
                    federal_tax
                } else {
                    fallback.income_tax_rate
                        - Decimal::from_f64_retain(self.config.tax_rates.state_effective)
                            .unwrap_or(Decimal::ZERO)
                };
                let s = if found_state {
                    state_tax
                } else {
                    Decimal::from_f64_retain(self.config.tax_rates.state_effective)
                        .unwrap_or(Decimal::ZERO)
                };
                f + s
            } else {
                fallback.income_tax_rate
            },
            income_tax_brackets: pack.tax.payroll_tax.income_tax_brackets.clone(),
            fica_rate: if found_fica { fica } else { fallback.fica_rate },
            health_rate: if found_health {
                health
            } else {
                fallback.health_rate
            },
            retirement_rate: if found_retirement {
                retirement
            } else {
                fallback.retirement_rate
            },
            employer_fica_rate: if found_fica {
                fica
            } else {
                fallback.employer_fica_rate
            },
        }
    }

    /// Build [`DeductionLabels`] from a country pack.
    ///
    /// Walks the pack's `statutory_deductions` and `employer_contributions` and
    /// picks the matching deduction's localized `name` (falling back to
    /// `name_en` when `name` is empty) for each category.  The matching logic
    /// mirrors [`rates_from_country_pack`] so labels and rates stay consistent.
    fn labels_from_country_pack(pack: &CountryPack) -> DeductionLabels {
        let mut labels = DeductionLabels::default();

        for ded in &pack.payroll.statutory_deductions {
            let code_upper = ded.code.to_uppercase();
            let name_en_lower = ded.name_en.to_lowercase();

            // Pick the best human-readable label: prefer localized `name`, fall
            // back to `name_en`.
            let label = if ded.name.is_empty() {
                ded.name_en.clone()
            } else {
                ded.name.clone()
            };
            if label.is_empty() {
                continue;
            }

            // For progressive placeholders (rate 0), still capture the label
            // since the config-fallback rate will be used for the amount.
            if (ded.deduction_type == "progressive" || ded.type_field == "progressive")
                && ded.rate == 0.0
            {
                if code_upper == "FIT"
                    || code_upper == "LOHNST"
                    || (name_en_lower.contains("income tax") && !name_en_lower.contains("state"))
                {
                    if labels.tax_withholding.is_none() {
                        labels.tax_withholding = Some(label);
                    }
                } else if code_upper == "SIT" || name_en_lower.contains("state income tax") {
                    labels.tax_withholding = Some(match labels.tax_withholding.take() {
                        Some(existing) => format!("{existing}; {label}"),
                        None => label,
                    });
                }
                continue;
            }

            if code_upper == "FIT"
                || code_upper == "LOHNST"
                || code_upper == "SIT"
                || name_en_lower.contains("income tax")
                || name_en_lower.contains("state income tax")
            {
                // All income-tax-related deductions (federal, state, combined)
                // are grouped under the tax_withholding label.
                labels.tax_withholding = Some(match labels.tax_withholding.take() {
                    Some(existing) => format!("{existing}; {label}"),
                    None => label,
                });
            } else if code_upper == "FICA" || name_en_lower.contains("social security") {
                labels.social_security = Some(match labels.social_security.take() {
                    Some(existing) => format!("{existing}; {label}"),
                    None => label,
                });
            } else if name_en_lower.contains("health insurance") {
                if labels.health_insurance.is_none() {
                    labels.health_insurance = Some(label);
                }
            } else if name_en_lower.contains("pension") || name_en_lower.contains("retirement") {
                if labels.retirement_contribution.is_none() {
                    labels.retirement_contribution = Some(label);
                }
            } else {
                // Misc deductions (unemployment, church tax, etc.) — append to
                // social_security label since those rates go into that bucket.
                labels.social_security = Some(match labels.social_security.take() {
                    Some(existing) => format!("{existing}; {label}"),
                    None => label,
                });
            }
        }

        // Employer contributions
        let emp_labels: Vec<String> = pack
            .payroll
            .employer_contributions
            .iter()
            .filter_map(|c| {
                let l = if c.name.is_empty() {
                    c.name_en.clone()
                } else {
                    c.name.clone()
                };
                if l.is_empty() {
                    None
                } else {
                    Some(l)
                }
            })
            .collect();
        if !emp_labels.is_empty() {
            labels.employer_contribution = Some(emp_labels.join("; "));
        }

        labels
    }

    /// Core generation logic parameterised on resolved rates and labels.
    fn generate_with_rates_and_labels(
        &mut self,
        company_code: &str,
        employees: &[(String, Decimal, Option<String>, Option<String>)],
        period_start: NaiveDate,
        period_end: NaiveDate,
        currency: &str,
        rates: &PayrollRates,
        labels: &DeductionLabels,
    ) -> (PayrollRun, Vec<PayrollLineItem>) {
        let payroll_id = self.uuid_factory.next().to_string();

        let mut line_items = Vec::with_capacity(employees.len());
        let mut total_gross = Decimal::ZERO;
        let mut total_deductions = Decimal::ZERO;
        let mut total_net = Decimal::ZERO;
        let mut total_employer_cost = Decimal::ZERO;

        let benefits_enrolled = self.config.benefits_enrollment_rate;
        let retirement_participating = self.config.retirement_participation_rate;

        for (employee_id, base_salary, cost_center, department) in employees {
            let line_id = self.line_uuid_factory.next().to_string();

            // Monthly base component (annual salary / 12)
            let monthly_base = (*base_salary / Decimal::from(12)).round_dp(2);

            // Overtime: 10% chance, 1-20 hours at 1.5x hourly rate
            let (overtime_pay, overtime_hours) = if self.rng.random_bool(0.10) {
                let ot_hours = self.rng.random_range(1.0..=20.0);
                // Hourly rate = annual salary / (52 weeks * 40 hours)
                let hourly_rate = *base_salary / Decimal::from(2080);
                let ot_rate = hourly_rate * Decimal::from_f64_retain(1.5).unwrap_or(Decimal::ONE);
                let ot_pay = (ot_rate
                    * Decimal::from_f64_retain(ot_hours).unwrap_or(Decimal::ZERO))
                .round_dp(2);
                (ot_pay, ot_hours)
            } else {
                (Decimal::ZERO, 0.0)
            };

            // Bonus: 5% chance for a monthly bonus (1-10% of monthly base)
            let bonus = if self.rng.random_bool(0.05) {
                let pct = self.rng.random_range(0.01..=0.10);
                (monthly_base * Decimal::from_f64_retain(pct).unwrap_or(Decimal::ZERO)).round_dp(2)
            } else {
                Decimal::ZERO
            };

            let gross_pay = monthly_base + overtime_pay + bonus;

            // Deductions — use progressive brackets when available
            let tax_withholding = if !rates.income_tax_brackets.is_empty() {
                let annual = gross_pay * Decimal::from(12);
                Self::compute_progressive_tax(annual, &rates.income_tax_brackets)
                    / Decimal::from(12)
            } else {
                (gross_pay * rates.income_tax_rate).round_dp(2)
            };
            let social_security = (gross_pay * rates.fica_rate).round_dp(2);

            let health_insurance = if self.rng.random_bool(benefits_enrolled) {
                (gross_pay * rates.health_rate).round_dp(2)
            } else {
                Decimal::ZERO
            };

            let retirement_contribution = if self.rng.random_bool(retirement_participating) {
                (gross_pay * rates.retirement_rate).round_dp(2)
            } else {
                Decimal::ZERO
            };

            // Small random other deductions (garnishments, etc.): ~3% chance
            let other_deductions = if self.rng.random_bool(0.03) {
                sample_decimal_range(&mut self.rng, Decimal::from(50), Decimal::from(500))
                    .round_dp(2)
            } else {
                Decimal::ZERO
            };

            let total_ded = tax_withholding
                + social_security
                + health_insurance
                + retirement_contribution
                + other_deductions;
            let net_pay = gross_pay - total_ded;

            // Standard 160 regular hours per month (8h * 20 business days)
            let hours_worked = 160.0;

            // Employer-side cost: gross + employer contribution match
            let employer_contrib = (gross_pay * rates.employer_fica_rate).round_dp(2);
            let employer_cost = gross_pay + employer_contrib;

            total_gross += gross_pay;
            total_deductions += total_ded;
            total_net += net_pay;
            total_employer_cost += employer_cost;

            line_items.push(PayrollLineItem {
                payroll_id: payroll_id.clone(),
                employee_id: employee_id.clone(),
                line_id,
                gross_pay,
                base_salary: monthly_base,
                overtime_pay,
                bonus,
                tax_withholding,
                social_security,
                health_insurance,
                retirement_contribution,
                other_deductions,
                net_pay,
                hours_worked,
                overtime_hours,
                pay_date: period_end,
                cost_center: cost_center.clone(),
                department: department.clone(),
                tax_withholding_label: labels.tax_withholding.clone(),
                social_security_label: labels.social_security.clone(),
                health_insurance_label: labels.health_insurance.clone(),
                retirement_contribution_label: labels.retirement_contribution.clone(),
                employer_contribution_label: labels.employer_contribution.clone(),
            });
        }

        // Determine status
        let status_roll: f64 = self.rng.random();
        let status = if status_roll < 0.60 {
            PayrollRunStatus::Posted
        } else if status_roll < 0.85 {
            PayrollRunStatus::Approved
        } else if status_roll < 0.95 {
            PayrollRunStatus::Calculated
        } else {
            PayrollRunStatus::Draft
        };

        let approved_by = if matches!(
            status,
            PayrollRunStatus::Approved | PayrollRunStatus::Posted
        ) {
            if !self.employee_ids_pool.is_empty() {
                let idx = self.rng.random_range(0..self.employee_ids_pool.len());
                Some(self.employee_ids_pool[idx].clone())
            } else {
                Some(format!("USR-{:04}", self.rng.random_range(201..=400)))
            }
        } else {
            None
        };

        let posted_by = if status == PayrollRunStatus::Posted {
            if !self.employee_ids_pool.is_empty() {
                let idx = self.rng.random_range(0..self.employee_ids_pool.len());
                Some(self.employee_ids_pool[idx].clone())
            } else {
                Some(format!("USR-{:04}", self.rng.random_range(401..=500)))
            }
        } else {
            None
        };

        let run = PayrollRun {
            company_code: company_code.to_string(),
            payroll_id: payroll_id.clone(),
            pay_period_start: period_start,
            pay_period_end: period_end,
            run_date: period_end,
            status,
            total_gross,
            total_deductions,
            total_net,
            total_employer_cost,
            employee_count: employees.len() as u32,
            currency: currency.to_string(),
            posted_by,
            approved_by,
        };

        (run, line_items)
    }

    /// Generate a payroll run, adjusting each employee's salary based on
    /// [`EmployeeChangeEvent`] records before delegating to [`generate`].
    ///
    /// For each employee, all `SalaryAdjustment` events whose `effective_date`
    /// falls on or before `period_end` are examined.  The most recent such
    /// event determines the effective annual salary for the period (prorated
    /// when the effective date falls mid-period).
    ///
    /// # Arguments
    ///
    /// * `company_code`  - Company code owning the payroll
    /// * `employees`     - Slice of (employee_id, base_annual_salary, cost_center, department)
    /// * `period_start`  - Start of the pay period (inclusive)
    /// * `period_end`    - End of the pay period (inclusive)
    /// * `currency`      - ISO 4217 currency code
    /// * `changes`       - Employee change history to apply
    pub fn generate_with_changes(
        &mut self,
        company_code: &str,
        employees: &[(String, Decimal, Option<String>, Option<String>)],
        period_start: NaiveDate,
        period_end: NaiveDate,
        currency: &str,
        changes: &[datasynth_core::models::EmployeeChangeEvent],
    ) -> (PayrollRun, Vec<PayrollLineItem>) {
        let adjusted: Vec<(String, Decimal, Option<String>, Option<String>)> = employees
            .iter()
            .map(|(id, salary, cc, dept)| {
                let adjusted_salary =
                    Self::apply_salary_changes(id, *salary, period_start, period_end, changes);
                (id.clone(), adjusted_salary, cc.clone(), dept.clone())
            })
            .collect();
        self.generate(company_code, &adjusted, period_start, period_end, currency)
    }

    /// Compute the effective annual salary for one employee over a pay period,
    /// taking `SalaryAdjustment` events into account.
    ///
    /// If the latest qualifying change became effective before `period_start`,
    /// the new salary applies for the full period.  If it became effective
    /// mid-period, the salary is prorated by calendar days.
    fn apply_salary_changes(
        employee_id: &str,
        base_annual_salary: Decimal,
        period_start: NaiveDate,
        period_end: NaiveDate,
        changes: &[datasynth_core::models::EmployeeChangeEvent],
    ) -> Decimal {
        use datasynth_core::models::EmployeeEventType;

        // Filter: only SalaryAdjustment events for this employee that are on or
        // before period_end (i.e. they could affect this payroll period).
        let relevant: Vec<&datasynth_core::models::EmployeeChangeEvent> = changes
            .iter()
            .filter(|c| {
                c.employee_id == employee_id
                    && c.event_type == EmployeeEventType::SalaryAdjustment
                    && c.effective_date <= period_end
            })
            .collect();

        if relevant.is_empty() {
            return base_annual_salary;
        }

        // Find the latest change by effective_date.
        let latest = relevant
            .iter()
            .max_by_key(|c| c.effective_date)
            .expect("non-empty slice always has a max");

        // Parse the new annual salary from new_value.
        let new_salary = match latest
            .new_value
            .as_deref()
            .and_then(|v| v.parse::<Decimal>().ok())
        {
            Some(s) => s,
            None => return base_annual_salary,
        };

        let effective = latest.effective_date;

        if effective <= period_start {
            // Change took effect before or on period start → full period at new rate.
            new_salary
        } else {
            // Change is mid-period → prorate.
            let total_days = (period_end - period_start).num_days() + 1;
            let days_at_old = (effective - period_start).num_days();
            let days_at_new = total_days - days_at_old;

            let total = Decimal::from(total_days);
            let old_fraction = Decimal::from(days_at_old) / total;
            let new_fraction = Decimal::from(days_at_new) / total;

            (base_annual_salary * old_fraction + new_salary * new_fraction).round_dp(2)
        }
    }
}

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

    fn test_employees() -> Vec<(String, Decimal, Option<String>, Option<String>)> {
        vec![
            (
                "EMP-001".to_string(),
                Decimal::from(60_000),
                Some("CC-100".to_string()),
                Some("Engineering".to_string()),
            ),
            (
                "EMP-002".to_string(),
                Decimal::from(85_000),
                Some("CC-200".to_string()),
                Some("Finance".to_string()),
            ),
            (
                "EMP-003".to_string(),
                Decimal::from(120_000),
                None,
                Some("Sales".to_string()),
            ),
        ]
    }

    #[test]
    fn test_basic_payroll_generation() {
        let mut gen = PayrollGenerator::new(42);
        let employees = test_employees();
        let period_start = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let period_end = NaiveDate::from_ymd_opt(2024, 1, 31).unwrap();

        let (run, items) = gen.generate("C001", &employees, period_start, period_end, "USD");

        assert_eq!(run.company_code, "C001");
        assert_eq!(run.currency, "USD");
        assert_eq!(run.employee_count, 3);
        assert_eq!(items.len(), 3);
        assert!(run.total_gross > Decimal::ZERO);
        assert!(run.total_deductions > Decimal::ZERO);
        assert!(run.total_net > Decimal::ZERO);
        assert!(run.total_employer_cost > run.total_gross);
        // net = gross - deductions
        assert_eq!(run.total_net, run.total_gross - run.total_deductions);

        for item in &items {
            assert_eq!(item.payroll_id, run.payroll_id);
            assert!(item.gross_pay > Decimal::ZERO);
            assert!(item.net_pay > Decimal::ZERO);
            assert!(item.net_pay < item.gross_pay);
            assert!(item.base_salary > Decimal::ZERO);
            assert_eq!(item.pay_date, period_end);
            // Without country pack, labels should be None
            assert!(item.tax_withholding_label.is_none());
            assert!(item.social_security_label.is_none());
        }
    }

    #[test]
    fn test_deterministic_payroll() {
        let employees = test_employees();
        let period_start = NaiveDate::from_ymd_opt(2024, 3, 1).unwrap();
        let period_end = NaiveDate::from_ymd_opt(2024, 3, 31).unwrap();

        let mut gen1 = PayrollGenerator::new(42);
        let (run1, items1) = gen1.generate("C001", &employees, period_start, period_end, "USD");

        let mut gen2 = PayrollGenerator::new(42);
        let (run2, items2) = gen2.generate("C001", &employees, period_start, period_end, "USD");

        assert_eq!(run1.payroll_id, run2.payroll_id);
        assert_eq!(run1.total_gross, run2.total_gross);
        assert_eq!(run1.total_net, run2.total_net);
        assert_eq!(run1.status, run2.status);
        assert_eq!(items1.len(), items2.len());
        for (a, b) in items1.iter().zip(items2.iter()) {
            assert_eq!(a.line_id, b.line_id);
            assert_eq!(a.gross_pay, b.gross_pay);
            assert_eq!(a.net_pay, b.net_pay);
        }
    }

    #[test]
    fn test_payroll_deduction_components() {
        let mut gen = PayrollGenerator::new(99);
        let employees = vec![(
            "EMP-010".to_string(),
            Decimal::from(100_000),
            Some("CC-300".to_string()),
            Some("HR".to_string()),
        )];
        let period_start = NaiveDate::from_ymd_opt(2024, 6, 1).unwrap();
        let period_end = NaiveDate::from_ymd_opt(2024, 6, 30).unwrap();

        let (_run, items) = gen.generate("C001", &employees, period_start, period_end, "USD");
        assert_eq!(items.len(), 1);

        let item = &items[0];
        // base_salary should be approximately 100000/12 = 8333.33
        let expected_monthly = (Decimal::from(100_000) / Decimal::from(12)).round_dp(2);
        assert_eq!(item.base_salary, expected_monthly);

        // Deductions should sum correctly
        let deduction_sum = item.tax_withholding
            + item.social_security
            + item.health_insurance
            + item.retirement_contribution
            + item.other_deductions;
        let expected_net = item.gross_pay - deduction_sum;
        assert_eq!(item.net_pay, expected_net);

        // Tax withholding should be reasonable (22% federal + 5% state = 27% of gross)
        assert!(item.tax_withholding > Decimal::ZERO);
        assert!(item.social_security > Decimal::ZERO);
    }

    // ---------------------------------------------------------------
    // Country-pack tests
    // ---------------------------------------------------------------

    /// Helper: build a US-like country pack with explicit statutory deductions.
    fn us_country_pack() -> CountryPack {
        use datasynth_core::country::schema::{PayrollCountryConfig, PayrollDeduction};
        CountryPack {
            country_code: "US".to_string(),
            payroll: PayrollCountryConfig {
                statutory_deductions: vec![
                    PayrollDeduction {
                        code: "FICA".to_string(),
                        name_en: "Federal Insurance Contributions Act".to_string(),
                        deduction_type: "percentage".to_string(),
                        rate: 0.0765,
                        ..Default::default()
                    },
                    PayrollDeduction {
                        code: "FIT".to_string(),
                        name_en: "Federal Income Tax".to_string(),
                        deduction_type: "progressive".to_string(),
                        rate: 0.0, // progressive placeholder
                        ..Default::default()
                    },
                    PayrollDeduction {
                        code: "SIT".to_string(),
                        name_en: "State Income Tax".to_string(),
                        deduction_type: "percentage".to_string(),
                        rate: 0.05,
                        ..Default::default()
                    },
                ],
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// Helper: build a DE-like country pack.
    fn de_country_pack() -> CountryPack {
        use datasynth_core::country::schema::{PayrollCountryConfig, PayrollDeduction};
        CountryPack {
            country_code: "DE".to_string(),
            payroll: PayrollCountryConfig {
                pay_frequency: "monthly".to_string(),
                currency: "EUR".to_string(),
                statutory_deductions: vec![
                    PayrollDeduction {
                        code: "LOHNST".to_string(),
                        name_en: "Income Tax".to_string(),
                        type_field: "progressive".to_string(),
                        rate: 0.0, // progressive placeholder
                        ..Default::default()
                    },
                    PayrollDeduction {
                        code: "SOLI".to_string(),
                        name_en: "Solidarity Surcharge".to_string(),
                        type_field: "percentage".to_string(),
                        rate: 0.055,
                        ..Default::default()
                    },
                    PayrollDeduction {
                        code: "KiSt".to_string(),
                        name_en: "Church Tax".to_string(),
                        type_field: "percentage".to_string(),
                        rate: 0.08,
                        optional: true,
                        ..Default::default()
                    },
                    PayrollDeduction {
                        code: "RV".to_string(),
                        name_en: "Pension Insurance".to_string(),
                        type_field: "percentage".to_string(),
                        rate: 0.093,
                        ..Default::default()
                    },
                    PayrollDeduction {
                        code: "KV".to_string(),
                        name_en: "Health Insurance".to_string(),
                        type_field: "percentage".to_string(),
                        rate: 0.073,
                        ..Default::default()
                    },
                    PayrollDeduction {
                        code: "AV".to_string(),
                        name_en: "Unemployment Insurance".to_string(),
                        type_field: "percentage".to_string(),
                        rate: 0.013,
                        ..Default::default()
                    },
                    PayrollDeduction {
                        code: "PV".to_string(),
                        name_en: "Long-Term Care Insurance".to_string(),
                        type_field: "percentage".to_string(),
                        rate: 0.017,
                        ..Default::default()
                    },
                ],
                employer_contributions: vec![
                    PayrollDeduction {
                        code: "AG-RV".to_string(),
                        name_en: "Employer Pension Insurance".to_string(),
                        type_field: "percentage".to_string(),
                        rate: 0.093,
                        ..Default::default()
                    },
                    PayrollDeduction {
                        code: "AG-KV".to_string(),
                        name_en: "Employer Health Insurance".to_string(),
                        type_field: "percentage".to_string(),
                        rate: 0.073,
                        ..Default::default()
                    },
                ],
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[test]
    fn test_generate_with_us_country_pack() {
        let mut gen = PayrollGenerator::new(42);
        let employees = test_employees();
        let period_start = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let period_end = NaiveDate::from_ymd_opt(2024, 1, 31).unwrap();
        let pack = us_country_pack();

        let (run, items) = gen.generate_with_country_pack(
            "C001",
            &employees,
            period_start,
            period_end,
            "USD",
            &pack,
        );

        assert_eq!(run.company_code, "C001");
        assert_eq!(run.employee_count, 3);
        assert_eq!(items.len(), 3);
        assert_eq!(run.total_net, run.total_gross - run.total_deductions);

        for item in &items {
            assert!(item.gross_pay > Decimal::ZERO);
            assert!(item.net_pay > Decimal::ZERO);
            assert!(item.net_pay < item.gross_pay);
            // FICA deduction should be present
            assert!(item.social_security > Decimal::ZERO);
            // US pack should produce labels
            assert!(item.tax_withholding_label.is_some());
            assert!(item.social_security_label.is_some());
        }
    }

    #[test]
    fn test_generate_with_de_country_pack() {
        let mut gen = PayrollGenerator::new(42);
        let employees = test_employees();
        let period_start = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let period_end = NaiveDate::from_ymd_opt(2024, 1, 31).unwrap();
        let pack = de_country_pack();

        let (run, items) = gen.generate_with_country_pack(
            "DE01",
            &employees,
            period_start,
            period_end,
            "EUR",
            &pack,
        );

        assert_eq!(run.company_code, "DE01");
        assert_eq!(items.len(), 3);
        assert_eq!(run.total_net, run.total_gross - run.total_deductions);

        // DE pack should use pension rate 0.093 for retirement
        // and health insurance rate 0.073
        let rates = gen.rates_from_country_pack(&pack);
        assert_eq!(
            rates.retirement_rate,
            Decimal::from_f64_retain(0.093).unwrap()
        );
        assert_eq!(rates.health_rate, Decimal::from_f64_retain(0.073).unwrap());

        // Check DE labels are populated
        let item = &items[0];
        assert_eq!(
            item.health_insurance_label.as_deref(),
            Some("Health Insurance")
        );
        assert_eq!(
            item.retirement_contribution_label.as_deref(),
            Some("Pension Insurance")
        );
        // Employer contribution labels should include both AG-RV and AG-KV
        assert!(item.employer_contribution_label.is_some());
        let ec = item.employer_contribution_label.as_ref().unwrap();
        assert!(ec.contains("Employer Pension Insurance"));
        assert!(ec.contains("Employer Health Insurance"));
    }

    #[test]
    fn test_country_pack_falls_back_to_config_for_missing_categories() {
        // Empty pack: no statutory deductions => all rates fall back to config
        let pack = CountryPack::default();
        let gen = PayrollGenerator::new(42);
        let rates_pack = gen.rates_from_country_pack(&pack);
        let rates_cfg = gen.rates_from_config();

        assert_eq!(rates_pack.income_tax_rate, rates_cfg.income_tax_rate);
        assert_eq!(rates_pack.fica_rate, rates_cfg.fica_rate);
        assert_eq!(rates_pack.health_rate, rates_cfg.health_rate);
        assert_eq!(rates_pack.retirement_rate, rates_cfg.retirement_rate);
    }

    #[test]
    fn test_country_pack_deterministic() {
        let employees = test_employees();
        let period_start = NaiveDate::from_ymd_opt(2024, 3, 1).unwrap();
        let period_end = NaiveDate::from_ymd_opt(2024, 3, 31).unwrap();
        let pack = de_country_pack();

        let mut gen1 = PayrollGenerator::new(42);
        let (run1, items1) = gen1.generate_with_country_pack(
            "DE01",
            &employees,
            period_start,
            period_end,
            "EUR",
            &pack,
        );

        let mut gen2 = PayrollGenerator::new(42);
        let (run2, items2) = gen2.generate_with_country_pack(
            "DE01",
            &employees,
            period_start,
            period_end,
            "EUR",
            &pack,
        );

        assert_eq!(run1.payroll_id, run2.payroll_id);
        assert_eq!(run1.total_gross, run2.total_gross);
        assert_eq!(run1.total_net, run2.total_net);
        for (a, b) in items1.iter().zip(items2.iter()) {
            assert_eq!(a.net_pay, b.net_pay);
        }
    }

    #[test]
    fn test_de_rates_differ_from_default() {
        // With the DE pack, the resolved rates should differ from config defaults
        let gen = PayrollGenerator::new(42);
        let pack = de_country_pack();
        let rates_cfg = gen.rates_from_config();
        let rates_de = gen.rates_from_country_pack(&pack);

        // DE has no non-progressive income tax in pack -> income_tax_rate falls
        // back to config default for federal part.
        // But health (0.073 vs 0.03) and retirement (0.093 vs 0.05) should differ.
        assert_ne!(rates_de.health_rate, rates_cfg.health_rate);
        assert_ne!(rates_de.retirement_rate, rates_cfg.retirement_rate);
    }

    #[test]
    fn test_set_country_pack_uses_labels() {
        let mut gen = PayrollGenerator::new(42);
        let pack = de_country_pack();
        gen.set_country_pack(pack);

        let employees = test_employees();
        let period_start = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let period_end = NaiveDate::from_ymd_opt(2024, 1, 31).unwrap();

        // generate() should now use the stored pack for rates + labels
        let (_run, items) = gen.generate("DE01", &employees, period_start, period_end, "EUR");

        let item = &items[0];
        // Labels should be populated from the DE pack
        assert!(item.tax_withholding_label.is_some());
        assert!(item.health_insurance_label.is_some());
        assert!(item.retirement_contribution_label.is_some());
        assert!(item.employer_contribution_label.is_some());
    }

    #[test]
    fn test_compute_progressive_tax_us_brackets() {
        // Simplified US-style brackets for testing
        let brackets = vec![
            TaxBracket {
                above: Some(0.0),
                up_to: Some(11_000.0),
                rate: 0.10,
            },
            TaxBracket {
                above: Some(11_000.0),
                up_to: Some(44_725.0),
                rate: 0.12,
            },
            TaxBracket {
                above: Some(44_725.0),
                up_to: Some(95_375.0),
                rate: 0.22,
            },
            TaxBracket {
                above: Some(95_375.0),
                up_to: None,
                rate: 0.24,
            },
        ];

        // $60,000 income
        let tax = PayrollGenerator::compute_progressive_tax(Decimal::from(60_000), &brackets);
        // 11,000 * 0.10 = 1,100
        // (44,725 - 11,000) * 0.12 = 4,047
        // (60,000 - 44,725) * 0.22 = 3,360.50
        // Total = 8,507.50
        assert_eq!(tax, Decimal::from_f64_retain(8507.50).unwrap());

        // $11,000 income — only first bracket
        let tax = PayrollGenerator::compute_progressive_tax(Decimal::from(11_000), &brackets);
        assert_eq!(tax, Decimal::from_f64_retain(1100.0).unwrap());
    }

    #[test]
    fn test_progressive_tax_zero_income() {
        let brackets = vec![TaxBracket {
            above: Some(0.0),
            up_to: Some(10_000.0),
            rate: 0.10,
        }];
        let tax = PayrollGenerator::compute_progressive_tax(Decimal::ZERO, &brackets);
        assert_eq!(tax, Decimal::ZERO);
    }

    #[test]
    fn test_us_pack_employees_have_varying_rates() {
        use datasynth_core::country::schema::{
            CountryTaxConfig, PayrollCountryConfig, PayrollDeduction, PayrollTaxBracketsConfig,
        };

        let brackets = vec![
            TaxBracket {
                above: Some(0.0),
                up_to: Some(11_000.0),
                rate: 0.10,
            },
            TaxBracket {
                above: Some(11_000.0),
                up_to: Some(44_725.0),
                rate: 0.12,
            },
            TaxBracket {
                above: Some(44_725.0),
                up_to: None,
                rate: 0.22,
            },
        ];
        let pack = CountryPack {
            country_code: "US".to_string(),
            payroll: PayrollCountryConfig {
                statutory_deductions: vec![
                    PayrollDeduction {
                        code: "FIT".to_string(),
                        name_en: "Federal Income Tax".to_string(),
                        deduction_type: "progressive".to_string(),
                        rate: 0.0,
                        ..Default::default()
                    },
                    PayrollDeduction {
                        code: "FICA".to_string(),
                        name_en: "Social Security".to_string(),
                        deduction_type: "percentage".to_string(),
                        rate: 0.0765,
                        ..Default::default()
                    },
                ],
                ..Default::default()
            },
            tax: CountryTaxConfig {
                payroll_tax: PayrollTaxBracketsConfig {
                    income_tax_brackets: brackets,
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        };

        let mut gen = PayrollGenerator::new(42);
        gen.set_country_pack(pack);

        // Low earner vs high earner
        let low_earner = vec![("LOW".to_string(), Decimal::from(30_000), None, None)];
        let high_earner = vec![("HIGH".to_string(), Decimal::from(200_000), None, None)];

        let start = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let end = NaiveDate::from_ymd_opt(2024, 1, 31).unwrap();

        let (_, low_items) = gen.generate("C001", &low_earner, start, end, "USD");
        let mut gen2 = PayrollGenerator::new(42);
        gen2.set_country_pack(CountryPack {
            country_code: "US".to_string(),
            payroll: PayrollCountryConfig {
                statutory_deductions: vec![
                    PayrollDeduction {
                        code: "FIT".to_string(),
                        name_en: "Federal Income Tax".to_string(),
                        deduction_type: "progressive".to_string(),
                        rate: 0.0,
                        ..Default::default()
                    },
                    PayrollDeduction {
                        code: "FICA".to_string(),
                        name_en: "Social Security".to_string(),
                        deduction_type: "percentage".to_string(),
                        rate: 0.0765,
                        ..Default::default()
                    },
                ],
                ..Default::default()
            },
            tax: CountryTaxConfig {
                payroll_tax: PayrollTaxBracketsConfig {
                    income_tax_brackets: vec![
                        TaxBracket {
                            above: Some(0.0),
                            up_to: Some(11_000.0),
                            rate: 0.10,
                        },
                        TaxBracket {
                            above: Some(11_000.0),
                            up_to: Some(44_725.0),
                            rate: 0.12,
                        },
                        TaxBracket {
                            above: Some(44_725.0),
                            up_to: None,
                            rate: 0.22,
                        },
                    ],
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        });
        let (_, high_items) = gen2.generate("C001", &high_earner, start, end, "USD");

        let low_eff = low_items[0].tax_withholding / low_items[0].gross_pay;
        let high_eff = high_items[0].tax_withholding / high_items[0].gross_pay;

        // High earner should have a higher effective tax rate
        assert!(
            high_eff > low_eff,
            "High earner effective rate ({high_eff}) should exceed low earner ({low_eff})"
        );
    }

    #[test]
    fn test_empty_pack_labels_are_none() {
        let pack = CountryPack::default();
        let labels = PayrollGenerator::labels_from_country_pack(&pack);
        assert!(labels.tax_withholding.is_none());
        assert!(labels.social_security.is_none());
        assert!(labels.health_insurance.is_none());
        assert!(labels.retirement_contribution.is_none());
        assert!(labels.employer_contribution.is_none());
    }

    #[test]
    fn test_us_pack_labels() {
        let pack = us_country_pack();
        let labels = PayrollGenerator::labels_from_country_pack(&pack);
        // FIT is a progressive placeholder but label is still captured
        assert!(labels.tax_withholding.is_some());
        let tw = labels.tax_withholding.unwrap();
        assert!(tw.contains("Federal Income Tax"));
        assert!(tw.contains("State Income Tax"));
        // FICA label
        assert!(labels.social_security.is_some());
        assert!(labels
            .social_security
            .unwrap()
            .contains("Federal Insurance Contributions Act"));
    }
}