stateset-core 0.8.1

Core domain models and business logic for StateSet iCommerce
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
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
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
//! Repository traits for data access abstraction.
//!
//! This module defines the interface for data persistence. Implementations
//! can be SQLite, PostgreSQL, in-memory, etc.
//!
//! # Generic Repository
//!
//! The [`Repository`] trait provides a generic CRUD interface using associated
//! types. Domain-specific traits (e.g. [`OrderRepository`]) extend it with
//! entity-specific operations.
//!
//! # Auto-impl
//!
//! Key traits use [`auto_impl`](https://docs.rs/auto_impl) so that `&T`,
//! `Box<T>`, and `Arc<T>` automatically implement the trait when `T` does.

pub mod async_repository;
pub mod repository;

pub use async_repository::{AsyncRepository, AsyncTransactional};
pub use repository::{Repository, Transactional};

use crate::errors::{BatchResult, Result};
use crate::models::*;
use chrono::{DateTime, Utc};
use stateset_primitives::{
    CartId, CreditId, CustomerId, FraudRuleId, FulfillmentId, GiftCardId, InvoiceId,
    LoyaltyAccountId, LoyaltyProgramId, OrderId, OrderItemId, PaymentId, ProductId, PromotionId,
    PurchaseOrderId, ReturnId, ReviewId, RewardId, SearchConfigId, SegmentId, ShipmentId,
    ShippingMethodId, ShippingZoneId, StoreCreditId, SubscriptionId, WarrantyId, WishlistId,
};
use uuid::Uuid;

/// Order repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait OrderRepository: Send + Sync {
    /// Create a new order
    fn create(&self, input: CreateOrder) -> Result<Order>;

    /// Get order by ID
    fn get(&self, id: OrderId) -> Result<Option<Order>>;

    /// Get order by order number
    fn get_by_number(&self, order_number: &str) -> Result<Option<Order>>;

    /// Update an order
    fn update(&self, id: OrderId, input: UpdateOrder) -> Result<Order>;

    /// List orders with filter
    fn list(&self, filter: OrderFilter) -> Result<Vec<Order>>;

    /// Delete an order
    fn delete(&self, id: OrderId) -> Result<()>;

    /// Add item to order
    fn add_item(&self, order_id: OrderId, item: CreateOrderItem) -> Result<OrderItem>;

    /// Remove item from order
    fn remove_item(&self, order_id: OrderId, item_id: OrderItemId) -> Result<()>;

    /// Count orders matching filter
    fn count(&self, filter: OrderFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple orders - partial success allowed
    fn create_batch(&self, inputs: Vec<CreateOrder>) -> Result<BatchResult<Order>>;

    /// Create multiple orders - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreateOrder>) -> Result<Vec<Order>>;

    /// Update multiple orders - partial success allowed
    fn update_batch(&self, updates: Vec<(OrderId, UpdateOrder)>) -> Result<BatchResult<Order>>;

    /// Update multiple orders - atomic (all-or-nothing)
    fn update_batch_atomic(&self, updates: Vec<(OrderId, UpdateOrder)>) -> Result<Vec<Order>>;

    /// Delete multiple orders - partial success allowed
    fn delete_batch(&self, ids: Vec<OrderId>) -> Result<BatchResult<OrderId>>;

    /// Delete multiple orders - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<OrderId>) -> Result<()>;

    /// Get multiple orders by ID
    fn get_batch(&self, ids: Vec<OrderId>) -> Result<Vec<Order>>;
}

/// Inventory repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait InventoryRepository: Send + Sync {
    /// Create a new inventory item
    fn create_item(&self, input: CreateInventoryItem) -> Result<InventoryItem>;

    /// Get inventory item by ID
    fn get_item(&self, id: i64) -> Result<Option<InventoryItem>>;

    /// Get inventory item by SKU
    fn get_item_by_sku(&self, sku: &str) -> Result<Option<InventoryItem>>;

    /// Get stock level for SKU (aggregated across locations)
    fn get_stock(&self, sku: &str) -> Result<Option<StockLevel>>;

    /// Get balance at specific location
    fn get_balance(&self, item_id: i64, location_id: i32) -> Result<Option<InventoryBalance>>;

    /// Adjust inventory quantity
    fn adjust(&self, input: AdjustInventory) -> Result<InventoryTransaction>;

    /// Reserve inventory
    fn reserve(&self, input: ReserveInventory) -> Result<InventoryReservation>;

    /// Get a reservation by ID
    fn get_reservation(&self, reservation_id: Uuid) -> Result<Option<InventoryReservation>>;

    /// Release reservation
    fn release_reservation(&self, reservation_id: Uuid) -> Result<()>;

    /// Confirm reservation (convert to allocation)
    fn confirm_reservation(&self, reservation_id: Uuid) -> Result<()>;

    /// List reservations by reference (e.g., order id)
    fn list_reservations_by_reference(
        &self,
        reference_type: &str,
        reference_id: &str,
    ) -> Result<Vec<InventoryReservation>>;

    /// List inventory items with filter
    fn list(&self, filter: InventoryFilter) -> Result<Vec<InventoryItem>>;

    /// Get items below reorder point
    fn get_reorder_needed(&self) -> Result<Vec<StockLevel>>;

    /// Record transaction
    fn record_transaction(&self, transaction: InventoryTransaction)
    -> Result<InventoryTransaction>;

    /// Get transaction history
    fn get_transactions(&self, item_id: i64, limit: u32) -> Result<Vec<InventoryTransaction>>;

    // === Batch Operations ===

    /// Create multiple inventory items - partial success allowed
    fn create_item_batch(
        &self,
        inputs: Vec<CreateInventoryItem>,
    ) -> Result<BatchResult<InventoryItem>>;

    /// Create multiple inventory items - atomic (all-or-nothing)
    fn create_item_batch_atomic(
        &self,
        inputs: Vec<CreateInventoryItem>,
    ) -> Result<Vec<InventoryItem>>;

    /// Adjust multiple inventory quantities - partial success allowed
    fn adjust_batch(
        &self,
        adjustments: Vec<AdjustInventory>,
    ) -> Result<BatchResult<InventoryTransaction>>;

    /// Adjust multiple inventory quantities - atomic (all-or-nothing)
    fn adjust_batch_atomic(
        &self,
        adjustments: Vec<AdjustInventory>,
    ) -> Result<Vec<InventoryTransaction>>;

    /// Get multiple inventory items by ID
    fn get_item_batch(&self, ids: Vec<i64>) -> Result<Vec<InventoryItem>>;

    /// Get stock levels for multiple SKUs
    fn get_stock_batch(&self, skus: Vec<String>) -> Result<Vec<StockLevel>>;
}

/// Customer repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait CustomerRepository: Send + Sync {
    /// Create a new customer
    fn create(&self, input: CreateCustomer) -> Result<Customer>;

    /// Get customer by ID
    fn get(&self, id: CustomerId) -> Result<Option<Customer>>;

    /// Get customer by email
    fn get_by_email(&self, email: &str) -> Result<Option<Customer>>;

    /// Update a customer
    fn update(&self, id: CustomerId, input: UpdateCustomer) -> Result<Customer>;

    /// List customers with filter
    fn list(&self, filter: CustomerFilter) -> Result<Vec<Customer>>;

    /// Delete a customer (soft delete)
    fn delete(&self, id: CustomerId) -> Result<()>;

    /// Add address for customer
    fn add_address(&self, input: CreateCustomerAddress) -> Result<CustomerAddress>;

    /// Get customer addresses
    fn get_addresses(&self, customer_id: CustomerId) -> Result<Vec<CustomerAddress>>;

    /// Update address
    fn update_address(
        &self,
        address_id: Uuid,
        input: CreateCustomerAddress,
    ) -> Result<CustomerAddress>;

    /// Delete address
    fn delete_address(&self, address_id: Uuid) -> Result<()>;

    /// Set default address
    fn set_default_address(
        &self,
        customer_id: CustomerId,
        address_id: Uuid,
        address_type: AddressType,
    ) -> Result<()>;

    /// Count customers matching filter
    fn count(&self, filter: CustomerFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple customers - partial success allowed
    fn create_batch(&self, inputs: Vec<CreateCustomer>) -> Result<BatchResult<Customer>>;

    /// Create multiple customers - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreateCustomer>) -> Result<Vec<Customer>>;

    /// Update multiple customers - partial success allowed
    fn update_batch(
        &self,
        updates: Vec<(CustomerId, UpdateCustomer)>,
    ) -> Result<BatchResult<Customer>>;

    /// Update multiple customers - atomic (all-or-nothing)
    fn update_batch_atomic(
        &self,
        updates: Vec<(CustomerId, UpdateCustomer)>,
    ) -> Result<Vec<Customer>>;

    /// Delete multiple customers - partial success allowed
    fn delete_batch(&self, ids: Vec<CustomerId>) -> Result<BatchResult<CustomerId>>;

    /// Delete multiple customers - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<CustomerId>) -> Result<()>;

    /// Get multiple customers by ID
    fn get_batch(&self, ids: Vec<CustomerId>) -> Result<Vec<Customer>>;
}

/// Product repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait ProductRepository: Send + Sync {
    /// Create a new product
    fn create(&self, input: CreateProduct) -> Result<Product>;

    /// Get product by ID
    fn get(&self, id: ProductId) -> Result<Option<Product>>;

    /// Get product by slug
    fn get_by_slug(&self, slug: &str) -> Result<Option<Product>>;

    /// Update a product
    fn update(&self, id: ProductId, input: UpdateProduct) -> Result<Product>;

    /// List products with filter
    fn list(&self, filter: ProductFilter) -> Result<Vec<Product>>;

    /// Delete a product (archive)
    fn delete(&self, id: ProductId) -> Result<()>;

    /// Add variant to product
    fn add_variant(
        &self,
        product_id: ProductId,
        variant: CreateProductVariant,
    ) -> Result<ProductVariant>;

    /// Get variant by ID
    fn get_variant(&self, id: Uuid) -> Result<Option<ProductVariant>>;

    /// Get variant by SKU
    fn get_variant_by_sku(&self, sku: &str) -> Result<Option<ProductVariant>>;

    /// Update variant
    fn update_variant(&self, id: Uuid, variant: CreateProductVariant) -> Result<ProductVariant>;

    /// Delete variant
    fn delete_variant(&self, id: Uuid) -> Result<()>;

    /// Get all variants for product
    fn get_variants(&self, product_id: ProductId) -> Result<Vec<ProductVariant>>;

    /// Count products matching filter
    fn count(&self, filter: ProductFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple products - partial success allowed
    fn create_batch(&self, inputs: Vec<CreateProduct>) -> Result<BatchResult<Product>>;

    /// Create multiple products - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreateProduct>) -> Result<Vec<Product>>;

    /// Update multiple products - partial success allowed
    fn update_batch(
        &self,
        updates: Vec<(ProductId, UpdateProduct)>,
    ) -> Result<BatchResult<Product>>;

    /// Update multiple products - atomic (all-or-nothing)
    fn update_batch_atomic(&self, updates: Vec<(ProductId, UpdateProduct)>)
    -> Result<Vec<Product>>;

    /// Delete multiple products - partial success allowed
    fn delete_batch(&self, ids: Vec<ProductId>) -> Result<BatchResult<ProductId>>;

    /// Delete multiple products - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<ProductId>) -> Result<()>;

    /// Get multiple products by ID
    fn get_batch(&self, ids: Vec<ProductId>) -> Result<Vec<Product>>;
}

/// Return repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait ReturnRepository: Send + Sync {
    /// Create a new return
    fn create(&self, input: CreateReturn) -> Result<Return>;

    /// Get return by ID
    fn get(&self, id: ReturnId) -> Result<Option<Return>>;

    /// Update a return
    fn update(&self, id: ReturnId, input: UpdateReturn) -> Result<Return>;

    /// List returns with filter
    fn list(&self, filter: ReturnFilter) -> Result<Vec<Return>>;

    /// Approve a return
    fn approve(&self, id: ReturnId) -> Result<Return>;

    /// Reject a return
    fn reject(&self, id: ReturnId, reason: &str) -> Result<Return>;

    /// Complete a return
    fn complete(&self, id: ReturnId) -> Result<Return>;

    /// Cancel a return
    fn cancel(&self, id: ReturnId) -> Result<Return>;

    /// Count returns matching filter
    fn count(&self, filter: ReturnFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple returns - partial success allowed
    fn create_batch(&self, inputs: Vec<CreateReturn>) -> Result<BatchResult<Return>>;

    /// Create multiple returns - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreateReturn>) -> Result<Vec<Return>>;

    /// Update multiple returns - partial success allowed
    fn update_batch(&self, updates: Vec<(ReturnId, UpdateReturn)>) -> Result<BatchResult<Return>>;

    /// Update multiple returns - atomic (all-or-nothing)
    fn update_batch_atomic(&self, updates: Vec<(ReturnId, UpdateReturn)>) -> Result<Vec<Return>>;

    /// Delete multiple returns - partial success allowed
    fn delete_batch(&self, ids: Vec<ReturnId>) -> Result<BatchResult<Uuid>>;

    /// Delete multiple returns - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<ReturnId>) -> Result<()>;

    /// Get multiple returns by ID
    fn get_batch(&self, ids: Vec<ReturnId>) -> Result<Vec<Return>>;
}

/// Event handler trait for domain events
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait EventHandler: Send + Sync {
    /// Handle a commerce event
    fn handle(&self, event: &crate::events::CommerceEvent) -> Result<()>;
}

/// Bill of Materials repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait BomRepository: Send + Sync {
    /// Create a new BOM
    fn create(&self, input: CreateBom) -> Result<BillOfMaterials>;

    /// Get BOM by ID
    fn get(&self, id: Uuid) -> Result<Option<BillOfMaterials>>;

    /// Get BOM by BOM number
    fn get_by_number(&self, bom_number: &str) -> Result<Option<BillOfMaterials>>;

    /// Update a BOM
    fn update(&self, id: Uuid, input: UpdateBom) -> Result<BillOfMaterials>;

    /// List BOMs with filter
    fn list(&self, filter: BomFilter) -> Result<Vec<BillOfMaterials>>;

    /// Delete a BOM (marks as obsolete)
    fn delete(&self, id: Uuid) -> Result<()>;

    /// Add component to BOM
    fn add_component(&self, bom_id: Uuid, component: CreateBomComponent) -> Result<BomComponent>;

    /// Update a BOM component
    fn update_component(
        &self,
        component_id: Uuid,
        component: CreateBomComponent,
    ) -> Result<BomComponent>;

    /// Remove component from BOM
    fn remove_component(&self, component_id: Uuid) -> Result<()>;

    /// Get all components for a BOM
    fn get_components(&self, bom_id: Uuid) -> Result<Vec<BomComponent>>;

    /// Activate a BOM (make it ready for production use)
    fn activate(&self, id: Uuid) -> Result<BillOfMaterials>;

    /// Count BOMs matching filter
    fn count(&self, filter: BomFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple BOMs - partial success allowed
    fn create_batch(&self, inputs: Vec<CreateBom>) -> Result<BatchResult<BillOfMaterials>>;

    /// Create multiple BOMs - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreateBom>) -> Result<Vec<BillOfMaterials>>;

    /// Update multiple BOMs - partial success allowed
    fn update_batch(&self, updates: Vec<(Uuid, UpdateBom)>)
    -> Result<BatchResult<BillOfMaterials>>;

    /// Update multiple BOMs - atomic (all-or-nothing)
    fn update_batch_atomic(&self, updates: Vec<(Uuid, UpdateBom)>) -> Result<Vec<BillOfMaterials>>;

    /// Delete multiple BOMs - partial success allowed
    fn delete_batch(&self, ids: Vec<Uuid>) -> Result<BatchResult<Uuid>>;

    /// Delete multiple BOMs - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<Uuid>) -> Result<()>;

    /// Get multiple BOMs by ID
    fn get_batch(&self, ids: Vec<Uuid>) -> Result<Vec<BillOfMaterials>>;
}

/// Work Order repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait WorkOrderRepository: Send + Sync {
    /// Create a new work order
    fn create(&self, input: CreateWorkOrder) -> Result<WorkOrder>;

    /// Get work order by ID
    fn get(&self, id: Uuid) -> Result<Option<WorkOrder>>;

    /// Get work order by work order number
    fn get_by_number(&self, work_order_number: &str) -> Result<Option<WorkOrder>>;

    /// Update a work order
    fn update(&self, id: Uuid, input: UpdateWorkOrder) -> Result<WorkOrder>;

    /// List work orders with filter
    fn list(&self, filter: WorkOrderFilter) -> Result<Vec<WorkOrder>>;

    /// Delete a work order (cancels if not started)
    fn delete(&self, id: Uuid) -> Result<()>;

    /// Start a work order (transitions from planned to `in_progress`)
    fn start(&self, id: Uuid) -> Result<WorkOrder>;

    /// Complete a work order
    fn complete(&self, id: Uuid, quantity_completed: rust_decimal::Decimal) -> Result<WorkOrder>;

    /// Put work order on hold
    fn hold(&self, id: Uuid) -> Result<WorkOrder>;

    /// Resume a held work order
    fn resume(&self, id: Uuid) -> Result<WorkOrder>;

    /// Cancel a work order
    fn cancel(&self, id: Uuid) -> Result<WorkOrder>;

    // Task operations
    /// Add task to work order
    fn add_task(&self, work_order_id: Uuid, task: CreateWorkOrderTask) -> Result<WorkOrderTask>;

    /// Update a task
    fn update_task(&self, task_id: Uuid, task: UpdateWorkOrderTask) -> Result<WorkOrderTask>;

    /// Remove task from work order
    fn remove_task(&self, task_id: Uuid) -> Result<()>;

    /// Get tasks for work order
    fn get_tasks(&self, work_order_id: Uuid) -> Result<Vec<WorkOrderTask>>;

    /// Start a task
    fn start_task(&self, task_id: Uuid) -> Result<WorkOrderTask>;

    /// Complete a task
    fn complete_task(
        &self,
        task_id: Uuid,
        actual_hours: Option<rust_decimal::Decimal>,
    ) -> Result<WorkOrderTask>;

    // Material operations
    /// Add material to work order
    fn add_material(
        &self,
        work_order_id: Uuid,
        material: AddWorkOrderMaterial,
    ) -> Result<WorkOrderMaterial>;

    /// Consume material
    fn consume_material(
        &self,
        material_id: Uuid,
        quantity: rust_decimal::Decimal,
    ) -> Result<WorkOrderMaterial>;

    /// Get materials for work order
    fn get_materials(&self, work_order_id: Uuid) -> Result<Vec<WorkOrderMaterial>>;

    /// Count work orders matching filter
    fn count(&self, filter: WorkOrderFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple work orders - partial success allowed
    fn create_batch(&self, inputs: Vec<CreateWorkOrder>) -> Result<BatchResult<WorkOrder>>;

    /// Create multiple work orders - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreateWorkOrder>) -> Result<Vec<WorkOrder>>;

    /// Update multiple work orders - partial success allowed
    fn update_batch(&self, updates: Vec<(Uuid, UpdateWorkOrder)>)
    -> Result<BatchResult<WorkOrder>>;

    /// Update multiple work orders - atomic (all-or-nothing)
    fn update_batch_atomic(&self, updates: Vec<(Uuid, UpdateWorkOrder)>) -> Result<Vec<WorkOrder>>;

    /// Delete multiple work orders - partial success allowed
    fn delete_batch(&self, ids: Vec<Uuid>) -> Result<BatchResult<Uuid>>;

    /// Delete multiple work orders - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<Uuid>) -> Result<()>;

    /// Get multiple work orders by ID
    fn get_batch(&self, ids: Vec<Uuid>) -> Result<Vec<WorkOrder>>;
}

/// Shipment repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait ShipmentRepository: Send + Sync {
    /// Create a new shipment
    fn create(&self, input: CreateShipment) -> Result<Shipment>;

    /// Get shipment by ID
    fn get(&self, id: ShipmentId) -> Result<Option<Shipment>>;

    /// Get shipment by shipment number
    fn get_by_number(&self, shipment_number: &str) -> Result<Option<Shipment>>;

    /// Get shipment by tracking number
    fn get_by_tracking(&self, tracking_number: &str) -> Result<Option<Shipment>>;

    /// Update a shipment
    fn update(&self, id: ShipmentId, input: UpdateShipment) -> Result<Shipment>;

    /// List shipments with filter
    fn list(&self, filter: ShipmentFilter) -> Result<Vec<Shipment>>;

    /// Get shipments for an order
    fn for_order(&self, order_id: OrderId) -> Result<Vec<Shipment>>;

    /// Delete a shipment (cancel if not shipped)
    fn delete(&self, id: ShipmentId) -> Result<()>;

    // Status transitions
    /// Mark shipment as processing
    fn mark_processing(&self, id: ShipmentId) -> Result<Shipment>;

    /// Mark shipment as ready to ship
    fn mark_ready(&self, id: ShipmentId) -> Result<Shipment>;

    /// Mark shipment as shipped with tracking number
    fn ship(&self, id: ShipmentId, tracking_number: Option<String>) -> Result<Shipment>;

    /// Mark shipment as in transit
    fn mark_in_transit(&self, id: ShipmentId) -> Result<Shipment>;

    /// Mark shipment as out for delivery
    fn mark_out_for_delivery(&self, id: ShipmentId) -> Result<Shipment>;

    /// Mark shipment as delivered
    fn mark_delivered(&self, id: ShipmentId) -> Result<Shipment>;

    /// Mark shipment as failed delivery
    fn mark_failed(&self, id: ShipmentId) -> Result<Shipment>;

    /// Put shipment on hold
    fn hold(&self, id: ShipmentId) -> Result<Shipment>;

    /// Cancel shipment
    fn cancel(&self, id: ShipmentId) -> Result<Shipment>;

    // Item operations
    /// Add item to shipment
    fn add_item(&self, shipment_id: ShipmentId, item: CreateShipmentItem) -> Result<ShipmentItem>;

    /// Remove item from shipment
    fn remove_item(&self, item_id: Uuid) -> Result<()>;

    /// Get items in shipment
    fn get_items(&self, shipment_id: ShipmentId) -> Result<Vec<ShipmentItem>>;

    // Event/tracking operations
    /// Add tracking event
    fn add_event(&self, shipment_id: ShipmentId, event: AddShipmentEvent) -> Result<ShipmentEvent>;

    /// Get tracking events for shipment
    fn get_events(&self, shipment_id: ShipmentId) -> Result<Vec<ShipmentEvent>>;

    /// Count shipments matching filter
    fn count(&self, filter: ShipmentFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple shipments - partial success allowed
    fn create_batch(&self, inputs: Vec<CreateShipment>) -> Result<BatchResult<Shipment>>;

    /// Create multiple shipments - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreateShipment>) -> Result<Vec<Shipment>>;

    /// Update multiple shipments - partial success allowed
    fn update_batch(
        &self,
        updates: Vec<(ShipmentId, UpdateShipment)>,
    ) -> Result<BatchResult<Shipment>>;

    /// Update multiple shipments - atomic (all-or-nothing)
    fn update_batch_atomic(
        &self,
        updates: Vec<(ShipmentId, UpdateShipment)>,
    ) -> Result<Vec<Shipment>>;

    /// Delete multiple shipments - partial success allowed
    fn delete_batch(&self, ids: Vec<ShipmentId>) -> Result<BatchResult<Uuid>>;

    /// Delete multiple shipments - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<ShipmentId>) -> Result<()>;

    /// Get multiple shipments by ID
    fn get_batch(&self, ids: Vec<ShipmentId>) -> Result<Vec<Shipment>>;
}

/// Payment repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait PaymentRepository: Send + Sync {
    /// Create a new payment
    fn create(&self, input: CreatePayment) -> Result<Payment>;

    /// Get payment by ID
    fn get(&self, id: PaymentId) -> Result<Option<Payment>>;

    /// Get payment by payment number
    fn get_by_number(&self, payment_number: &str) -> Result<Option<Payment>>;

    /// Get payment by external ID (e.g., Stripe payment intent)
    fn get_by_external_id(&self, external_id: &str) -> Result<Option<Payment>>;

    /// Update a payment
    fn update(&self, id: PaymentId, input: UpdatePayment) -> Result<Payment>;

    /// List payments with filter
    fn list(&self, filter: PaymentFilter) -> Result<Vec<Payment>>;

    /// Get payments for an order
    fn for_order(&self, order_id: OrderId) -> Result<Vec<Payment>>;

    /// Get payments for an invoice
    fn for_invoice(&self, invoice_id: InvoiceId) -> Result<Vec<Payment>>;

    // Status transitions
    /// Mark payment as processing
    fn mark_processing(&self, id: PaymentId) -> Result<Payment>;

    /// Mark payment as completed (paid)
    fn mark_completed(&self, id: PaymentId) -> Result<Payment>;

    /// Mark payment as failed
    fn mark_failed(&self, id: PaymentId, reason: &str, code: Option<&str>) -> Result<Payment>;

    /// Cancel payment
    fn cancel(&self, id: PaymentId) -> Result<Payment>;

    // Refund operations
    /// Create a refund for a payment
    fn create_refund(&self, input: CreateRefund) -> Result<Refund>;

    /// Get refund by ID
    fn get_refund(&self, id: Uuid) -> Result<Option<Refund>>;

    /// Get refunds for a payment
    fn get_refunds(&self, payment_id: PaymentId) -> Result<Vec<Refund>>;

    /// Process refund (mark as completed)
    fn complete_refund(&self, id: Uuid) -> Result<Refund>;

    /// Fail refund
    fn fail_refund(&self, id: Uuid, reason: &str) -> Result<Refund>;

    // Payment method operations
    /// Create a payment method for a customer
    fn create_payment_method(&self, input: CreatePaymentMethod) -> Result<PaymentMethod>;

    /// Get payment methods for a customer
    fn get_payment_methods(&self, customer_id: CustomerId) -> Result<Vec<PaymentMethod>>;

    /// Delete a payment method
    fn delete_payment_method(&self, id: Uuid) -> Result<()>;

    /// Set default payment method
    fn set_default_payment_method(&self, customer_id: CustomerId, method_id: Uuid) -> Result<()>;

    /// Count payments matching filter
    fn count(&self, filter: PaymentFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple payments - partial success allowed
    fn create_batch(&self, inputs: Vec<CreatePayment>) -> Result<BatchResult<Payment>>;

    /// Create multiple payments - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreatePayment>) -> Result<Vec<Payment>>;

    /// Update multiple payments - partial success allowed
    fn update_batch(
        &self,
        updates: Vec<(PaymentId, UpdatePayment)>,
    ) -> Result<BatchResult<Payment>>;

    /// Update multiple payments - atomic (all-or-nothing)
    fn update_batch_atomic(&self, updates: Vec<(PaymentId, UpdatePayment)>)
    -> Result<Vec<Payment>>;

    /// Delete multiple payments - partial success allowed
    fn delete_batch(&self, ids: Vec<PaymentId>) -> Result<BatchResult<Uuid>>;

    /// Delete multiple payments - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<PaymentId>) -> Result<()>;

    /// Get multiple payments by ID
    fn get_batch(&self, ids: Vec<PaymentId>) -> Result<Vec<Payment>>;
}

/// Warranty repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait WarrantyRepository: Send + Sync {
    /// Create a new warranty
    fn create(&self, input: CreateWarranty) -> Result<Warranty>;

    /// Get warranty by ID
    fn get(&self, id: WarrantyId) -> Result<Option<Warranty>>;

    /// Get warranty by warranty number
    fn get_by_number(&self, warranty_number: &str) -> Result<Option<Warranty>>;

    /// Get warranty by serial number
    fn get_by_serial(&self, serial_number: &str) -> Result<Option<Warranty>>;

    /// Update a warranty
    fn update(&self, id: WarrantyId, input: UpdateWarranty) -> Result<Warranty>;

    /// List warranties with filter
    fn list(&self, filter: WarrantyFilter) -> Result<Vec<Warranty>>;

    /// Get warranties for a customer
    fn for_customer(&self, customer_id: CustomerId) -> Result<Vec<Warranty>>;

    /// Get warranties for an order
    fn for_order(&self, order_id: OrderId) -> Result<Vec<Warranty>>;

    // Status transitions
    /// Void a warranty
    fn void(&self, id: WarrantyId) -> Result<Warranty>;

    /// Expire a warranty
    fn expire(&self, id: WarrantyId) -> Result<Warranty>;

    /// Transfer warranty to new owner
    fn transfer(&self, id: WarrantyId, new_customer_id: CustomerId) -> Result<Warranty>;

    // Claim operations
    /// Create a warranty claim
    fn create_claim(&self, input: CreateWarrantyClaim) -> Result<WarrantyClaim>;

    /// Get claim by ID
    fn get_claim(&self, id: Uuid) -> Result<Option<WarrantyClaim>>;

    /// Get claim by claim number
    fn get_claim_by_number(&self, claim_number: &str) -> Result<Option<WarrantyClaim>>;

    /// Update a claim
    fn update_claim(&self, id: Uuid, input: UpdateWarrantyClaim) -> Result<WarrantyClaim>;

    /// List claims with filter
    fn list_claims(&self, filter: WarrantyClaimFilter) -> Result<Vec<WarrantyClaim>>;

    /// Get claims for a warranty
    fn get_claims(&self, warranty_id: WarrantyId) -> Result<Vec<WarrantyClaim>>;

    // Claim status transitions
    /// Approve a claim
    fn approve_claim(&self, id: Uuid) -> Result<WarrantyClaim>;

    /// Deny a claim
    fn deny_claim(&self, id: Uuid, reason: &str) -> Result<WarrantyClaim>;

    /// Complete a claim
    fn complete_claim(&self, id: Uuid, resolution: ClaimResolution) -> Result<WarrantyClaim>;

    /// Cancel a claim
    fn cancel_claim(&self, id: Uuid) -> Result<WarrantyClaim>;

    /// Count warranties matching filter
    fn count(&self, filter: WarrantyFilter) -> Result<u64>;

    /// Count claims matching filter
    fn count_claims(&self, filter: WarrantyClaimFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple warranties - partial success allowed
    fn create_batch(&self, inputs: Vec<CreateWarranty>) -> Result<BatchResult<Warranty>>;

    /// Create multiple warranties - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreateWarranty>) -> Result<Vec<Warranty>>;

    /// Update multiple warranties - partial success allowed
    fn update_batch(
        &self,
        updates: Vec<(WarrantyId, UpdateWarranty)>,
    ) -> Result<BatchResult<Warranty>>;

    /// Update multiple warranties - atomic (all-or-nothing)
    fn update_batch_atomic(
        &self,
        updates: Vec<(WarrantyId, UpdateWarranty)>,
    ) -> Result<Vec<Warranty>>;

    /// Delete multiple warranties - partial success allowed
    fn delete_batch(&self, ids: Vec<WarrantyId>) -> Result<BatchResult<Uuid>>;

    /// Delete multiple warranties - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<WarrantyId>) -> Result<()>;

    /// Get multiple warranties by ID
    fn get_batch(&self, ids: Vec<WarrantyId>) -> Result<Vec<Warranty>>;
}

/// Purchase Order repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait PurchaseOrderRepository: Send + Sync {
    // Supplier operations
    /// Create a new supplier
    fn create_supplier(&self, input: CreateSupplier) -> Result<Supplier>;

    /// Get supplier by ID
    fn get_supplier(&self, id: Uuid) -> Result<Option<Supplier>>;

    /// Get supplier by code
    fn get_supplier_by_code(&self, code: &str) -> Result<Option<Supplier>>;

    /// Update a supplier
    fn update_supplier(&self, id: Uuid, input: UpdateSupplier) -> Result<Supplier>;

    /// List suppliers with filter
    fn list_suppliers(&self, filter: SupplierFilter) -> Result<Vec<Supplier>>;

    /// Delete supplier (deactivate)
    fn delete_supplier(&self, id: Uuid) -> Result<()>;

    // Purchase Order operations
    /// Create a new purchase order
    fn create(&self, input: CreatePurchaseOrder) -> Result<PurchaseOrder>;

    /// Get purchase order by ID
    fn get(&self, id: PurchaseOrderId) -> Result<Option<PurchaseOrder>>;

    /// Get purchase order by PO number
    fn get_by_number(&self, po_number: &str) -> Result<Option<PurchaseOrder>>;

    /// Update a purchase order
    fn update(&self, id: PurchaseOrderId, input: UpdatePurchaseOrder) -> Result<PurchaseOrder>;

    /// List purchase orders with filter
    fn list(&self, filter: PurchaseOrderFilter) -> Result<Vec<PurchaseOrder>>;

    /// Get purchase orders for a supplier
    fn for_supplier(&self, supplier_id: Uuid) -> Result<Vec<PurchaseOrder>>;

    /// Delete a purchase order (only if draft)
    fn delete(&self, id: PurchaseOrderId) -> Result<()>;

    // Status transitions
    /// Submit for approval
    fn submit_for_approval(&self, id: PurchaseOrderId) -> Result<PurchaseOrder>;

    /// Approve purchase order
    fn approve(&self, id: PurchaseOrderId, approved_by: &str) -> Result<PurchaseOrder>;

    /// Send to supplier
    fn send(&self, id: PurchaseOrderId) -> Result<PurchaseOrder>;

    /// Mark as acknowledged by supplier
    fn acknowledge(
        &self,
        id: PurchaseOrderId,
        supplier_reference: Option<&str>,
    ) -> Result<PurchaseOrder>;

    /// Put on hold
    fn hold(&self, id: PurchaseOrderId) -> Result<PurchaseOrder>;

    /// Cancel purchase order
    fn cancel(&self, id: PurchaseOrderId) -> Result<PurchaseOrder>;

    /// Receive items on a purchase order
    fn receive(
        &self,
        id: PurchaseOrderId,
        items: ReceivePurchaseOrderItems,
    ) -> Result<PurchaseOrder>;

    /// Complete/close purchase order
    fn complete(&self, id: PurchaseOrderId) -> Result<PurchaseOrder>;

    // Item operations
    /// Add item to purchase order
    fn add_item(
        &self,
        po_id: PurchaseOrderId,
        item: CreatePurchaseOrderItem,
    ) -> Result<PurchaseOrderItem>;

    /// Update a PO item
    fn update_item(
        &self,
        item_id: Uuid,
        item: CreatePurchaseOrderItem,
    ) -> Result<PurchaseOrderItem>;

    /// Remove item from purchase order
    fn remove_item(&self, item_id: Uuid) -> Result<()>;

    /// Get items for purchase order
    fn get_items(&self, po_id: PurchaseOrderId) -> Result<Vec<PurchaseOrderItem>>;

    /// Count purchase orders matching filter
    fn count(&self, filter: PurchaseOrderFilter) -> Result<u64>;

    /// Count suppliers matching filter
    fn count_suppliers(&self, filter: SupplierFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple purchase orders - partial success allowed
    fn create_batch(&self, inputs: Vec<CreatePurchaseOrder>) -> Result<BatchResult<PurchaseOrder>>;

    /// Create multiple purchase orders - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreatePurchaseOrder>) -> Result<Vec<PurchaseOrder>>;

    /// Update multiple purchase orders - partial success allowed
    fn update_batch(
        &self,
        updates: Vec<(PurchaseOrderId, UpdatePurchaseOrder)>,
    ) -> Result<BatchResult<PurchaseOrder>>;

    /// Update multiple purchase orders - atomic (all-or-nothing)
    fn update_batch_atomic(
        &self,
        updates: Vec<(PurchaseOrderId, UpdatePurchaseOrder)>,
    ) -> Result<Vec<PurchaseOrder>>;

    /// Delete multiple purchase orders - partial success allowed
    fn delete_batch(&self, ids: Vec<PurchaseOrderId>) -> Result<BatchResult<PurchaseOrderId>>;

    /// Delete multiple purchase orders - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<PurchaseOrderId>) -> Result<()>;

    /// Get multiple purchase orders by ID
    fn get_batch(&self, ids: Vec<PurchaseOrderId>) -> Result<Vec<PurchaseOrder>>;
}

/// Invoice repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait InvoiceRepository: Send + Sync {
    /// Create a new invoice
    fn create(&self, input: CreateInvoice) -> Result<Invoice>;

    /// Get invoice by ID
    fn get(&self, id: InvoiceId) -> Result<Option<Invoice>>;

    /// Get invoice by invoice number
    fn get_by_number(&self, invoice_number: &str) -> Result<Option<Invoice>>;

    /// Update an invoice
    fn update(&self, id: InvoiceId, input: UpdateInvoice) -> Result<Invoice>;

    /// List invoices with filter
    fn list(&self, filter: InvoiceFilter) -> Result<Vec<Invoice>>;

    /// Get invoices for a customer
    fn for_customer(&self, customer_id: CustomerId) -> Result<Vec<Invoice>>;

    /// Get invoices for an order
    fn for_order(&self, order_id: OrderId) -> Result<Vec<Invoice>>;

    /// Delete an invoice (only if draft)
    fn delete(&self, id: InvoiceId) -> Result<()>;

    // Status transitions
    /// Send invoice to customer
    fn send(&self, id: InvoiceId) -> Result<Invoice>;

    /// Mark invoice as viewed
    fn mark_viewed(&self, id: InvoiceId) -> Result<Invoice>;

    /// Record a payment on the invoice
    fn record_payment(&self, id: InvoiceId, payment: RecordInvoicePayment) -> Result<Invoice>;

    /// Void an invoice
    fn void(&self, id: InvoiceId) -> Result<Invoice>;

    /// Write off an invoice as uncollectible
    fn write_off(&self, id: InvoiceId) -> Result<Invoice>;

    /// Mark invoice as disputed
    fn dispute(&self, id: InvoiceId) -> Result<Invoice>;

    // Item operations
    /// Add item to invoice
    fn add_item(&self, invoice_id: InvoiceId, item: CreateInvoiceItem) -> Result<InvoiceItem>;

    /// Update an invoice item
    fn update_item(&self, item_id: Uuid, item: CreateInvoiceItem) -> Result<InvoiceItem>;

    /// Remove item from invoice
    fn remove_item(&self, item_id: Uuid) -> Result<()>;

    /// Get items for invoice
    fn get_items(&self, invoice_id: InvoiceId) -> Result<Vec<InvoiceItem>>;

    /// Recalculate invoice totals
    fn recalculate(&self, id: InvoiceId) -> Result<Invoice>;

    /// Get overdue invoices
    fn get_overdue(&self) -> Result<Vec<Invoice>>;

    /// Count invoices matching filter
    fn count(&self, filter: InvoiceFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple invoices - partial success allowed
    fn create_batch(&self, inputs: Vec<CreateInvoice>) -> Result<BatchResult<Invoice>>;

    /// Create multiple invoices - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreateInvoice>) -> Result<Vec<Invoice>>;

    /// Update multiple invoices - partial success allowed
    fn update_batch(
        &self,
        updates: Vec<(InvoiceId, UpdateInvoice)>,
    ) -> Result<BatchResult<Invoice>>;

    /// Update multiple invoices - atomic (all-or-nothing)
    fn update_batch_atomic(&self, updates: Vec<(InvoiceId, UpdateInvoice)>)
    -> Result<Vec<Invoice>>;

    /// Delete multiple invoices - partial success allowed
    fn delete_batch(&self, ids: Vec<InvoiceId>) -> Result<BatchResult<Uuid>>;

    /// Delete multiple invoices - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<InvoiceId>) -> Result<()>;

    /// Get multiple invoices by ID
    fn get_batch(&self, ids: Vec<InvoiceId>) -> Result<Vec<Invoice>>;
}

/// Cart/Checkout repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait CartRepository: Send + Sync {
    /// Create a new cart/checkout session
    fn create(&self, input: CreateCart) -> Result<Cart>;

    /// Get cart by ID
    fn get(&self, id: CartId) -> Result<Option<Cart>>;

    /// Get cart by cart number
    fn get_by_number(&self, cart_number: &str) -> Result<Option<Cart>>;

    /// Update a cart
    fn update(&self, id: CartId, input: UpdateCart) -> Result<Cart>;

    /// List carts with filter
    fn list(&self, filter: CartFilter) -> Result<Vec<Cart>>;

    /// Get carts for a customer
    fn for_customer(&self, customer_id: CustomerId) -> Result<Vec<Cart>>;

    /// Delete a cart (or mark as cancelled)
    fn delete(&self, id: CartId) -> Result<()>;

    // Item operations
    /// Add item to cart
    fn add_item(&self, cart_id: CartId, item: AddCartItem) -> Result<CartItem>;

    /// Update a cart item (quantity, etc)
    fn update_item(&self, item_id: Uuid, input: UpdateCartItem) -> Result<CartItem>;

    /// Remove item from cart
    fn remove_item(&self, item_id: Uuid) -> Result<()>;

    /// Get items for a cart
    fn get_items(&self, cart_id: CartId) -> Result<Vec<CartItem>>;

    /// Clear all items from cart
    fn clear_items(&self, cart_id: CartId) -> Result<()>;

    // Address operations
    /// Set shipping address
    fn set_shipping_address(&self, id: CartId, address: CartAddress) -> Result<Cart>;

    /// Set billing address
    fn set_billing_address(&self, id: CartId, address: CartAddress) -> Result<Cart>;

    // Shipping operations
    /// Set shipping method
    fn set_shipping(&self, id: CartId, shipping: SetCartShipping) -> Result<Cart>;

    /// Get available shipping rates for cart
    fn get_shipping_rates(&self, id: CartId) -> Result<Vec<ShippingRate>>;

    // Payment operations
    /// Set payment method/token
    fn set_payment(&self, id: CartId, payment: SetCartPayment) -> Result<Cart>;

    /// Set x402 payment method (stablecoin)
    fn set_x402_payment(&self, id: CartId, payment: SetCartX402Payment) -> Result<Cart>;

    /// Complete checkout with x402 payment
    /// Returns `PaymentRequired` if no intent exists, `IntentCreated` if awaiting signature,
    /// `AwaitingSettlement` if signed but not settled, or Completed if settled
    fn complete_with_x402(&self, id: CartId, payee_address: &str) -> Result<X402CheckoutResult>;

    // Discount operations
    /// Apply coupon/discount code
    fn apply_discount(&self, id: CartId, coupon_code: &str) -> Result<Cart>;

    /// Remove discount
    fn remove_discount(&self, id: CartId) -> Result<Cart>;

    // Status transitions
    /// Mark cart as ready for payment (validates all requirements met)
    fn mark_ready_for_payment(&self, id: CartId) -> Result<Cart>;

    /// Begin checkout/payment process
    fn begin_checkout(&self, id: CartId) -> Result<Cart>;

    /// Complete checkout (creates order, returns checkout result)
    fn complete(&self, id: CartId) -> Result<CheckoutResult>;

    /// Cancel a cart
    fn cancel(&self, id: CartId) -> Result<Cart>;

    /// Mark cart as abandoned
    fn abandon(&self, id: CartId) -> Result<Cart>;

    /// Expire a cart
    fn expire(&self, id: CartId) -> Result<Cart>;

    // Inventory operations
    /// Reserve inventory for cart items
    fn reserve_inventory(&self, id: CartId) -> Result<Cart>;

    /// Release inventory reservations
    fn release_inventory(&self, id: CartId) -> Result<Cart>;

    // Totals
    /// Recalculate cart totals
    fn recalculate(&self, id: CartId) -> Result<Cart>;

    /// Set tax amount
    fn set_tax(&self, id: CartId, tax_amount: rust_decimal::Decimal) -> Result<Cart>;

    // Queries
    /// Get abandoned carts (for recovery campaigns)
    fn get_abandoned(&self) -> Result<Vec<Cart>>;

    /// Get expired carts
    fn get_expired(&self) -> Result<Vec<Cart>>;

    /// Count carts matching filter
    fn count(&self, filter: CartFilter) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple carts - partial success allowed
    fn create_batch(&self, inputs: Vec<CreateCart>) -> Result<BatchResult<Cart>>;

    /// Create multiple carts - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreateCart>) -> Result<Vec<Cart>>;

    /// Update multiple carts - partial success allowed
    fn update_batch(&self, updates: Vec<(CartId, UpdateCart)>) -> Result<BatchResult<Cart>>;

    /// Update multiple carts - atomic (all-or-nothing)
    fn update_batch_atomic(&self, updates: Vec<(CartId, UpdateCart)>) -> Result<Vec<Cart>>;

    /// Delete multiple carts - partial success allowed
    fn delete_batch(&self, ids: Vec<CartId>) -> Result<BatchResult<CartId>>;

    /// Delete multiple carts - atomic (all-or-nothing)
    fn delete_batch_atomic(&self, ids: Vec<CartId>) -> Result<()>;

    /// Get multiple carts by ID
    fn get_batch(&self, ids: Vec<CartId>) -> Result<Vec<Cart>>;
}

/// Analytics repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait AnalyticsRepository: Send + Sync {
    // Sales analytics
    /// Get sales summary for a time period
    fn get_sales_summary(&self, query: AnalyticsQuery) -> Result<SalesSummary>;

    /// Get revenue broken down by time periods
    fn get_revenue_by_period(&self, query: AnalyticsQuery) -> Result<Vec<RevenueByPeriod>>;

    /// Get top selling products
    fn get_top_products(&self, query: AnalyticsQuery) -> Result<Vec<TopProduct>>;

    /// Get product performance with period comparison
    fn get_product_performance(&self, query: AnalyticsQuery) -> Result<Vec<ProductPerformance>>;

    // Customer analytics
    /// Get customer metrics
    fn get_customer_metrics(&self, query: AnalyticsQuery) -> Result<CustomerMetrics>;

    /// Get top customers by spend
    fn get_top_customers(&self, query: AnalyticsQuery) -> Result<Vec<TopCustomer>>;

    // Inventory analytics
    /// Get inventory health summary
    fn get_inventory_health(&self) -> Result<InventoryHealth>;

    /// Get low stock items
    fn get_low_stock_items(
        &self,
        threshold: Option<rust_decimal::Decimal>,
    ) -> Result<Vec<LowStockItem>>;

    /// Get inventory movement summary
    fn get_inventory_movement(&self, query: AnalyticsQuery) -> Result<Vec<InventoryMovement>>;

    // Order analytics
    /// Get order status breakdown
    fn get_order_status_breakdown(&self, query: AnalyticsQuery) -> Result<OrderStatusBreakdown>;

    /// Get fulfillment metrics
    fn get_fulfillment_metrics(&self, query: AnalyticsQuery) -> Result<FulfillmentMetrics>;

    // Return analytics
    /// Get return metrics
    fn get_return_metrics(&self, query: AnalyticsQuery) -> Result<ReturnMetrics>;

    // Forecasting
    /// Get demand forecast for SKUs
    fn get_demand_forecast(
        &self,
        skus: Option<Vec<String>>,
        days_ahead: u32,
    ) -> Result<Vec<DemandForecast>>;

    /// Get revenue forecast
    fn get_revenue_forecast(
        &self,
        periods_ahead: u32,
        granularity: TimeGranularity,
    ) -> Result<Vec<RevenueForecast>>;

    // === Batch Operations ===

    /// Get multiple sales summaries for different queries
    fn get_sales_summary_batch(&self, queries: Vec<AnalyticsQuery>) -> Result<Vec<SalesSummary>>;
}

/// Currency and exchange rate repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait CurrencyRepository: Send + Sync {
    /// Get current exchange rate between two currencies
    fn get_rate(&self, from: Currency, to: Currency) -> Result<Option<ExchangeRate>>;

    /// Get all exchange rates for a base currency
    fn get_rates_for(&self, base: Currency) -> Result<Vec<ExchangeRate>>;

    /// List all exchange rates with optional filter
    fn list_rates(&self, filter: ExchangeRateFilter) -> Result<Vec<ExchangeRate>>;

    /// Set an exchange rate
    fn set_rate(&self, input: SetExchangeRate) -> Result<ExchangeRate>;

    /// Set multiple exchange rates at once
    fn set_rates(&self, rates: Vec<SetExchangeRate>) -> Result<Vec<ExchangeRate>>;

    /// Delete an exchange rate
    fn delete_rate(&self, id: Uuid) -> Result<()>;

    /// Convert money between currencies
    fn convert(&self, input: ConvertCurrency) -> Result<ConversionResult>;

    /// Get store currency settings
    fn get_settings(&self) -> Result<StoreCurrencySettings>;

    /// Update store currency settings
    fn update_settings(&self, settings: StoreCurrencySettings) -> Result<StoreCurrencySettings>;

    // === Batch Operations ===

    /// Set multiple exchange rates - atomic (all-or-nothing)
    /// Note: `set_rates` already exists as a partial-success batch operation
    fn set_rates_atomic(&self, rates: Vec<SetExchangeRate>) -> Result<Vec<ExchangeRate>>;

    /// Delete multiple exchange rates - partial success allowed
    fn delete_rates_batch(&self, ids: Vec<Uuid>) -> Result<BatchResult<Uuid>>;

    /// Delete multiple exchange rates - atomic (all-or-nothing)
    fn delete_rates_atomic(&self, ids: Vec<Uuid>) -> Result<()>;

    /// Get multiple exchange rates by currency pairs
    fn get_rates_batch(&self, pairs: Vec<(Currency, Currency)>) -> Result<Vec<ExchangeRate>>;
}

/// Tax repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait TaxRepository: Send + Sync {
    /// Create a tax jurisdiction
    fn create_jurisdiction(&self, input: CreateTaxJurisdiction) -> Result<TaxJurisdiction>;
    /// Get a tax jurisdiction by ID
    fn get_jurisdiction(&self, id: Uuid) -> Result<Option<TaxJurisdiction>>;
    /// Get a tax jurisdiction by code
    fn get_jurisdiction_by_code(&self, code: &str) -> Result<Option<TaxJurisdiction>>;
    /// List tax jurisdictions matching a filter
    fn list_jurisdictions(&self, filter: TaxJurisdictionFilter) -> Result<Vec<TaxJurisdiction>>;

    /// Create a tax rate
    fn create_rate(&self, input: CreateTaxRate) -> Result<TaxRate>;
    /// Get a tax rate by ID
    fn get_rate(&self, id: Uuid) -> Result<Option<TaxRate>>;
    /// List tax rates matching a filter
    fn list_rates(&self, filter: TaxRateFilter) -> Result<Vec<TaxRate>>;
    /// Get applicable tax rates for an address and category on a date
    fn get_rates_for_address(
        &self,
        address: &TaxAddress,
        category: ProductTaxCategory,
        date: chrono::NaiveDate,
    ) -> Result<Vec<TaxRate>>;

    /// Create a tax exemption
    fn create_exemption(&self, input: CreateTaxExemption) -> Result<TaxExemption>;
    /// Get a tax exemption by ID
    fn get_exemption(&self, id: Uuid) -> Result<Option<TaxExemption>>;
    /// Get all exemptions for a customer
    fn get_customer_exemptions(&self, customer_id: Uuid) -> Result<Vec<TaxExemption>>;

    /// Get tax settings
    fn get_settings(&self) -> Result<TaxSettings>;
    /// Update tax settings
    fn update_settings(&self, settings: TaxSettings) -> Result<TaxSettings>;

    /// Calculate tax for a request
    fn calculate_tax(&self, request: TaxCalculationRequest) -> Result<TaxCalculationResult>;
    /// Persist a tax calculation for audit/reporting
    fn save_calculation(
        &self,
        result: &TaxCalculationResult,
        order_id: Option<Uuid>,
        cart_id: Option<Uuid>,
        customer_id: Option<Uuid>,
        address: &TaxAddress,
        currency: &str,
    ) -> Result<()>;
}

/// Promotions repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait PromotionRepository: Send + Sync {
    /// Create a promotion
    fn create(&self, input: CreatePromotion) -> Result<Promotion>;
    /// Get a promotion by ID
    fn get(&self, id: PromotionId) -> Result<Option<Promotion>>;
    /// Get a promotion by code
    fn get_by_code(&self, code: &str) -> Result<Option<Promotion>>;
    /// List promotions matching a filter
    fn list(&self, filter: PromotionFilter) -> Result<Vec<Promotion>>;
    /// Update a promotion
    fn update(&self, id: PromotionId, input: UpdatePromotion) -> Result<Promotion>;
    /// Delete a promotion
    fn delete(&self, id: PromotionId) -> Result<()>;
    /// Activate a promotion
    fn activate(&self, id: PromotionId) -> Result<Promotion>;
    /// Deactivate a promotion
    fn deactivate(&self, id: PromotionId) -> Result<Promotion>;

    /// Create a coupon code
    fn create_coupon(&self, input: CreateCouponCode) -> Result<CouponCode>;
    /// Get a coupon by ID
    fn get_coupon(&self, id: Uuid) -> Result<Option<CouponCode>>;
    /// Get a coupon by code
    fn get_coupon_by_code(&self, code: &str) -> Result<Option<CouponCode>>;
    /// List coupons matching a filter
    fn list_coupons(&self, filter: CouponFilter) -> Result<Vec<CouponCode>>;

    /// Apply promotions to a cart or order snapshot
    fn apply_promotions(&self, request: ApplyPromotionsRequest) -> Result<ApplyPromotionsResult>;
    /// Record a promotion usage event
    #[allow(clippy::too_many_arguments)]
    fn record_usage(
        &self,
        promotion_id: PromotionId,
        coupon_id: Option<Uuid>,
        customer_id: Option<CustomerId>,
        order_id: Option<OrderId>,
        cart_id: Option<CartId>,
        discount_amount: rust_decimal::Decimal,
        currency: &str,
    ) -> Result<PromotionUsage>;
}

/// Subscriptions repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait SubscriptionRepository: Send + Sync {
    /// Create a subscription plan
    fn create_plan(&self, input: CreateSubscriptionPlan) -> Result<SubscriptionPlan>;
    /// Get a subscription plan by ID
    fn get_plan(&self, id: Uuid) -> Result<Option<SubscriptionPlan>>;
    /// Get a subscription plan by code
    fn get_plan_by_code(&self, code: &str) -> Result<Option<SubscriptionPlan>>;
    /// List subscription plans matching a filter
    fn list_plans(&self, filter: SubscriptionPlanFilter) -> Result<Vec<SubscriptionPlan>>;
    /// Update a subscription plan
    fn update_plan(&self, id: Uuid, input: UpdateSubscriptionPlan) -> Result<SubscriptionPlan>;
    /// Activate a subscription plan
    fn activate_plan(&self, id: Uuid) -> Result<SubscriptionPlan>;
    /// Archive a subscription plan
    fn archive_plan(&self, id: Uuid) -> Result<SubscriptionPlan>;

    /// Create a subscription
    fn create_subscription(&self, input: CreateSubscription) -> Result<Subscription>;
    /// Get a subscription by ID
    fn get_subscription(&self, id: SubscriptionId) -> Result<Option<Subscription>>;
    /// Get a subscription by number
    fn get_subscription_by_number(&self, number: &str) -> Result<Option<Subscription>>;
    /// List subscriptions matching a filter
    fn list_subscriptions(&self, filter: SubscriptionFilter) -> Result<Vec<Subscription>>;
    /// Update a subscription
    fn update_subscription(
        &self,
        id: SubscriptionId,
        input: UpdateSubscription,
    ) -> Result<Subscription>;
    /// Cancel a subscription
    fn cancel_subscription(
        &self,
        id: SubscriptionId,
        input: CancelSubscription,
    ) -> Result<Subscription>;
    /// Pause a subscription
    fn pause_subscription(
        &self,
        id: SubscriptionId,
        input: PauseSubscription,
    ) -> Result<Subscription>;
    /// Resume a paused subscription
    fn resume_subscription(&self, id: SubscriptionId) -> Result<Subscription>;

    /// Create a billing cycle
    fn create_billing_cycle(&self, input: CreateBillingCycle) -> Result<BillingCycle>;
    /// Get a billing cycle by ID
    fn get_billing_cycle(&self, id: Uuid) -> Result<Option<BillingCycle>>;
    /// List billing cycles matching a filter
    fn list_billing_cycles(&self, filter: BillingCycleFilter) -> Result<Vec<BillingCycle>>;
    /// Update the status of a billing cycle
    fn update_billing_cycle_status(
        &self,
        id: Uuid,
        status: BillingCycleStatus,
    ) -> Result<BillingCycle>;
    /// Skip a billing cycle
    fn skip_billing_cycle(
        &self,
        id: SubscriptionId,
        input: SkipBillingCycle,
    ) -> Result<Subscription>;

    /// Record a subscription event
    fn record_event(
        &self,
        subscription_id: SubscriptionId,
        event_type: SubscriptionEventType,
        notes: Option<String>,
    ) -> Result<SubscriptionEvent>;
    /// Get all events for a subscription
    fn get_subscription_events(
        &self,
        subscription_id: SubscriptionId,
    ) -> Result<Vec<SubscriptionEvent>>;
}

// The `Transactional` trait is defined in `repository.rs` and re-exported
// from this module via `pub use repository::Transactional;`.

// ============================================================================
// Quality Control Repository
// ============================================================================

/// Quality Control repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait QualityRepository: Send + Sync {
    // Inspection operations
    /// Create a new inspection
    fn create_inspection(&self, input: CreateInspection) -> Result<Inspection>;

    /// Get inspection by ID
    fn get_inspection(&self, id: Uuid) -> Result<Option<Inspection>>;

    /// Get inspection by number
    fn get_inspection_by_number(&self, number: &str) -> Result<Option<Inspection>>;

    /// Update an inspection
    fn update_inspection(&self, id: Uuid, input: UpdateInspection) -> Result<Inspection>;

    /// List inspections with filter
    fn list_inspections(&self, filter: InspectionFilter) -> Result<Vec<Inspection>>;

    /// Delete an inspection
    fn delete_inspection(&self, id: Uuid) -> Result<()>;

    /// Start an inspection
    fn start_inspection(&self, id: Uuid) -> Result<Inspection>;

    /// Complete an inspection
    fn complete_inspection(&self, id: Uuid) -> Result<Inspection>;

    /// Record inspection result for an item
    fn record_inspection_result(&self, input: RecordInspectionResult) -> Result<InspectionItem>;

    /// Get inspection items
    fn get_inspection_items(&self, inspection_id: Uuid) -> Result<Vec<InspectionItem>>;

    /// Count inspections
    fn count_inspections(&self, filter: InspectionFilter) -> Result<u64>;

    // NCR operations
    /// Create a non-conformance report
    fn create_ncr(&self, input: CreateNonConformance) -> Result<NonConformance>;

    /// Get NCR by ID
    fn get_ncr(&self, id: Uuid) -> Result<Option<NonConformance>>;

    /// Get NCR by number
    fn get_ncr_by_number(&self, number: &str) -> Result<Option<NonConformance>>;

    /// Update an NCR
    fn update_ncr(&self, id: Uuid, input: UpdateNonConformance) -> Result<NonConformance>;

    /// List NCRs with filter
    fn list_ncrs(&self, filter: NonConformanceFilter) -> Result<Vec<NonConformance>>;

    /// Close an NCR
    fn close_ncr(&self, id: Uuid) -> Result<NonConformance>;

    /// Cancel an NCR
    fn cancel_ncr(&self, id: Uuid) -> Result<NonConformance>;

    /// Count NCRs
    fn count_ncrs(&self, filter: NonConformanceFilter) -> Result<u64>;

    // Quality hold operations
    /// Create a quality hold
    fn create_hold(&self, input: CreateQualityHold) -> Result<QualityHold>;

    /// Get hold by ID
    fn get_hold(&self, id: Uuid) -> Result<Option<QualityHold>>;

    /// List holds with filter
    fn list_holds(&self, filter: QualityHoldFilter) -> Result<Vec<QualityHold>>;

    /// Release a hold
    fn release_hold(&self, id: Uuid, input: ReleaseQualityHold) -> Result<QualityHold>;

    /// Get active holds for SKU
    fn get_active_holds_for_sku(&self, sku: &str) -> Result<Vec<QualityHold>>;

    /// Get active holds for lot
    fn get_active_holds_for_lot(&self, lot_number: &str) -> Result<Vec<QualityHold>>;

    /// Count active holds
    fn count_active_holds(&self) -> Result<u64>;

    // Defect code operations
    /// Create a defect code
    fn create_defect_code(&self, input: CreateDefectCode) -> Result<DefectCode>;

    /// Get defect code by code
    fn get_defect_code(&self, code: &str) -> Result<Option<DefectCode>>;

    /// List defect codes
    fn list_defect_codes(&self, category: Option<&str>) -> Result<Vec<DefectCode>>;

    /// Deactivate a defect code
    fn deactivate_defect_code(&self, id: Uuid) -> Result<()>;
}

// ============================================================================
// Lot Repository
// ============================================================================

/// Lot/Batch tracking repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait LotRepository: Send + Sync {
    /// Create a new lot
    fn create(&self, input: CreateLot) -> Result<Lot>;

    /// Get lot by ID
    fn get(&self, id: Uuid) -> Result<Option<Lot>>;

    /// Get lot by lot number
    fn get_by_number(&self, lot_number: &str) -> Result<Option<Lot>>;

    /// Update a lot
    fn update(&self, id: Uuid, input: UpdateLot) -> Result<Lot>;

    /// List lots with filter
    fn list(&self, filter: LotFilter) -> Result<Vec<Lot>>;

    /// Delete a lot (only if no transactions)
    fn delete(&self, id: Uuid) -> Result<()>;

    /// Adjust lot quantity
    fn adjust(&self, input: AdjustLot) -> Result<LotTransaction>;

    /// Consume from a lot
    fn consume(&self, input: ConsumeLot) -> Result<LotTransaction>;

    /// Reserve quantity from a lot
    fn reserve(&self, input: ReserveLot) -> Result<Uuid>;

    /// Release a reservation
    fn release_reservation(&self, reservation_id: Uuid) -> Result<()>;

    /// Confirm a reservation (convert to consumption)
    fn confirm_reservation(&self, reservation_id: Uuid) -> Result<LotTransaction>;

    /// Transfer lot between locations
    fn transfer(&self, input: TransferLot) -> Result<LotTransaction>;

    /// Split a lot into two
    fn split(&self, input: SplitLot) -> Result<Lot>;

    /// Merge multiple lots into one
    fn merge(&self, input: MergeLots) -> Result<Lot>;

    /// Quarantine a lot
    fn quarantine(&self, id: Uuid, reason: &str) -> Result<Lot>;

    /// Release from quarantine
    fn release_quarantine(&self, id: Uuid) -> Result<Lot>;

    /// Get lot transactions
    fn get_transactions(&self, lot_id: Uuid, limit: u32) -> Result<Vec<LotTransaction>>;

    /// Get lot quantity at a location (None if no location record exists)
    fn get_quantity_at_location(
        &self,
        lot_id: Uuid,
        location_id: i32,
    ) -> Result<Option<rust_decimal::Decimal>>;

    /// Get all locations for a lot
    fn get_lot_locations(&self, lot_id: Uuid) -> Result<Vec<LotLocation>>;

    // Certificate operations
    /// Add certificate to lot
    fn add_certificate(&self, input: AddLotCertificate) -> Result<LotCertificate>;

    /// Get certificates for lot
    fn get_certificates(&self, lot_id: Uuid) -> Result<Vec<LotCertificate>>;

    /// Delete certificate
    fn delete_certificate(&self, certificate_id: Uuid) -> Result<()>;

    // Queries
    /// Get expiring lots
    fn get_expiring_lots(&self, days: i32) -> Result<Vec<Lot>>;

    /// Get expired lots
    fn get_expired_lots(&self) -> Result<Vec<Lot>>;

    /// Get lots with available quantity for SKU
    fn get_available_lots_for_sku(&self, sku: &str) -> Result<Vec<Lot>>;

    /// Trace lot (upstream and downstream)
    fn trace(&self, lot_id: Uuid) -> Result<TraceabilityResult>;

    /// Count lots
    fn count(&self, filter: LotFilter) -> Result<u64>;

    // Batch operations
    /// Create multiple lots
    fn create_batch(&self, inputs: Vec<CreateLot>) -> Result<BatchResult<Lot>>;

    /// Get multiple lots by ID
    fn get_batch(&self, ids: Vec<Uuid>) -> Result<Vec<Lot>>;
}

// ============================================================================
// Serial Number Repository
// ============================================================================

/// Serial number management repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait SerialRepository: Send + Sync {
    /// Create a serial number
    fn create(&self, input: CreateSerialNumber) -> Result<SerialNumber>;

    /// Create multiple serial numbers in bulk
    fn create_bulk(&self, input: CreateSerialNumbersBulk) -> Result<Vec<SerialNumber>>;

    /// Get serial by ID
    fn get(&self, id: Uuid) -> Result<Option<SerialNumber>>;

    /// Get serial by serial number string
    fn get_by_serial(&self, serial: &str) -> Result<Option<SerialNumber>>;

    /// Update a serial number
    fn update(&self, id: Uuid, input: UpdateSerialNumber) -> Result<SerialNumber>;

    /// List serials with filter
    fn list(&self, filter: SerialFilter) -> Result<Vec<SerialNumber>>;

    /// Delete a serial (only if never used)
    fn delete(&self, id: Uuid) -> Result<()>;

    /// Change serial status with history tracking
    fn change_status(&self, input: ChangeSerialStatus) -> Result<SerialNumber>;

    /// Reserve a serial
    fn reserve(&self, input: ReserveSerialNumber) -> Result<SerialReservation>;

    /// Release reservation
    fn release_reservation(&self, reservation_id: Uuid) -> Result<()>;

    /// Confirm reservation
    fn confirm_reservation(&self, reservation_id: Uuid) -> Result<()>;

    /// Move serial to new location
    fn move_serial(&self, input: MoveSerial) -> Result<SerialNumber>;

    /// Transfer ownership
    fn transfer_ownership(&self, input: TransferSerialOwnership) -> Result<SerialNumber>;

    /// Mark as sold
    fn mark_sold(
        &self,
        id: Uuid,
        customer_id: Uuid,
        order_id: Option<Uuid>,
    ) -> Result<SerialNumber>;

    /// Mark as shipped
    fn mark_shipped(&self, id: Uuid, shipment_id: Uuid) -> Result<SerialNumber>;

    /// Mark as returned
    fn mark_returned(&self, id: Uuid, return_id: Uuid) -> Result<SerialNumber>;

    /// Activate serial (e.g., for warranty)
    fn activate(&self, id: Uuid) -> Result<SerialNumber>;

    /// Quarantine serial
    fn quarantine(&self, id: Uuid, reason: &str) -> Result<SerialNumber>;

    /// Release from quarantine
    fn release_quarantine(&self, id: Uuid) -> Result<SerialNumber>;

    /// Scrap serial
    fn scrap(&self, id: Uuid, reason: &str) -> Result<SerialNumber>;

    // History operations
    /// Get serial history
    fn get_history(
        &self,
        serial_id: Uuid,
        filter: SerialHistoryFilter,
    ) -> Result<Vec<SerialHistory>>;

    /// Get full serial lookup with related data
    fn lookup(&self, serial: &str) -> Result<Option<SerialLookupResult>>;

    /// Validate serial number
    fn validate(&self, serial: &str) -> Result<SerialValidation>;

    // Queries
    /// Get available serials for SKU
    fn get_available_for_sku(&self, sku: &str, limit: u32) -> Result<Vec<SerialNumber>>;

    /// Get serials for lot
    fn get_for_lot(&self, lot_id: Uuid) -> Result<Vec<SerialNumber>>;

    /// Get serials for customer
    fn get_for_customer(&self, customer_id: Uuid) -> Result<Vec<SerialNumber>>;

    /// Count serials
    fn count(&self, filter: SerialFilter) -> Result<u64>;

    // Batch operations
    /// Create multiple serials
    fn create_batch(&self, inputs: Vec<CreateSerialNumber>) -> Result<BatchResult<SerialNumber>>;

    /// Get multiple serials by ID
    fn get_batch(&self, ids: Vec<Uuid>) -> Result<Vec<SerialNumber>>;

    /// Get multiple serials by serial string
    fn get_batch_by_serial(&self, serials: Vec<String>) -> Result<Vec<SerialNumber>>;
}

// ============================================================================
// Warehouse Repository
// ============================================================================

/// Warehouse management repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait WarehouseRepository: Send + Sync {
    // Warehouse operations
    /// Create a new warehouse
    fn create_warehouse(&self, input: CreateWarehouse) -> Result<Warehouse>;

    /// Get warehouse by ID
    fn get_warehouse(&self, id: i32) -> Result<Option<Warehouse>>;

    /// Get warehouse by code
    fn get_warehouse_by_code(&self, code: &str) -> Result<Option<Warehouse>>;

    /// Update a warehouse
    fn update_warehouse(&self, id: i32, input: UpdateWarehouse) -> Result<Warehouse>;

    /// List warehouses with filter
    fn list_warehouses(&self, filter: WarehouseFilter) -> Result<Vec<Warehouse>>;

    /// Delete a warehouse (only if empty)
    fn delete_warehouse(&self, id: i32) -> Result<()>;

    /// Count warehouses
    fn count_warehouses(&self, filter: WarehouseFilter) -> Result<u64>;

    // Zone operations
    /// Create a zone
    fn create_zone(&self, input: CreateZone) -> Result<Zone>;

    /// Get zone by ID
    fn get_zone(&self, id: i32) -> Result<Option<Zone>>;

    /// Get zones for warehouse
    fn get_zones(&self, warehouse_id: i32) -> Result<Vec<Zone>>;

    /// Update a zone
    fn update_zone(&self, id: i32, input: UpdateZone) -> Result<Zone>;

    /// Delete a zone
    fn delete_zone(&self, id: i32) -> Result<()>;

    // Location operations
    /// Create a location
    fn create_location(&self, input: CreateLocation) -> Result<Location>;

    /// Get location by ID
    fn get_location(&self, id: i32) -> Result<Option<Location>>;

    /// Get location by code
    fn get_location_by_code(&self, warehouse_id: i32, code: &str) -> Result<Option<Location>>;

    /// Update a location
    fn update_location(&self, id: i32, input: UpdateLocation) -> Result<Location>;

    /// List locations with filter
    fn list_locations(&self, filter: LocationFilter) -> Result<Vec<Location>>;

    /// Delete a location (only if empty)
    fn delete_location(&self, id: i32) -> Result<()>;

    /// Count locations
    fn count_locations(&self, filter: LocationFilter) -> Result<u64>;

    /// Get locations for warehouse
    fn get_locations_for_warehouse(&self, warehouse_id: i32) -> Result<Vec<Location>>;

    /// Get pickable locations for SKU
    fn get_pickable_locations(&self, warehouse_id: i32, sku: &str) -> Result<Vec<Location>>;

    /// Get receivable locations
    fn get_receivable_locations(&self, warehouse_id: i32) -> Result<Vec<Location>>;

    // Location inventory operations
    /// Get inventory at location
    fn get_location_inventory(&self, location_id: i32) -> Result<Vec<LocationInventory>>;

    /// Get inventory for SKU across locations
    fn get_inventory_for_sku(&self, warehouse_id: i32, sku: &str)
    -> Result<Vec<LocationInventory>>;

    /// Adjust inventory at location
    fn adjust_inventory(&self, input: AdjustLocationInventory) -> Result<LocationInventory>;

    /// Move inventory between locations
    fn move_inventory(&self, input: MoveInventory) -> Result<LocationMovement>;

    /// Get location inventory by filter
    fn list_location_inventory(
        &self,
        filter: LocationInventoryFilter,
    ) -> Result<Vec<LocationInventory>>;

    // Movement operations
    /// Get inventory movements
    fn get_movements(&self, filter: MovementFilter) -> Result<Vec<LocationMovement>>;

    /// Count movements
    fn count_movements(&self, filter: MovementFilter) -> Result<u64>;

    // Batch operations
    /// Create multiple locations
    fn create_locations_batch(&self, inputs: Vec<CreateLocation>) -> Result<BatchResult<Location>>;

    /// Get multiple locations by ID
    fn get_locations_batch(&self, ids: Vec<i32>) -> Result<Vec<Location>>;
}

// ============================================================================
// Receiving Repository
// ============================================================================

/// Receiving/Goods receipt repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait ReceivingRepository: Send + Sync {
    // Receipt operations
    /// Create a new receipt
    fn create_receipt(&self, input: CreateReceipt) -> Result<Receipt>;

    /// Get receipt by ID
    fn get_receipt(&self, id: Uuid) -> Result<Option<Receipt>>;

    /// Get receipt by receipt number
    fn get_receipt_by_number(&self, number: &str) -> Result<Option<Receipt>>;

    /// Update a receipt
    fn update_receipt(&self, id: Uuid, input: UpdateReceipt) -> Result<Receipt>;

    /// List receipts with filter
    fn list_receipts(&self, filter: ReceiptFilter) -> Result<Vec<Receipt>>;

    /// Delete a receipt (only if not started)
    fn delete_receipt(&self, id: Uuid) -> Result<()>;

    /// Start receiving (transition to `in_progress`)
    fn start_receiving(&self, id: Uuid) -> Result<Receipt>;

    /// Receive items on a receipt
    fn receive_items(&self, input: ReceiveItems) -> Result<Receipt>;

    /// Complete receiving (all items received)
    fn complete_receiving(&self, id: Uuid) -> Result<Receipt>;

    /// Cancel a receipt
    fn cancel_receipt(&self, id: Uuid) -> Result<Receipt>;

    /// Get receipt items
    fn get_receipt_items(&self, receipt_id: Uuid) -> Result<Vec<ReceiptItem>>;

    /// Count receipts
    fn count_receipts(&self, filter: ReceiptFilter) -> Result<u64>;

    // Put-away operations
    /// Create a put-away task
    fn create_put_away(&self, input: CreatePutAway) -> Result<PutAway>;

    /// Get put-away by ID
    fn get_put_away(&self, id: Uuid) -> Result<Option<PutAway>>;

    /// List put-aways with filter
    fn list_put_aways(&self, filter: PutAwayFilter) -> Result<Vec<PutAway>>;

    /// Assign put-away to user
    fn assign_put_away(&self, id: Uuid, assigned_to: &str) -> Result<PutAway>;

    /// Start put-away
    fn start_put_away(&self, id: Uuid) -> Result<PutAway>;

    /// Complete put-away
    fn complete_put_away(&self, input: CompletePutAway) -> Result<PutAway>;

    /// Cancel put-away
    fn cancel_put_away(&self, id: Uuid) -> Result<PutAway>;

    /// Get pending put-aways for receipt
    fn get_pending_put_aways(&self, receipt_id: Uuid) -> Result<Vec<PutAway>>;

    /// Count put-aways
    fn count_put_aways(&self, filter: PutAwayFilter) -> Result<u64>;

    // Integration with PO
    /// Create receipt from purchase order
    fn create_receipt_from_po(&self, po_id: Uuid, warehouse_id: i32) -> Result<Receipt>;

    // Batch operations
    /// Create multiple receipts
    fn create_receipts_batch(&self, inputs: Vec<CreateReceipt>) -> Result<BatchResult<Receipt>>;

    /// Get multiple receipts by ID
    fn get_receipts_batch(&self, ids: Vec<Uuid>) -> Result<Vec<Receipt>>;
}

// ============================================================================
// Fulfillment Repository
// ============================================================================

/// Fulfillment (pick/pack/ship) repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait FulfillmentRepository: Send + Sync {
    // Wave operations
    /// Create a wave from orders
    fn create_wave(&self, input: CreateWave) -> Result<Wave>;

    /// Get wave by ID
    fn get_wave(&self, id: FulfillmentId) -> Result<Option<Wave>>;

    /// Get wave by number
    fn get_wave_by_number(&self, number: &str) -> Result<Option<Wave>>;

    /// List waves with filter
    fn list_waves(&self, filter: WaveFilter) -> Result<Vec<Wave>>;

    /// Release wave for picking
    fn release_wave(&self, id: FulfillmentId) -> Result<Wave>;

    /// Complete a wave
    fn complete_wave(&self, id: FulfillmentId) -> Result<Wave>;

    /// Cancel a wave
    fn cancel_wave(&self, id: FulfillmentId) -> Result<Wave>;

    /// Get orders in a wave
    fn get_wave_orders(&self, wave_id: FulfillmentId) -> Result<Vec<OrderId>>;

    /// Count waves
    fn count_waves(&self, filter: WaveFilter) -> Result<u64>;

    // Pick operations
    /// Create a pick task
    fn create_pick(&self, input: CreatePickTask) -> Result<PickTask>;

    /// Get pick task by ID
    fn get_pick(&self, id: Uuid) -> Result<Option<PickTask>>;

    /// List pick tasks with filter
    fn list_picks(&self, filter: PickTaskFilter) -> Result<Vec<PickTask>>;

    /// Assign pick to user
    fn assign_pick(&self, id: Uuid, assigned_to: &str) -> Result<PickTask>;

    /// Start a pick
    fn start_pick(&self, id: Uuid) -> Result<PickTask>;

    /// Complete a pick
    fn complete_pick(&self, input: CompletePick) -> Result<PickTask>;

    /// Report short pick
    fn report_short(
        &self,
        id: Uuid,
        short_qty: rust_decimal::Decimal,
        reason: &str,
    ) -> Result<PickTask>;

    /// Cancel a pick
    fn cancel_pick(&self, id: Uuid) -> Result<PickTask>;

    /// Get picks for order
    fn get_picks_for_order(&self, order_id: OrderId) -> Result<Vec<PickTask>>;

    /// Get picks for wave
    fn get_picks_for_wave(&self, wave_id: FulfillmentId) -> Result<Vec<PickTask>>;

    /// Count picks
    fn count_picks(&self, filter: PickTaskFilter) -> Result<u64>;

    // Pack operations
    /// Create a pack task
    fn create_pack(&self, input: CreatePackTask) -> Result<PackTask>;

    /// Get pack task by ID
    fn get_pack(&self, id: Uuid) -> Result<Option<PackTask>>;

    /// List pack tasks with filter
    fn list_packs(&self, filter: PackTaskFilter) -> Result<Vec<PackTask>>;

    /// Assign pack to user
    fn assign_pack(&self, id: Uuid, assigned_to: &str) -> Result<PackTask>;

    /// Start packing
    fn start_pack(&self, id: Uuid) -> Result<PackTask>;

    /// Complete packing
    fn complete_pack(&self, id: Uuid) -> Result<PackTask>;

    /// Add carton to pack task
    fn add_carton(&self, input: AddCarton) -> Result<Carton>;

    /// Add item to carton
    fn add_carton_item(&self, input: AddCartonItem) -> Result<CartonItem>;

    /// Get cartons for pack task
    fn get_cartons(&self, pack_task_id: Uuid) -> Result<Vec<Carton>>;

    /// Get items in carton
    fn get_carton_items(&self, carton_id: Uuid) -> Result<Vec<CartonItem>>;

    /// Mark carton label printed
    fn mark_label_printed(&self, carton_id: Uuid) -> Result<Carton>;

    /// Cancel pack task
    fn cancel_pack(&self, id: Uuid) -> Result<PackTask>;

    /// Count packs
    fn count_packs(&self, filter: PackTaskFilter) -> Result<u64>;

    // Ship operations
    /// Create a ship task
    fn create_ship(&self, input: CreateShipTask) -> Result<ShipTask>;

    /// Get ship task by ID
    fn get_ship(&self, id: Uuid) -> Result<Option<ShipTask>>;

    /// List ship tasks with filter
    fn list_ships(&self, filter: ShipTaskFilter) -> Result<Vec<ShipTask>>;

    /// Assign ship to user
    fn assign_ship(&self, id: Uuid, assigned_to: &str) -> Result<ShipTask>;

    /// Print shipping label
    fn print_label(&self, id: Uuid, label_url: &str) -> Result<ShipTask>;

    /// Complete shipping
    fn complete_ship(&self, input: CompleteShip) -> Result<ShipTask>;

    /// Cancel ship task
    fn cancel_ship(&self, id: Uuid) -> Result<ShipTask>;

    /// Count ships
    fn count_ships(&self, filter: ShipTaskFilter) -> Result<u64>;

    // Workflow helpers
    /// Create picks for an order
    fn create_picks_for_order(&self, order_id: OrderId, warehouse_id: i32)
    -> Result<Vec<PickTask>>;

    /// Check if order is ready to pack
    fn is_order_ready_to_pack(&self, order_id: OrderId) -> Result<bool>;

    /// Check if order is ready to ship
    fn is_order_ready_to_ship(&self, order_id: OrderId) -> Result<bool>;

    // Batch operations
    /// Create multiple waves
    fn create_waves_batch(&self, inputs: Vec<CreateWave>) -> Result<BatchResult<Wave>>;

    /// Get multiple picks by ID
    fn get_picks_batch(&self, ids: Vec<Uuid>) -> Result<Vec<PickTask>>;
}

// ============================================================================
// Accounts Payable Repository
// ============================================================================

/// Accounts Payable repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait AccountsPayableRepository: Send + Sync {
    // Bill operations
    /// Create a new bill
    fn create_bill(&self, input: CreateBill) -> Result<Bill>;

    /// Get bill by ID
    fn get_bill(&self, id: Uuid) -> Result<Option<Bill>>;

    /// Get bill by number
    fn get_bill_by_number(&self, number: &str) -> Result<Option<Bill>>;

    /// Update a bill
    fn update_bill(&self, id: Uuid, input: UpdateBill) -> Result<Bill>;

    /// List bills with filter
    fn list_bills(&self, filter: BillFilter) -> Result<Vec<Bill>>;

    /// Delete a bill (only if draft)
    fn delete_bill(&self, id: Uuid) -> Result<()>;

    /// Approve a bill
    fn approve_bill(&self, id: Uuid) -> Result<Bill>;

    /// Cancel a bill
    fn cancel_bill(&self, id: Uuid) -> Result<Bill>;

    /// Mark bill as disputed
    fn dispute_bill(&self, id: Uuid) -> Result<Bill>;

    /// Get bill items
    fn get_bill_items(&self, bill_id: Uuid) -> Result<Vec<BillItem>>;

    /// Add item to bill
    fn add_bill_item(&self, bill_id: Uuid, item: CreateBillItem) -> Result<BillItem>;

    /// Remove item from bill
    fn remove_bill_item(&self, item_id: Uuid) -> Result<()>;

    /// Count bills
    fn count_bills(&self, filter: BillFilter) -> Result<u64>;

    /// Get overdue bills
    fn get_overdue_bills(&self) -> Result<Vec<Bill>>;

    /// Get bills due soon (within days)
    fn get_bills_due_soon(&self, days: i32) -> Result<Vec<Bill>>;

    // Payment operations
    /// Create a payment
    fn create_payment(&self, input: CreateBillPayment) -> Result<BillPayment>;

    /// Get payment by ID
    fn get_payment(&self, id: Uuid) -> Result<Option<BillPayment>>;

    /// Get payment by number
    fn get_payment_by_number(&self, number: &str) -> Result<Option<BillPayment>>;

    /// List payments with filter
    fn list_payments(&self, filter: BillPaymentFilter) -> Result<Vec<BillPayment>>;

    /// Void a payment
    fn void_payment(&self, id: Uuid) -> Result<BillPayment>;

    /// Mark payment as cleared
    fn clear_payment(&self, id: Uuid) -> Result<BillPayment>;

    /// Get payment allocations
    fn get_payment_allocations(&self, payment_id: Uuid) -> Result<Vec<PaymentAllocation>>;

    /// Get payments for bill
    fn get_payments_for_bill(&self, bill_id: Uuid) -> Result<Vec<BillPayment>>;

    /// Count payments
    fn count_payments(&self, filter: BillPaymentFilter) -> Result<u64>;

    // Payment run operations
    /// Create a payment run
    fn create_payment_run(&self, input: CreatePaymentRun) -> Result<PaymentRun>;

    /// Get payment run by ID
    fn get_payment_run(&self, id: Uuid) -> Result<Option<PaymentRun>>;

    /// List payment runs with filter
    fn list_payment_runs(&self, filter: PaymentRunFilter) -> Result<Vec<PaymentRun>>;

    /// Approve payment run
    fn approve_payment_run(&self, id: Uuid, approved_by: &str) -> Result<PaymentRun>;

    /// Process payment run
    fn process_payment_run(&self, id: Uuid) -> Result<PaymentRun>;

    /// Cancel payment run
    fn cancel_payment_run(&self, id: Uuid) -> Result<PaymentRun>;

    /// Get bills in payment run
    fn get_payment_run_bills(&self, run_id: Uuid) -> Result<Vec<Bill>>;

    // Analytics
    /// Get AP aging summary
    fn get_aging_summary(&self) -> Result<ApAgingSummary>;

    /// Get AP summary by supplier (None if supplier is not found)
    fn get_supplier_summary(&self, supplier_id: Uuid) -> Result<Option<SupplierApSummary>>;

    /// Get total AP outstanding
    fn get_total_outstanding(&self) -> Result<rust_decimal::Decimal>;

    // Batch operations
    /// Create multiple bills
    fn create_bills_batch(&self, inputs: Vec<CreateBill>) -> Result<BatchResult<Bill>>;

    /// Get multiple bills by ID
    fn get_bills_batch(&self, ids: Vec<Uuid>) -> Result<Vec<Bill>>;
}

/// Cost Accounting repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait CostAccountingRepository: Send + Sync {
    // Item cost operations
    /// Get item cost by SKU
    fn get_item_cost(&self, sku: &str) -> Result<Option<ItemCost>>;

    /// Set/update item cost
    fn set_item_cost(&self, input: SetItemCost) -> Result<ItemCost>;

    /// List item costs
    fn list_item_costs(&self, filter: ItemCostFilter) -> Result<Vec<ItemCost>>;

    /// Update average cost (called when receiving inventory)
    fn update_average_cost(
        &self,
        sku: &str,
        quantity: rust_decimal::Decimal,
        unit_cost: rust_decimal::Decimal,
    ) -> Result<ItemCost>;

    /// Update last cost
    fn update_last_cost(&self, sku: &str, unit_cost: rust_decimal::Decimal) -> Result<ItemCost>;

    // Cost layer operations (for FIFO/LIFO)
    /// Create a cost layer
    fn create_cost_layer(&self, input: CreateCostLayer) -> Result<CostLayer>;

    /// Get cost layer by ID
    fn get_cost_layer(&self, id: Uuid) -> Result<Option<CostLayer>>;

    /// List cost layers
    fn list_cost_layers(&self, filter: CostLayerFilter) -> Result<Vec<CostLayer>>;

    /// Issue from cost layers (FIFO)
    fn issue_fifo(&self, input: IssueCostLayers) -> Result<Vec<CostTransaction>>;

    /// Issue from cost layers (LIFO)
    fn issue_lifo(&self, input: IssueCostLayers) -> Result<Vec<CostTransaction>>;

    /// Get remaining quantity in layers for SKU
    fn get_layers_remaining(&self, sku: &str) -> Result<rust_decimal::Decimal>;

    // Cost transaction operations
    /// Record a cost transaction
    #[allow(clippy::too_many_arguments)]
    fn record_cost_transaction(
        &self,
        sku: &str,
        transaction_type: CostTransactionType,
        quantity: rust_decimal::Decimal,
        unit_cost: rust_decimal::Decimal,
        layer_id: Option<Uuid>,
        reference_type: Option<&str>,
        reference_id: Option<Uuid>,
        notes: Option<&str>,
    ) -> Result<CostTransaction>;

    /// List cost transactions
    fn list_cost_transactions(&self, filter: CostTransactionFilter)
    -> Result<Vec<CostTransaction>>;

    // Cost variance operations
    /// Record a cost variance
    fn record_variance(&self, input: RecordCostVariance) -> Result<CostVariance>;

    /// List cost variances
    fn list_variances(&self, filter: CostVarianceFilter) -> Result<Vec<CostVariance>>;

    /// Get variance summary for period
    fn get_variance_summary(
        &self,
        from: DateTime<Utc>,
        to: DateTime<Utc>,
    ) -> Result<rust_decimal::Decimal>;

    // Cost adjustment operations
    /// Create a cost adjustment
    fn create_adjustment(&self, input: CreateCostAdjustment) -> Result<CostAdjustment>;

    /// Get adjustment by ID
    fn get_adjustment(&self, id: Uuid) -> Result<Option<CostAdjustment>>;

    /// List adjustments
    fn list_adjustments(&self, filter: CostAdjustmentFilter) -> Result<Vec<CostAdjustment>>;

    /// Approve adjustment
    fn approve_adjustment(&self, id: Uuid, approved_by: &str) -> Result<CostAdjustment>;

    /// Apply adjustment (update item cost)
    fn apply_adjustment(&self, id: Uuid) -> Result<CostAdjustment>;

    /// Reject adjustment
    fn reject_adjustment(&self, id: Uuid) -> Result<CostAdjustment>;

    // Rollup operations
    /// Calculate cost rollup for manufactured item
    fn calculate_rollup(&self, sku: &str, bom_id: Option<Uuid>) -> Result<CostRollup>;

    /// Get latest rollup for SKU
    fn get_rollup(&self, sku: &str) -> Result<Option<CostRollup>>;

    // Valuation operations
    /// Get inventory valuation
    fn get_inventory_valuation(&self, cost_method: CostMethod) -> Result<InventoryValuation>;

    /// Get SKU cost summary
    fn get_sku_cost_summary(&self, sku: &str) -> Result<Option<SkuCostSummary>>;

    /// Get total inventory value
    fn get_total_inventory_value(&self) -> Result<rust_decimal::Decimal>;
}

/// Credit Management repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait CreditRepository: Send + Sync {
    // Credit account operations
    /// Create a credit account for a customer
    fn create_credit_account(&self, input: CreateCreditAccount) -> Result<CreditAccount>;

    /// Get credit account by ID
    fn get_credit_account(&self, id: CreditId) -> Result<Option<CreditAccount>>;

    /// Get credit account by customer ID
    fn get_credit_account_by_customer(
        &self,
        customer_id: CustomerId,
    ) -> Result<Option<CreditAccount>>;

    /// Update credit account
    fn update_credit_account(
        &self,
        id: CreditId,
        input: UpdateCreditAccount,
    ) -> Result<CreditAccount>;

    /// List credit accounts
    fn list_credit_accounts(&self, filter: CreditAccountFilter) -> Result<Vec<CreditAccount>>;

    /// Adjust credit limit
    fn adjust_credit_limit(
        &self,
        customer_id: CustomerId,
        new_limit: rust_decimal::Decimal,
        reason: &str,
    ) -> Result<CreditAccount>;

    /// Suspend credit account
    fn suspend_credit_account(
        &self,
        customer_id: CustomerId,
        reason: &str,
    ) -> Result<CreditAccount>;

    /// Reactivate credit account
    fn reactivate_credit_account(&self, customer_id: CustomerId) -> Result<CreditAccount>;

    // Credit check operations
    /// Check credit for an order
    fn check_credit(
        &self,
        customer_id: CustomerId,
        order_amount: rust_decimal::Decimal,
    ) -> Result<CreditCheckResult>;

    /// Reserve credit for an order
    fn reserve_credit(
        &self,
        customer_id: CustomerId,
        order_id: OrderId,
        amount: rust_decimal::Decimal,
    ) -> Result<CreditAccount>;

    /// Release credit reservation
    fn release_credit_reservation(
        &self,
        customer_id: CustomerId,
        order_id: OrderId,
    ) -> Result<CreditAccount>;

    /// Charge credit (convert reservation to balance)
    fn charge_credit(
        &self,
        customer_id: CustomerId,
        order_id: OrderId,
        amount: rust_decimal::Decimal,
    ) -> Result<CreditAccount>;

    // Credit hold operations
    /// Place a credit hold
    fn place_hold(&self, input: PlaceCreditHold) -> Result<CreditHold>;

    /// Get credit hold by ID
    fn get_hold(&self, id: Uuid) -> Result<Option<CreditHold>>;

    /// List credit holds
    fn list_holds(&self, filter: CreditHoldFilter) -> Result<Vec<CreditHold>>;

    /// Release a credit hold
    fn release_hold(&self, input: ReleaseCreditHold) -> Result<CreditHold>;

    /// Get active holds for customer
    fn get_active_holds(&self, customer_id: CustomerId) -> Result<Vec<CreditHold>>;

    /// Get active holds for order
    fn get_holds_for_order(&self, order_id: OrderId) -> Result<Vec<CreditHold>>;

    // Credit application operations
    /// Submit a credit application
    fn submit_application(&self, input: SubmitCreditApplication) -> Result<CreditApplication>;

    /// Get credit application by ID
    fn get_application(&self, id: Uuid) -> Result<Option<CreditApplication>>;

    /// List credit applications
    fn list_applications(&self, filter: CreditApplicationFilter) -> Result<Vec<CreditApplication>>;

    /// Review credit application
    fn review_application(&self, input: ReviewCreditApplication) -> Result<CreditApplication>;

    /// Withdraw credit application
    fn withdraw_application(&self, id: Uuid) -> Result<CreditApplication>;

    // Transaction operations
    /// Record a credit transaction
    fn record_transaction(&self, input: RecordCreditTransaction) -> Result<CreditTransaction>;

    /// List credit transactions
    fn list_transactions(&self, filter: CreditTransactionFilter) -> Result<Vec<CreditTransaction>>;

    /// Apply payment to balance
    fn apply_payment(
        &self,
        customer_id: CustomerId,
        amount: rust_decimal::Decimal,
        reference_id: Option<Uuid>,
    ) -> Result<CreditAccount>;

    // Analytics
    /// Get customer credit summary
    fn get_customer_summary(
        &self,
        customer_id: CustomerId,
    ) -> Result<Option<CustomerCreditSummary>>;

    /// Get credit aging buckets
    fn get_aging_report(&self) -> Result<Vec<(CustomerId, CreditAgingBucket)>>;

    /// Get customers over credit limit
    fn get_over_limit_customers(&self) -> Result<Vec<CreditAccount>>;
}

/// Backorder repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait BackorderRepository: Send + Sync {
    // Backorder operations
    /// Create a backorder
    fn create_backorder(&self, input: CreateBackorder) -> Result<Backorder>;

    /// Get backorder by ID
    fn get_backorder(&self, id: Uuid) -> Result<Option<Backorder>>;

    /// Get backorder by number
    fn get_backorder_by_number(&self, number: &str) -> Result<Option<Backorder>>;

    /// Update backorder
    fn update_backorder(&self, id: Uuid, input: UpdateBackorder) -> Result<Backorder>;

    /// List backorders
    fn list_backorders(&self, filter: BackorderFilter) -> Result<Vec<Backorder>>;

    /// Cancel backorder
    fn cancel_backorder(&self, id: Uuid) -> Result<Backorder>;

    /// Get backorders for order
    fn get_backorders_for_order(&self, order_id: Uuid) -> Result<Vec<Backorder>>;

    /// Get backorders for customer
    fn get_backorders_for_customer(&self, customer_id: Uuid) -> Result<Vec<Backorder>>;

    /// Get backorders for SKU
    fn get_backorders_for_sku(&self, sku: &str) -> Result<Vec<Backorder>>;

    // Fulfillment operations
    /// Fulfill backorder (partial or full)
    fn fulfill_backorder(&self, input: FulfillBackorder) -> Result<Backorder>;

    /// Get fulfillment history for backorder
    fn get_fulfillment_history(&self, backorder_id: Uuid) -> Result<Vec<BackorderFulfillment>>;

    // Allocation operations
    /// Allocate inventory to backorder
    fn allocate_backorder(&self, input: AllocateBackorder) -> Result<BackorderAllocation>;

    /// Get allocations for backorder
    fn get_allocations(&self, backorder_id: Uuid) -> Result<Vec<BackorderAllocation>>;

    /// Release allocation
    fn release_allocation(&self, allocation_id: Uuid) -> Result<BackorderAllocation>;

    /// Confirm allocation
    fn confirm_allocation(&self, allocation_id: Uuid) -> Result<BackorderAllocation>;

    /// Expire old allocations
    fn expire_allocations(&self) -> Result<u32>;

    // Auto-allocation
    /// Auto-allocate available inventory to pending backorders
    fn auto_allocate_inventory(&self, sku: &str) -> Result<Vec<BackorderAllocation>>;

    // Analytics
    /// Get backorder summary
    fn get_summary(&self) -> Result<BackorderSummary>;

    /// Get SKU backorder summary
    fn get_sku_summary(&self, sku: &str) -> Result<Option<SkuBackorderSummary>>;

    /// Get overdue backorders
    fn get_overdue_backorders(&self) -> Result<Vec<Backorder>>;

    /// Count pending backorders
    fn count_pending(&self) -> Result<u64>;
}

// ============================================================================
// Accounts Receivable Repository
// ============================================================================

/// Accounts Receivable repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait AccountsReceivableRepository: Send + Sync {
    // Aging reports
    /// Get AR aging summary across all customers
    fn get_aging_summary(&self) -> Result<ArAgingSummary>;

    /// Get aging by customer (None if customer is not found)
    fn get_customer_aging(&self, customer_id: Uuid) -> Result<Option<CustomerArAging>>;

    /// Get all customers with aging (AR aging report)
    fn get_aging_report(&self, filter: ArAgingFilter) -> Result<Vec<CustomerArAging>>;

    // Collection management
    /// Log collection activity
    fn log_collection_activity(
        &self,
        input: CreateCollectionActivity,
    ) -> Result<CollectionActivity>;

    /// Get collection activities
    fn list_collection_activities(
        &self,
        filter: CollectionActivityFilter,
    ) -> Result<Vec<CollectionActivity>>;

    /// Update invoice collection status
    fn update_collection_status(
        &self,
        invoice_id: InvoiceId,
        status: CollectionStatus,
    ) -> Result<()>;

    /// Get invoices due for dunning (based on aging)
    fn get_invoices_due_for_dunning(&self) -> Result<Vec<Invoice>>;

    /// Send dunning letter (records activity, updates status)
    fn send_dunning_letter(
        &self,
        invoice_id: InvoiceId,
        letter_type: DunningLetterType,
        sent_by: Option<&str>,
    ) -> Result<CollectionActivity>;

    // Write-offs
    /// Create a write-off
    fn create_write_off(&self, input: CreateWriteOff) -> Result<WriteOff>;

    /// Get write-off by ID
    fn get_write_off(&self, id: Uuid) -> Result<Option<WriteOff>>;

    /// List write-offs
    fn list_write_offs(&self, filter: WriteOffFilter) -> Result<Vec<WriteOff>>;

    /// Reverse a write-off
    fn reverse_write_off(&self, id: Uuid) -> Result<WriteOff>;

    // Credit memos
    /// Create a credit memo
    fn create_credit_memo(&self, input: CreateCreditMemo) -> Result<CreditMemo>;

    /// Get credit memo by ID
    fn get_credit_memo(&self, id: Uuid) -> Result<Option<CreditMemo>>;

    /// Get credit memo by number
    fn get_credit_memo_by_number(&self, number: &str) -> Result<Option<CreditMemo>>;

    /// List credit memos
    fn list_credit_memos(&self, filter: CreditMemoFilter) -> Result<Vec<CreditMemo>>;

    /// Apply credit memo to invoice
    fn apply_credit_memo(&self, input: ApplyCreditMemo) -> Result<CreditMemo>;

    /// Void credit memo
    fn void_credit_memo(&self, id: Uuid) -> Result<CreditMemo>;

    /// Get unapplied credit memos for customer
    fn get_unapplied_credits(&self, customer_id: Uuid) -> Result<Vec<CreditMemo>>;

    // Payment application
    /// Apply payment to invoices
    fn apply_payment_to_invoices(
        &self,
        input: ApplyPaymentToInvoices,
    ) -> Result<Vec<ArPaymentApplication>>;

    /// Get payment applications
    fn get_payment_applications(&self, payment_id: Uuid) -> Result<Vec<ArPaymentApplication>>;

    /// Unapply payment from invoice
    fn unapply_payment(&self, application_id: Uuid) -> Result<()>;

    // Customer summaries and statements
    /// Get customer AR summary (None if customer is not found)
    fn get_customer_summary(&self, customer_id: Uuid) -> Result<Option<CustomerArSummary>>;

    /// Generate customer statement
    fn generate_statement(&self, request: GenerateStatementRequest) -> Result<CustomerStatement>;

    // Analytics
    /// Get total AR outstanding
    fn get_total_outstanding(&self) -> Result<rust_decimal::Decimal>;

    /// Get Days Sales Outstanding (DSO)
    fn get_dso(&self, days: i32) -> Result<rust_decimal::Decimal>;

    /// Get average days to pay by customer
    fn get_average_days_to_pay(&self, customer_id: Uuid) -> Result<Option<i32>>;

    // Batch operations
    fn get_customers_batch(&self, ids: Vec<Uuid>) -> Result<Vec<CustomerArSummary>>;
}

// ============================================================================
// General Ledger Repository
// ============================================================================

use chrono::NaiveDate;

/// General Ledger repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait GeneralLedgerRepository: Send + Sync {
    // Chart of Accounts
    /// Create a GL account
    fn create_account(&self, input: CreateGlAccount) -> Result<GlAccount>;

    /// Get account by ID
    fn get_account(&self, id: Uuid) -> Result<Option<GlAccount>>;

    /// Get account by account number
    fn get_account_by_number(&self, account_number: &str) -> Result<Option<GlAccount>>;

    /// Update account
    fn update_account(&self, id: Uuid, input: UpdateGlAccount) -> Result<GlAccount>;

    /// List accounts (Chart of Accounts)
    fn list_accounts(&self, filter: GlAccountFilter) -> Result<Vec<GlAccount>>;

    /// Get account hierarchy (parent-child)
    fn get_account_hierarchy(&self) -> Result<Vec<GlAccount>>;

    /// Delete account (only if no transactions)
    fn delete_account(&self, id: Uuid) -> Result<()>;

    /// Initialize default Chart of Accounts
    fn initialize_chart_of_accounts(&self) -> Result<Vec<GlAccount>>;

    // GL Periods
    /// Create a GL period
    fn create_period(&self, input: CreateGlPeriod) -> Result<GlPeriod>;

    /// Get period by ID
    fn get_period(&self, id: Uuid) -> Result<Option<GlPeriod>>;

    /// Get current open period
    fn get_current_period(&self) -> Result<Option<GlPeriod>>;

    /// Get period for a date
    fn get_period_for_date(&self, date: NaiveDate) -> Result<Option<GlPeriod>>;

    /// List periods
    fn list_periods(&self, filter: GlPeriodFilter) -> Result<Vec<GlPeriod>>;

    /// Open a period
    fn open_period(&self, id: Uuid) -> Result<GlPeriod>;

    /// Close a period
    fn close_period(&self, id: Uuid, closed_by: &str) -> Result<GlPeriod>;

    /// Lock a period (prevents any changes)
    fn lock_period(&self, id: Uuid, locked_by: &str) -> Result<GlPeriod>;

    /// Reopen a closed period (not locked)
    fn reopen_period(&self, id: Uuid) -> Result<GlPeriod>;

    // Journal Entries
    /// Create a journal entry
    fn create_journal_entry(&self, input: CreateJournalEntry) -> Result<JournalEntry>;

    /// Get journal entry by ID
    fn get_journal_entry(&self, id: Uuid) -> Result<Option<JournalEntry>>;

    /// Get journal entry by number
    fn get_journal_entry_by_number(&self, number: &str) -> Result<Option<JournalEntry>>;

    /// List journal entries
    fn list_journal_entries(&self, filter: JournalEntryFilter) -> Result<Vec<JournalEntry>>;

    /// Post a journal entry (update account balances)
    fn post_journal_entry(&self, id: Uuid, posted_by: &str) -> Result<JournalEntry>;

    /// Void a journal entry
    fn void_journal_entry(&self, id: Uuid) -> Result<JournalEntry>;

    /// Reverse a journal entry (creates reversing entry)
    fn reverse_journal_entry(&self, id: Uuid, reversal_date: NaiveDate) -> Result<JournalEntry>;

    /// Get journal entry lines
    fn get_journal_entry_lines(&self, journal_entry_id: Uuid) -> Result<Vec<JournalEntryLine>>;

    // Auto-posting
    /// Get active auto-posting config
    fn get_auto_posting_config(&self) -> Result<Option<AutoPostingConfig>>;

    /// Create/update auto-posting config
    fn set_auto_posting_config(&self, input: CreateAutoPostingConfig) -> Result<AutoPostingConfig>;

    /// Auto-post invoice creation (DR AR / CR Revenue)
    fn auto_post_invoice(&self, invoice_id: InvoiceId) -> Result<JournalEntry>;

    /// Auto-post payment received (DR Cash / CR AR)
    fn auto_post_payment_received(&self, payment_id: Uuid) -> Result<JournalEntry>;

    /// Auto-post bill creation (DR Expense / CR AP)
    fn auto_post_bill(&self, bill_id: Uuid) -> Result<JournalEntry>;

    /// Auto-post bill payment (DR AP / CR Cash)
    fn auto_post_bill_payment(&self, payment_id: Uuid) -> Result<JournalEntry>;

    /// Auto-post inventory cost transaction (DR/CR Inventory/COGS)
    fn auto_post_inventory_cost(&self, cost_transaction_id: Uuid) -> Result<JournalEntry>;

    /// Auto-post write-off (DR Bad Debt / CR AR)
    fn auto_post_write_off(&self, write_off_id: Uuid) -> Result<JournalEntry>;

    // Financial Reports
    /// Generate trial balance
    fn get_trial_balance(&self, as_of_date: NaiveDate) -> Result<TrialBalance>;

    /// Generate balance sheet
    fn get_balance_sheet(&self, as_of_date: NaiveDate) -> Result<BalanceSheet>;

    /// Generate income statement
    fn get_income_statement(
        &self,
        start_date: NaiveDate,
        end_date: NaiveDate,
    ) -> Result<IncomeStatement>;

    /// Get account balance (None if account is not found)
    fn get_account_balance(
        &self,
        account_id: Uuid,
        as_of_date: Option<NaiveDate>,
    ) -> Result<Option<rust_decimal::Decimal>>;

    /// Get account transaction history
    fn get_account_transactions(
        &self,
        account_id: Uuid,
        filter: JournalEntryFilter,
    ) -> Result<Vec<JournalEntryLine>>;

    // Period close process
    /// Run period close (creates closing entries)
    fn run_period_close(&self, period_id: Uuid, closed_by: &str) -> Result<JournalEntry>;

    // Batch operations
    fn create_accounts_batch(&self, inputs: Vec<CreateGlAccount>)
    -> Result<BatchResult<GlAccount>>;
    fn get_accounts_batch(&self, ids: Vec<Uuid>) -> Result<Vec<GlAccount>>;
}

// ============================================================================
// Vector Search Repository
// ============================================================================

/// Vector search repository trait for semantic similarity search
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait VectorRepository: Send + Sync {
    /// Store embedding for an entity
    fn store_embedding(
        &self,
        entity_type: EntityType,
        entity_id: &str,
        embedding: &[f32],
        text_hash: &str,
        model: &str,
    ) -> Result<()>;

    /// Search similar products by embedding vector
    fn search_products(
        &self,
        embedding: &[f32],
        limit: usize,
    ) -> Result<Vec<VectorSearchResult<Product>>>;

    /// Search similar customers by embedding vector
    fn search_customers(
        &self,
        embedding: &[f32],
        limit: usize,
    ) -> Result<Vec<VectorSearchResult<Customer>>>;

    /// Search similar orders by embedding vector
    fn search_orders(
        &self,
        embedding: &[f32],
        limit: usize,
    ) -> Result<Vec<VectorSearchResult<Order>>>;

    /// Search similar inventory items by embedding vector
    fn search_inventory(
        &self,
        embedding: &[f32],
        limit: usize,
    ) -> Result<Vec<VectorSearchResult<InventoryItem>>>;

    /// Delete embedding for an entity
    fn delete_embedding(&self, entity_type: EntityType, entity_id: &str) -> Result<()>;

    /// Check if entity has an embedding stored
    fn has_embedding(&self, entity_type: EntityType, entity_id: &str) -> Result<bool>;

    /// Get embedding metadata for an entity
    fn get_embedding_metadata(
        &self,
        entity_type: EntityType,
        entity_id: &str,
    ) -> Result<Option<EmbeddingMetadata>>;

    /// Get embedding statistics
    fn get_stats(&self) -> Result<EmbeddingStats>;

    /// Delete all embeddings for an entity type
    fn clear_embeddings(&self, entity_type: EntityType) -> Result<u64>;
}

// ============================================================================
// X402 Payment Intent Repository
// ============================================================================

/// X402 Payment Intent repository trait for off-chain payment signing
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait X402PaymentIntentRepository: Send + Sync {
    /// Create a new x402 payment intent
    fn create(&self, input: CreateX402PaymentIntent) -> Result<X402PaymentIntent>;

    /// Get payment intent by ID
    fn get(&self, id: Uuid) -> Result<Option<X402PaymentIntent>>;

    /// Get payment intent by idempotency key
    fn get_by_idempotency_key(&self, key: &str) -> Result<Option<X402PaymentIntent>>;

    /// Sign a payment intent (records signature and public key)
    fn sign(&self, id: Uuid, input: SignX402PaymentIntent) -> Result<X402PaymentIntent>;

    /// Mark intent as sequenced (submitted to sequencer)
    fn mark_sequenced(
        &self,
        id: Uuid,
        sequence_number: u64,
        batch_id: Uuid,
    ) -> Result<X402PaymentIntent>;

    /// Mark intent as settled (confirmed on-chain)
    fn mark_settled(&self, id: Uuid, tx_hash: &str, block_number: u64)
    -> Result<X402PaymentIntent>;

    /// Mark intent as failed
    fn mark_failed(&self, id: Uuid, reason: &str) -> Result<X402PaymentIntent>;

    /// Mark intent as expired
    fn mark_expired(&self, id: Uuid) -> Result<X402PaymentIntent>;

    /// Cancel a payment intent (only if not yet sequenced)
    fn cancel(&self, id: Uuid) -> Result<X402PaymentIntent>;

    /// Get payment intents for a cart
    fn for_cart(&self, cart_id: Uuid) -> Result<Vec<X402PaymentIntent>>;

    /// Get payment intents for an order
    fn for_order(&self, order_id: Uuid) -> Result<Vec<X402PaymentIntent>>;

    /// Get the next nonce for a payer address
    fn get_next_nonce(&self, payer_address: &str) -> Result<u64>;

    /// List payment intents with filter
    fn list(&self, filter: X402PaymentIntentFilter) -> Result<Vec<X402PaymentIntent>>;

    /// Count payment intents matching filter
    fn count(&self, filter: X402PaymentIntentFilter) -> Result<u64>;

    /// Expire all intents that have passed their `valid_until` timestamp
    fn expire_stale_intents(&self) -> Result<u64>;

    // === Batch Operations ===

    /// Create multiple payment intents - partial success allowed
    fn create_batch(
        &self,
        inputs: Vec<CreateX402PaymentIntent>,
    ) -> Result<BatchResult<X402PaymentIntent>>;

    /// Create multiple payment intents - atomic (all-or-nothing)
    fn create_batch_atomic(
        &self,
        inputs: Vec<CreateX402PaymentIntent>,
    ) -> Result<Vec<X402PaymentIntent>>;

    /// Get multiple payment intents by ID
    fn get_batch(&self, ids: Vec<Uuid>) -> Result<Vec<X402PaymentIntent>>;
}

// ============================================================================
// X402 Credit Repository (Metered Billing)
// ============================================================================

/// X402 credit ledger repository for prepaid balances and metered usage.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait X402CreditRepository: Send + Sync {
    /// Get a credit account for payer/asset/network
    fn get_account(
        &self,
        payer_address: &str,
        asset: X402Asset,
        network: X402Network,
    ) -> Result<Option<X402CreditAccount>>;

    /// Get or create a credit account (balance default = 0)
    fn get_or_create_account(
        &self,
        payer_address: &str,
        asset: X402Asset,
        network: X402Network,
    ) -> Result<X402CreditAccount>;

    /// Get current balance for payer/asset/network
    fn get_balance(
        &self,
        payer_address: &str,
        asset: X402Asset,
        network: X402Network,
    ) -> Result<u64>;

    /// Apply a credit or debit adjustment
    fn adjust_balance(&self, input: X402CreditAdjustment) -> Result<X402CreditTransaction>;

    /// List credit transactions with optional filter
    fn list_transactions(
        &self,
        filter: X402CreditTransactionFilter,
    ) -> Result<Vec<X402CreditTransaction>>;
}

// ============================================================================
// Agent Card Repository
// ============================================================================

/// Agent Card repository trait for AI agent identity and capabilities
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait AgentCardRepository: Send + Sync {
    /// Create a new agent card
    fn create(&self, input: CreateAgentCard) -> Result<AgentCard>;

    /// Get agent card by ID
    fn get(&self, id: Uuid) -> Result<Option<AgentCard>>;

    /// Get agent card by wallet address
    fn get_by_wallet(&self, wallet_address: &str) -> Result<Option<AgentCard>>;

    /// Update an agent card
    fn update(&self, id: Uuid, input: UpdateAgentCard) -> Result<AgentCard>;

    /// Delete an agent card
    fn delete(&self, id: Uuid) -> Result<()>;

    /// List agent cards with filter
    fn list(&self, filter: AgentCardFilter) -> Result<Vec<AgentCard>>;

    /// Count agent cards matching filter
    fn count(&self, filter: AgentCardFilter) -> Result<u64>;

    /// Verify an agent card (set trust level and verification info)
    fn verify(&self, id: Uuid, trust_level: TrustLevel, method: &str) -> Result<AgentCard>;

    /// Suspend an agent card
    fn suspend(&self, id: Uuid, reason: &str) -> Result<AgentCard>;

    /// Reactivate a suspended agent card
    fn reactivate(&self, id: Uuid) -> Result<AgentCard>;

    /// Discover agents with specific capabilities
    fn discover(&self, filter: AgentCardFilter) -> Result<Vec<AgentCard>>;

    // === Batch Operations ===

    /// Create multiple agent cards - partial success allowed
    fn create_batch(&self, inputs: Vec<CreateAgentCard>) -> Result<BatchResult<AgentCard>>;

    /// Create multiple agent cards - atomic (all-or-nothing)
    fn create_batch_atomic(&self, inputs: Vec<CreateAgentCard>) -> Result<Vec<AgentCard>>;

    /// Get multiple agent cards by ID
    fn get_batch(&self, ids: Vec<Uuid>) -> Result<Vec<AgentCard>>;
}

// ============================================================================
// ERC-8004 Agent Identity Repository
// ============================================================================

/// Agent identity registry repository (ERC-8004)
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait AgentIdentityRepository: Send + Sync {
    /// Register a new agent identity
    fn register(&self, input: CreateAgentIdentity) -> Result<AgentIdentity>;

    /// Get identity by agent registry and agent ID
    fn get(&self, agent_registry: &str, agent_id: &str) -> Result<Option<AgentIdentity>>;

    /// Get identity by agent wallet address
    fn get_by_wallet(&self, agent_wallet: &str) -> Result<Option<AgentIdentity>>;

    /// Update agent identity
    fn update(
        &self,
        agent_registry: &str,
        agent_id: &str,
        input: UpdateAgentIdentity,
    ) -> Result<AgentIdentity>;

    /// Set or update agent wallet with proof metadata
    #[allow(clippy::too_many_arguments)]
    fn set_agent_wallet(
        &self,
        agent_registry: &str,
        agent_id: &str,
        agent_wallet: &str,
        proof_type: Option<AgentWalletProofType>,
        proof: Option<&str>,
        proof_chain_id: Option<u64>,
        proof_deadline: Option<DateTime<Utc>>,
    ) -> Result<AgentIdentity>;

    /// Clear agent wallet
    fn clear_agent_wallet(&self, agent_registry: &str, agent_id: &str) -> Result<AgentIdentity>;

    /// List identities with optional filtering
    fn list(&self, filter: AgentIdentityFilter) -> Result<Vec<AgentIdentity>>;

    /// Count identities matching filter
    fn count(&self, filter: AgentIdentityFilter) -> Result<u64>;

    /// Set identity metadata entry
    fn set_metadata(
        &self,
        agent_registry: &str,
        agent_id: &str,
        entry: AgentMetadataEntry,
    ) -> Result<()>;

    /// Get identity metadata entry
    fn get_metadata(
        &self,
        agent_registry: &str,
        agent_id: &str,
        metadata_key: &str,
    ) -> Result<Option<Vec<u8>>>;

    /// Delete identity metadata entry
    fn delete_metadata(
        &self,
        agent_registry: &str,
        agent_id: &str,
        metadata_key: &str,
    ) -> Result<()>;
}

// ============================================================================
// ERC-8004 Reputation Registry
// ============================================================================

/// Reputation feedback registry repository (ERC-8004)
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait AgentReputationRepository: Send + Sync {
    /// Submit feedback for an agent
    fn give_feedback(&self, input: CreateAgentFeedback) -> Result<AgentFeedback>;

    /// Revoke previously submitted feedback
    fn revoke_feedback(
        &self,
        agent_registry: &str,
        agent_id: &str,
        client_address: &str,
        feedback_index: u64,
    ) -> Result<AgentFeedback>;

    /// Read a specific feedback entry
    fn read_feedback(
        &self,
        agent_registry: &str,
        agent_id: &str,
        client_address: &str,
        feedback_index: u64,
    ) -> Result<Option<AgentFeedback>>;

    /// Read feedback entries with filters
    fn read_all_feedback(&self, filter: AgentFeedbackFilter) -> Result<Vec<AgentFeedback>>;

    /// Get feedback summary for an agent (filtered by client addresses + tags)
    fn get_summary(
        &self,
        agent_registry: &str,
        agent_id: &str,
        client_addresses: Vec<String>,
        tag1: Option<String>,
        tag2: Option<String>,
    ) -> Result<FeedbackSummary>;

    /// Append a response to a feedback entry
    fn append_response(&self, input: CreateAgentFeedbackResponse) -> Result<AgentFeedbackResponse>;

    /// Count responses for a feedback entry
    fn get_response_count(
        &self,
        agent_registry: &str,
        agent_id: &str,
        client_address: &str,
        feedback_index: u64,
        responders: Option<Vec<String>>,
    ) -> Result<u64>;

    /// List client addresses that have provided feedback
    fn get_clients(&self, agent_registry: &str, agent_id: &str) -> Result<Vec<String>>;

    /// Get last feedback index for a client/agent pair
    fn get_last_index(
        &self,
        agent_registry: &str,
        agent_id: &str,
        client_address: &str,
    ) -> Result<u64>;
}

// ============================================================================
// ERC-8004 Validation Registry
// ============================================================================

/// Validation registry repository (ERC-8004)
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait AgentValidationRepository: Send + Sync {
    /// Submit a validation request
    fn request_validation(
        &self,
        input: CreateAgentValidationRequest,
    ) -> Result<AgentValidationRequest>;

    /// Record a validation response for a request hash
    fn respond_validation(
        &self,
        request_hash: &str,
        input: CreateAgentValidationResponse,
    ) -> Result<AgentValidationResponse>;

    /// Get latest validation status for a request hash
    fn get_validation_status(&self, request_hash: &str) -> Result<Option<AgentValidationStatus>>;

    /// Get validation summary for an agent
    fn get_summary(
        &self,
        agent_registry: &str,
        agent_id: &str,
        validator_addresses: Option<Vec<String>>,
        tag: Option<String>,
    ) -> Result<ValidationSummary>;

    /// Get all request hashes for an agent
    fn get_agent_validations(&self, agent_registry: &str, agent_id: &str) -> Result<Vec<String>>;

    /// Get all request hashes for a validator
    fn get_validator_requests(&self, validator_address: &str) -> Result<Vec<String>>;
}

// ============================================================================
// A2A Commerce Repository
// ============================================================================

/// A2A (Agent-to-Agent) Commerce repository trait
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait A2ACommerceRepository: Send + Sync {
    // Quote operations
    /// Create a new quote
    fn create_quote(&self, input: CreateA2AQuote) -> Result<SkillQuote>;

    /// Get quote by ID
    fn get_quote(&self, id: Uuid) -> Result<Option<SkillQuote>>;

    /// Get quote by quote number
    fn get_quote_by_number(&self, quote_number: &str) -> Result<Option<SkillQuote>>;

    /// Update quote status
    fn update_quote_status(&self, id: Uuid, status: QuoteStatus) -> Result<SkillQuote>;

    /// List quotes with filter
    fn list_quotes(&self, filter: SkillQuoteFilter) -> Result<Vec<SkillQuote>>;

    /// Count quotes matching filter
    fn count_quotes(&self, filter: SkillQuoteFilter) -> Result<u64>;

    // Purchase operations
    /// Create a new purchase
    fn create_purchase(&self, input: CreateA2APurchase) -> Result<A2APurchase>;

    /// Get purchase by ID
    fn get_purchase(&self, id: Uuid) -> Result<Option<A2APurchase>>;

    /// Get purchase by purchase number
    fn get_purchase_by_number(&self, purchase_number: &str) -> Result<Option<A2APurchase>>;

    /// Update purchase status
    fn update_purchase_status(&self, id: Uuid, status: PurchaseStatus) -> Result<A2APurchase>;

    /// Link purchase to order
    fn link_purchase_to_order(&self, purchase_id: Uuid, order_id: Uuid) -> Result<A2APurchase>;

    /// Confirm delivery
    fn confirm_delivery(
        &self,
        purchase_id: Uuid,
        signature: &str,
        rating: Option<u8>,
        feedback: Option<&str>,
    ) -> Result<A2APurchase>;

    /// List purchases with filter
    fn list_purchases(&self, filter: A2APurchaseFilter) -> Result<Vec<A2APurchase>>;

    /// Count purchases matching filter
    fn count_purchases(&self, filter: A2APurchaseFilter) -> Result<u64>;
}

// ============================================================================
// Custom Objects Repository
// ============================================================================

/// Custom Objects repository trait (custom states / metaobjects).
///
/// Provides a schema-driven custom data system:
/// - Define types (schemas) with typed fields
/// - Create records (instances) that validate against the schema
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait CustomObjectRepository: Send + Sync {
    // ------------------------------------------------------------------------
    // Type (schema) operations
    // ------------------------------------------------------------------------

    fn create_type(&self, input: CreateCustomObjectType) -> Result<CustomObjectType>;

    fn get_type(&self, id: Uuid) -> Result<Option<CustomObjectType>>;

    fn get_type_by_handle(&self, handle: &str) -> Result<Option<CustomObjectType>>;

    fn update_type(&self, id: Uuid, input: UpdateCustomObjectType) -> Result<CustomObjectType>;

    fn list_types(&self, filter: CustomObjectTypeFilter) -> Result<Vec<CustomObjectType>>;

    fn delete_type(&self, id: Uuid) -> Result<()>;

    // ------------------------------------------------------------------------
    // Record operations
    // ------------------------------------------------------------------------

    fn create_object(&self, input: CreateCustomObject) -> Result<CustomObject>;

    fn get_object(&self, id: Uuid) -> Result<Option<CustomObject>>;

    fn get_object_by_handle(
        &self,
        type_handle: &str,
        object_handle: &str,
    ) -> Result<Option<CustomObject>>;

    fn update_object(&self, id: Uuid, input: UpdateCustomObject) -> Result<CustomObject>;

    fn list_objects(&self, filter: CustomObjectFilter) -> Result<Vec<CustomObject>>;

    fn delete_object(&self, id: Uuid) -> Result<()>;
}

// ============================================================================
// New Domain Repository Traits
// ============================================================================

/// Gift card repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait GiftCardRepository: Send + Sync {
    /// Create a new gift card
    fn create(&self, input: CreateGiftCard) -> Result<GiftCard>;

    /// Get gift card by ID
    fn get(&self, id: GiftCardId) -> Result<Option<GiftCard>>;

    /// Get gift card by code
    fn get_by_code(&self, code: &str) -> Result<Option<GiftCard>>;

    /// Update a gift card
    fn update(&self, id: GiftCardId, input: UpdateGiftCard) -> Result<GiftCard>;

    /// List gift cards with filter
    fn list(&self, filter: GiftCardFilter) -> Result<Vec<GiftCard>>;

    /// Charge (debit) a gift card
    fn charge(
        &self,
        id: GiftCardId,
        amount: rust_decimal::Decimal,
        reference_id: Option<String>,
    ) -> Result<GiftCardTransaction>;

    /// Refund (credit) to a gift card
    fn refund(
        &self,
        id: GiftCardId,
        amount: rust_decimal::Decimal,
        reference_id: Option<String>,
    ) -> Result<GiftCardTransaction>;

    /// Disable a gift card
    fn disable(&self, id: GiftCardId) -> Result<GiftCard>;

    /// Get transaction history for a gift card
    fn get_transactions(&self, gift_card_id: GiftCardId) -> Result<Vec<GiftCardTransaction>>;
}

/// Store credit repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait StoreCreditRepository: Send + Sync {
    /// Create a new store credit
    fn create(&self, input: CreateStoreCredit) -> Result<StoreCredit>;

    /// Get store credit by ID
    fn get(&self, id: StoreCreditId) -> Result<Option<StoreCredit>>;

    /// List store credits with filter
    fn list(&self, filter: StoreCreditFilter) -> Result<Vec<StoreCredit>>;

    /// Adjust store credit balance
    fn adjust(&self, id: StoreCreditId, input: AdjustStoreCredit) -> Result<StoreCredit>;

    /// Apply store credit to an order (debit)
    fn apply(
        &self,
        id: StoreCreditId,
        amount: rust_decimal::Decimal,
        reference_id: Option<String>,
    ) -> Result<StoreCreditTransaction>;

    /// Get transaction history for a store credit
    fn get_transactions(
        &self,
        store_credit_id: StoreCreditId,
    ) -> Result<Vec<StoreCreditTransaction>>;
}

/// Customer segment repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait SegmentRepository: Send + Sync {
    /// Create a new segment
    fn create(&self, input: CreateSegment) -> Result<Segment>;

    /// Get segment by ID
    fn get(&self, id: SegmentId) -> Result<Option<Segment>>;

    /// Update a segment
    fn update(&self, id: SegmentId, input: UpdateSegment) -> Result<Segment>;

    /// List segments with filter
    fn list(&self, filter: SegmentFilter) -> Result<Vec<Segment>>;

    /// Delete a segment
    fn delete(&self, id: SegmentId) -> Result<()>;

    /// Add a customer to a static segment
    fn add_member(
        &self,
        segment_id: SegmentId,
        customer_id: CustomerId,
    ) -> Result<SegmentMembership>;

    /// Remove a customer from a static segment
    fn remove_member(&self, segment_id: SegmentId, customer_id: CustomerId) -> Result<()>;

    /// List members of a segment
    fn list_members(
        &self,
        segment_id: SegmentId,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<Vec<SegmentMembership>>;

    /// Check if a customer is a member of a segment
    fn is_member(&self, segment_id: SegmentId, customer_id: CustomerId) -> Result<bool>;

    /// Count members in a segment
    fn count_members(&self, segment_id: SegmentId) -> Result<u64>;
}

/// Shipping zone repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait ShippingZoneRepository: Send + Sync {
    /// Create a new shipping zone
    fn create(&self, input: CreateShippingZone) -> Result<ShippingZone>;

    /// Get shipping zone by ID
    fn get(&self, id: ShippingZoneId) -> Result<Option<ShippingZone>>;

    /// Update a shipping zone
    fn update(&self, id: ShippingZoneId, input: UpdateShippingZone) -> Result<ShippingZone>;

    /// List shipping zones with filter
    fn list(&self, filter: ShippingZoneFilter) -> Result<Vec<ShippingZone>>;

    /// Delete a shipping zone
    fn delete(&self, id: ShippingZoneId) -> Result<()>;

    /// Find zones matching a destination
    fn find_matching_zones(
        &self,
        country: &str,
        region: Option<&str>,
        postal_code: Option<&str>,
    ) -> Result<Vec<ShippingZone>>;
}

/// Zone shipping method repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait ZoneShippingMethodRepository: Send + Sync {
    /// Create a shipping method in a zone
    fn create(&self, input: CreateZoneShippingMethod) -> Result<ZoneShippingMethod>;

    /// Get shipping method by ID
    fn get(&self, id: ShippingMethodId) -> Result<Option<ZoneShippingMethod>>;

    /// List shipping methods with filter
    fn list(&self, filter: ZoneShippingMethodFilter) -> Result<Vec<ZoneShippingMethod>>;

    /// Delete a shipping method
    fn delete(&self, id: ShippingMethodId) -> Result<()>;

    /// Calculate rates for a destination
    fn calculate_rates(&self, request: ZoneShippingRateRequest) -> Result<Vec<ZoneShippingRate>>;
}

/// Product review repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait ReviewRepository: Send + Sync {
    /// Create a new review
    fn create(&self, input: CreateReview) -> Result<Review>;

    /// Get review by ID
    fn get(&self, id: ReviewId) -> Result<Option<Review>>;

    /// Update a review
    fn update(&self, id: ReviewId, input: UpdateReview) -> Result<Review>;

    /// List reviews with filter
    fn list(&self, filter: ReviewFilter) -> Result<Vec<Review>>;

    /// Delete a review
    fn delete(&self, id: ReviewId) -> Result<()>;

    /// Get aggregate review summary for a product
    fn get_summary(&self, product_id: ProductId) -> Result<ReviewSummary>;

    /// Increment the helpful count
    fn mark_helpful(&self, id: ReviewId) -> Result<()>;

    /// Increment the reported count
    fn mark_reported(&self, id: ReviewId) -> Result<()>;
}

/// Wishlist repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait WishlistRepository: Send + Sync {
    /// Create a new wishlist
    fn create(&self, input: CreateWishlist) -> Result<Wishlist>;

    /// Get wishlist by ID
    fn get(&self, id: WishlistId) -> Result<Option<Wishlist>>;

    /// Update wishlist metadata
    fn update(&self, id: WishlistId, input: UpdateWishlist) -> Result<Wishlist>;

    /// List wishlists with filter
    fn list(&self, filter: WishlistFilter) -> Result<Vec<Wishlist>>;

    /// Delete a wishlist
    fn delete(&self, id: WishlistId) -> Result<()>;

    /// Add an item to a wishlist
    fn add_item(&self, wishlist_id: WishlistId, item: AddWishlistItem) -> Result<WishlistItem>;

    /// Remove an item from a wishlist
    fn remove_item(&self, wishlist_id: WishlistId, product_id: ProductId) -> Result<()>;
}

/// Loyalty program repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait LoyaltyProgramRepository: Send + Sync {
    /// Create a new loyalty program
    fn create(&self, input: CreateLoyaltyProgram) -> Result<LoyaltyProgram>;

    /// Get loyalty program by ID
    fn get(&self, id: LoyaltyProgramId) -> Result<Option<LoyaltyProgram>>;

    /// List all loyalty programs
    fn list(&self) -> Result<Vec<LoyaltyProgram>>;

    /// Enroll a customer in a program
    fn enroll(&self, input: EnrollCustomer) -> Result<LoyaltyAccount>;

    /// Get a loyalty account
    fn get_account(&self, id: LoyaltyAccountId) -> Result<Option<LoyaltyAccount>>;

    /// Get loyalty account by customer and program
    fn get_account_by_customer(
        &self,
        customer_id: CustomerId,
        program_id: LoyaltyProgramId,
    ) -> Result<Option<LoyaltyAccount>>;

    /// List loyalty accounts with filter
    fn list_accounts(&self, filter: LoyaltyAccountFilter) -> Result<Vec<LoyaltyAccount>>;

    /// Adjust points on an account (earn, redeem, etc.)
    fn adjust_points(&self, input: AdjustPoints) -> Result<LoyaltyTransaction>;

    /// Get transaction history for an account
    fn get_transactions(
        &self,
        account_id: LoyaltyAccountId,
        limit: Option<u32>,
    ) -> Result<Vec<LoyaltyTransaction>>;
}

/// Reward catalog repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait RewardRepository: Send + Sync {
    /// Create a new reward
    fn create(&self, input: CreateReward) -> Result<Reward>;

    /// Get reward by ID
    fn get(&self, id: RewardId) -> Result<Option<Reward>>;

    /// List rewards with filter
    fn list(&self, filter: RewardFilter) -> Result<Vec<Reward>>;

    /// Delete a reward
    fn delete(&self, id: RewardId) -> Result<()>;
}

/// Fraud detection repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait FraudRepository: Send + Sync {
    /// Create a fraud assessment for an order
    fn create_assessment(&self, input: CreateFraudAssessment) -> Result<FraudAssessment>;

    /// Get fraud assessment for an order
    fn get_assessment(&self, order_id: OrderId) -> Result<Option<FraudAssessment>>;

    /// List fraud assessments with filter
    fn list_assessments(&self, filter: FraudAssessmentFilter) -> Result<Vec<FraudAssessment>>;

    /// Update assessment after manual review
    fn review_assessment(
        &self,
        order_id: OrderId,
        decision: FraudDecision,
        reviewer: String,
        notes: Option<String>,
    ) -> Result<FraudAssessment>;

    /// Create a fraud rule
    fn create_rule(&self, input: CreateFraudRule) -> Result<FraudRule>;

    /// Get a fraud rule by ID
    fn get_rule(&self, id: FraudRuleId) -> Result<Option<FraudRule>>;

    /// Update a fraud rule
    fn update_rule(&self, id: FraudRuleId, input: UpdateFraudRule) -> Result<FraudRule>;

    /// List fraud rules with filter
    fn list_rules(&self, filter: FraudRuleFilter) -> Result<Vec<FraudRule>>;

    /// Delete a fraud rule
    fn delete_rule(&self, id: FraudRuleId) -> Result<()>;

    /// Get all enabled rules
    fn get_active_rules(&self) -> Result<Vec<FraudRule>>;
}

/// Search configuration repository trait.
#[auto_impl::auto_impl(&, Box, Arc)]
pub trait SearchConfigRepository: Send + Sync {
    /// Create a search configuration
    fn create(&self, input: CreateSearchConfig) -> Result<SearchConfig>;

    /// Get search configuration by ID
    fn get(&self, id: SearchConfigId) -> Result<Option<SearchConfig>>;

    /// Update a search configuration
    fn update(&self, id: SearchConfigId, input: UpdateSearchConfig) -> Result<SearchConfig>;

    /// List search configurations with filter
    fn list(&self, filter: SearchConfigFilter) -> Result<Vec<SearchConfig>>;

    /// Delete a search configuration
    fn delete(&self, id: SearchConfigId) -> Result<()>;

    /// Get the currently active search configuration
    fn get_active(&self) -> Result<Option<SearchConfig>>;

    /// Set a configuration as active (deactivating any current one)
    fn set_active(&self, id: SearchConfigId) -> Result<SearchConfig>;
}