mako-markt 0.15.0

Market data library for German energy market (MaKo/marktd)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
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
#![allow(clippy::doc_markdown)]
//! Repository traits for all `marktd` aggregate types.
//!
//! Every trait has exactly two implementations:
//! - Production: `Pg*Repository` in `services/marktd/src/pg/`
//! - Testing: `InMemory*` in `crates/mako-markt/src/testing.rs` (feature = "testing")
//!
//! All methods are `async` (AFIT, stable since Rust 1.75).
//! All methods return `Result<_, MdmError>` annotated `#[must_use]`.

use rubo4e::current::Lokationstyp;
use serde::{Deserialize, Serialize};
use time::Date;
use uuid::Uuid;

use crate::{
    domain::{MaloId, MarktpartnerId, MeloId, ProcessStatus, Sparte},
    error::MdmError,
};

// ── Serde default helpers ─────────────────────────────────────────────────────

/// Default value for `updated_at` serde fields: UNIX epoch (1970-01-01T00:00:00Z).
/// Used when a PUT request body omits the field (server overwrites it on upsert).
fn unix_epoch() -> time::OffsetDateTime {
    time::OffsetDateTime::UNIX_EPOCH
}

// ── Date serde helpers (ISO 8601 "YYYY-MM-DD" ↔ time::Date) ─────────────────
mod date_iso {
    use serde::{Deserialize, Deserializer, Serializer};
    use time::Date;
    use time::macros::format_description;

    #[expect(clippy::trivially_copy_pass_by_ref)]
    pub fn serialize<S: Serializer>(date: &Date, s: S) -> Result<S::Ok, S::Error> {
        let fmt = format_description!("[year]-[month]-[day]");
        s.serialize_str(&date.format(fmt).map_err(serde::ser::Error::custom)?)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Date, D::Error> {
        let raw = String::deserialize(d)?;
        let fmt = format_description!("[year]-[month]-[day]");
        Date::parse(&raw, fmt).map_err(serde::de::Error::custom)
    }

    pub mod opt {
        use serde::{Deserialize, Deserializer, Serializer};
        use time::Date;
        use time::macros::format_description;

        #[expect(clippy::trivially_copy_pass_by_ref, clippy::ref_option)]
        pub fn serialize<S: Serializer>(date: &Option<Date>, s: S) -> Result<S::Ok, S::Error> {
            match date {
                Some(d) => {
                    let fmt = format_description!("[year]-[month]-[day]");
                    s.serialize_some(&d.format(fmt).map_err(serde::ser::Error::custom)?)
                }
                None => s.serialize_none(),
            }
        }

        pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Date>, D::Error> {
            let raw: Option<String> = Option::deserialize(d)?;
            match raw {
                Some(s) => {
                    let fmt = format_description!("[year]-[month]-[day]");
                    Date::parse(&s, fmt)
                        .map(Some)
                        .map_err(serde::de::Error::custom)
                }
                None => Ok(None),
            }
        }
    }
}

// ── Type aliases ──────────────────────────────────────────────────────────────

/// Full BO4E `MARKTLOKATION` payload (stored as JSONB; returned as-is to callers).
pub type MaloPayload = serde_json::Value;
/// Full BO4E `MESSLOKATION` payload.
pub type MeloPayload = serde_json::Value;

/// Default BO4E schema version used by `#[serde(default = ...)]` on record
/// structs. Returns `"v202607.0.0"` so that records written before M5
/// (the `bo4e_version` migration) are read as the baseline version.
fn default_bo4e_version() -> String {
    "v202607.0.0".to_owned()
}

// ── MaLo ─────────────────────────────────────────────────────────────────────

/// Point-in-time market-role assignment (`rollenzuordnung`) for a `MARKTLOKATION`:
/// which Marktpartner (NB, LF, MSB, …) holds which role, and for which validity
/// period.
///
/// The `malo_id` is implicit (always the parent `MaloRecord.malo_id`) and
/// is therefore not repeated here.
///
/// **Not** the BO4E `Lokationszuordnung` business object — that BO models the
/// MaLo/MeLo/NeLo/TR/SR location-bundle *graph* and lives in
/// [`LokationszuordnungEdge`] (table `lokationszuordnungen`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Rollenzuordnung {
    pub zuordnungstyp: String,
    pub rollencodenummer: String,
    #[serde(with = "date_iso")]
    pub valid_from: Date,
    #[serde(default, with = "date_iso::opt")]
    pub valid_to: Option<Date>,
}

/// Stored MaLo record as returned by repository reads.
///
/// `rollenzuordnung` contains only the role assignments valid at the
/// `at` date passed to `MaloRepository::find` / `MaloRepository::list`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaloRecord {
    pub malo_id: MaloId,
    pub sparte: Sparte,
    /// Voltage/pressure level extracted from `Marktlokation.netzebene` (e.g. `"NS"`, `"MS"`).
    /// `None` when the incoming BO4E payload did not carry the field.
    pub netzebene: Option<String>,
    /// Bilanzierungsgebiet EIC code (`LOC+237` in UTILMD) extracted from `Marktlokation`.
    /// Used by `processd` NB check 4 as fallback when `malo_grid` is not populated.
    pub bilanzierungsgebiet: Option<String>,
    /// Gas quality extracted from `Marktlokation.standorteigenschaften.gasqualitaet`.
    ///
    /// Canonical form: `"H_GAS"` | `"L_GAS"` | `"H2_BLEND"` | `"BIOGAS"` | `"FLUESSIGGAS"`.
    ///
    /// Legacy values received via UTILMD G (`"HGas"`, `"LGas"`) are normalized to
    /// the canonical form on write via `mako_geli_gas::gas_quality::normalize_gasqualitaet()`.
    ///
    /// Used for:
    /// - Gas tariff routing in `billingd` (Brennwert/Zustandszahl defaults differ by quality)
    /// - Invoice audit annotation (`ZusatzAttribut.gasqualitaet` per § 147 AO / GoBD)
    /// - H2-blend detection for future DVGW G 260 billing compliance
    pub gasqualitaet: Option<String>,
    /// Energy direction (`Aussp` = generation, `Einsp` = consumption).
    pub energierichtung: Option<String>,
    /// Billing mode extracted from `Marktlokation.bilanzierungsmethode`.
    ///
    /// Values: `RLM` | `SLP` | `TLP_GEMEINSAM` | `TLP_GETRENNT` | `PAUSCHAL` | `IMS`.
    /// `RLM` → `netzbilanzd` must include Leistungspreis position (`spitzenleistung_kw` required).
    /// `SLP` → Arbeitspreis only; no `spitzenleistung_kw`.
    pub bilanzierungsmethode: Option<String>,
    /// Regelzone EIC code extracted from `Marktlokation.regelzone`.
    ///
    /// Maps the MaLo to an ÜNB (Transmission System Operator) for:
    /// - MABIS IFTSTA 21000 routing (Bilanzkreisabrechnung Strom, BKV↔ÜNB)
    /// - Redispatch 2.0 `Stammdaten` forwarding (VNB → ÜNB)
    pub regelzone: Option<String>,
    /// Gas GaBi RLM Fallgruppe — **denormalised current-value derived from the
    /// BO4E [`BilanzierungRecord`] resource** (`fallgruppenzuordnung`), which is
    /// the authoritative, temporal home. Unlike `bilanzierungsmethode`/
    /// `bilanzierungsgebiet` (genuine `Marktlokation` fields, BO #12), the GaBi
    /// Fallgruppe is a `Bilanzierung` field (BO #3, absent from `Marktlokation`);
    /// writing a Bilanzierung syncs this column.
    ///
    /// Values: `"GABI_RLM_MIT_TAGESBAND"` | `"GABI_RLM_OHNE_TAGESBAND"` |
    /// `"GABI_RLM_IM_NOMINIERUNGSERSATZVERFAHREN"`.
    ///
    /// Determines the GaBi billing category for Gas RLM MaLos.
    /// Required for `netzbilanzd` Gas MMM settlement routing.
    pub fallgruppe: Option<String>,
    /// Lokationsbündel object code extracted from
    /// `Marktlokation.lokationsbuendelObjektcode` — groups the locations that
    /// are bundled for market communication (UTILMD Lokationsbündelstruktur).
    #[serde(default)]
    pub lokationsbuendel_objektcode: Option<String>,
    /// §14a EnWG „Status der Fernsteuerbarkeit" of the Marktlokation.
    ///
    /// Extracted from UTILMD SG10 `CCI+7037`: `Z97` (technisch fernsteuerbar) →
    /// `true`, `Z96` (technisch nicht fernsteuerbar) → `false`. `None` when the
    /// message did not carry the characteristic. Relevant for the §14a EnWG
    /// netzorientierte Steuerung of controllable consumption devices.
    #[serde(default)]
    pub fernsteuerbar: Option<bool>,
    pub version: i64,
    pub data: MaloPayload,
    /// Role assignments valid at the requested reference date.
    pub rollenzuordnung: Vec<Rollenzuordnung>,
    pub updated_at: time::OffsetDateTime,
    /// BO4E schema version of the `data` payload (e.g. `"v202607.0.0"`).
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
}

/// Stored MeLo record.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeloRecord {
    pub melo_id: MeloId,
    pub malo_id: Option<MaloId>,
    /// Voltage/pressure level at the metering point, extracted from `Messlokation.netzebene_messung`.
    pub netzebene_messung: Option<String>,
    /// Regelzone EIC code extracted from
    /// `Messlokation.standorteigenschaften.eigenschaftenStrom[0].regelzone`.
    ///
    /// Maps this MeLo to the \u00dcNB (Transmission System Operator) for:
    /// - Redispatch 2.0 `Stammdaten` forwarding (VNB \u2192 \u00dcNB)
    /// - MABIS IFTSTA 21000 routing (Bilanzkreisabrechnung Strom, BKV\u2194\u00dcNB)
    pub regelzone: Option<String>,
    /// Full BO4E `Standorteigenschaften` payload as JSONB.
    ///
    /// Contains `StandorteigenschaftenStrom` (regelzone, bilanzierungsgebietEic)
    /// and `StandorteigenschaftenGas` (druckstufe). Required for:
    /// - Redispatch 2.0 `NetworkConstraintDocument` cross-references
    /// - Gas billing zone assignment (`druckstufe`) for GeLi Gas MMM
    /// - netz-checker check 5 (Bilanzierungszone at MeLo level)
    pub standorteigenschaften: Option<serde_json::Value>,
    /// Lokationsbündel object code extracted from
    /// `Messlokation.lokationsbuendelObjektcode` (UTILMD Lokationsbündelstruktur).
    #[serde(default)]
    pub lokationsbuendel_objektcode: Option<String>,
    pub version: i64,
    pub data: MeloPayload,
    pub updated_at: time::OffsetDateTime,
    /// BO4E schema version of the `data` payload.
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
}

/// Stored webhook subscription.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Subscription {
    pub subscriber_id: String,
    pub webhook_url: String,
    /// Stored encrypted at rest by the repository implementation.
    pub webhook_secret: Option<String>,
    /// Empty = all roles.
    pub roles: Vec<String>,
    /// Empty = all event types.
    pub event_types: Vec<String>,
    /// Empty = all Sparten.
    pub sparten: Vec<String>,
    pub active: bool,
    pub version: i64,
}

/// Stored trading-partner record.
///
/// `gln` holds the 13-digit `MarktpartnerId` (Rollencodenummer).  The field
/// name `gln` is kept for backward-compatibility with the PostgreSQL column
/// name and existing EDIFACT serialization; semantically this value is a
/// Marktpartner-ID, which may be a BDEW-Codenummer, DVGW-Codenummer, or a
/// GS1 GLN — use [`crate::domain::nad_agency_code`] to determine the coding
/// authority.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PartnerRecord {
    /// 13-digit Marktpartner-ID.
    pub mp_id: MarktpartnerId,
    pub display_name: Option<String>,
    /// BO4E market role (serialises as the BDEW code, e.g. `"LF"`, `"NB"`, `"MSB"`).
    pub marktrolle: Option<rubo4e::current::Marktrolle>,
    pub sparte: Option<Sparte>,
    /// Coding authority: `BDEW` | `DVGW` | `GLN` (BO4E `Rollencodetyp`).
    /// Derived from the MP-ID prefix; stored for fast AS4 routing lookups.
    pub rollencodetyp: Option<rubo4e::current::Rollencodetyp>,
    /// AS4 endpoint URL list from `Marktteilnehmer.makoadresse`.
    /// Used by `makod` for dynamic AS4 destination routing.
    pub makoadresse: Vec<String>,
    /// Raw JSON for additional channel details (certificate, etc.)
    pub channels: serde_json::Value,
    /// Optimistic-concurrency version.
    #[serde(default)]
    pub version: i64,
    #[serde(default = "unix_epoch", with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
}

impl PartnerRecord {
    /// Present the stored partner as a BO4E `Marktteilnehmer`.
    ///
    /// Field mapping:
    /// - `mp_id` → `rollencodenummer`
    /// - `marktrolle` / `rollencodetyp` → carried as-is (already typed)
    /// - `sparte` → BO4E `Sparte`
    /// - `makoadresse` → `makoadresse` (omitted when empty)
    /// - `display_name` → `geschaeftspartner.organisationsname`
    #[must_use]
    pub fn to_marktteilnehmer(&self) -> rubo4e::current::Marktteilnehmer {
        let geschaeftspartner = self.display_name.as_ref().map(|name| {
            Box::new(rubo4e::current::Geschaeftspartner {
                organisationsname: Some(name.clone()),
                ..Default::default()
            })
        });
        rubo4e::current::Marktteilnehmer {
            rollencodenummer: Some(self.mp_id.clone()),
            marktrolle: self.marktrolle,
            rollencodetyp: self.rollencodetyp,
            sparte: self.sparte.map(|s| match s {
                Sparte::Strom => rubo4e::current::Sparte::Strom,
                Sparte::Gas => rubo4e::current::Sparte::Gas,
            }),
            makoadresse: (!self.makoadresse.is_empty()).then(|| self.makoadresse.clone()),
            geschaeftspartner,
            ..Default::default()
        }
    }
}

/// Process correlation entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CorrelationEntry {
    pub process_id: Uuid,
    pub workflow_name: Option<String>,
    pub pid: Option<i32>,
    pub malo_id: Option<MaloId>,
    pub melo_id: Option<MeloId>,
    pub contract_id: Option<String>,
    pub erp_contract_id: Option<String>,
    pub erp_order_id: Option<String>,
    pub edifact_conv_id: Option<Uuid>,
    pub marktrolle: Option<String>,
    pub format_version: Option<String>,
    pub status: ProcessStatus,
    pub initiated_at: time::OffsetDateTime,
    pub completed_at: Option<time::OffsetDateTime>,
}

// ── Pagination ────────────────────────────────────────────────────────────────

/// A paged collection returned by list operations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PageResult<T> {
    pub items: Vec<T>,
    /// Total matching rows (without pagination).
    pub total: u64,
    /// Zero-based page index.
    pub page: u32,
    /// Page size requested.
    pub size: u32,
}

// ── Query filters ─────────────────────────────────────────────────────────────

/// Filters for `GET /api/v1/malo` listing.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct MaloFilter {
    pub sparte: Option<Sparte>,
    /// Filter by `zuordnungstyp` in active `rollenzuordnung` (e.g. `"NB"`, `"LF"`).
    pub zuordnungstyp: Option<String>,
    /// Filter by `rollencodenummer` (GLN) in active `rollenzuordnung`.
    pub rollencodenummer: Option<String>,
    /// Filter by Gas GaBi RLM Fallgruppe (e.g. `"GABI_RLM_MIT_TAGESBAND"`).
    /// Applies to Gas MaLos only; Strom MaLos have no Fallgruppe.
    pub fallgruppe: Option<String>,
    /// Filter by `bilanzierungsmethode` (e.g. `"RLM"`, `"SLP"`, `"IMS"`).
    pub bilanzierungsmethode: Option<String>,
    /// Filter by `regelzone` EIC code (e.g. `"10YDE-EON------1"`).
    /// Maps to the controlling ÜNB for MABIS IFTSTA and Redispatch 2.0.
    pub regelzone: Option<String>,
    pub page: u32,
    pub size: u32,
}

/// Filters for `GET /api/v1/correlations`.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct CorrelationFilter {
    pub erp_order_id: Option<String>,
    pub malo_id: Option<MaloId>,
    pub status: Option<ProcessStatus>,
}

// ── Traits ────────────────────────────────────────────────────────────────────

/// Read/write access to `MARKTLOKATION` records.
#[allow(async_fn_in_trait)]
/// Lightweight read model returned by `MarktdClient::get_malo`.
///
/// Contains only the typed fields extracted from the `Marktlokation` JSONB — not
/// the full payload. Used by `processd` NB check 4 (Bilanzierungsgebiet) as the
/// primary source before falling back to the `malo_grid` side table.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
pub struct MaloTypedFields {
    pub malo_id: String,
    /// Voltage/pressure level (e.g. `"NS"`, `"MS"`, `"HS"`).
    pub netzebene: Option<String>,
    /// Bilanzierungsgebiet EIC code — primary input for `processd` NB check 4.
    pub bilanzierungsgebiet: Option<String>,
    /// Gas quality — canonical form: `"H_GAS"` | `"L_GAS"` | `"H2_BLEND"` | `"BIOGAS"`.
    ///
    /// Legacy UTILMD G values (`"HGas"`, `"LGas"`) are normalized to the canonical
    /// form by the `marktd` GeLi Gas event handler.
    pub gasqualitaet: Option<String>,
    /// Energy direction (`"Aussp"` = generation, `"Einsp"` = consumption).
    pub energierichtung: Option<String>,
    /// Billing mode — `"SLP"` | `"RLM"` | `"IMS"`.
    ///
    /// Derived from UTILMD `TM+EM` at supply-start and updated by `marktd`
    /// `patch_typenmerkmal()`.  Drives `netzbilanzd` MMM SLP variant selection
    /// (H0/G0/L0) and `processd` NB billing-mode check.
    pub bilanzierungsmethode: Option<String>,
    /// Gas GaBi RLM Fallgruppe.
    pub fallgruppe: Option<String>,
    /// Regelzone EIC code — maps MeLo to ÜNB for Redispatch 2.0 Stammdaten routing.
    pub regelzone: Option<String>,
}

/// A UTILMD Stammdatenänderung applied to the typed MaLo columns.
///
/// Each `Some` field is a new authoritative value from a GPKE Teil 4 / GeLi Gas
/// "Änderung Daten der MaLo" message; each `None` leaves the column untouched.
/// Populated by the `makod` adapter from the UTILMD SG8 `SEQ`/SG10 `CCI`/`CAV`
/// and `TM` segments and carried into the `de.mako.process.completed` payload
/// that `marktd` applies via [`MaloRepository::patch_stammdaten`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MaloStammdatenPatch {
    /// `netzebene` (e.g. `NSP7`).
    pub netzebene: Option<String>,
    /// `bilanzierungsgebiet` EIC.
    pub bilanzierungsgebiet: Option<String>,
    /// Gas quality (`HGAS`/`LGAS`).
    pub gasqualitaet: Option<String>,
    /// `energierichtung` (`AUSSP`/`EINSP`).
    pub energierichtung: Option<String>,
    /// Bilanzierungsmethode (`RLM`/`SLP`/`IMS`/`TLP_*`).
    pub bilanzierungsmethode: Option<String>,
    /// Regelzone EIC (ÜNB assignment).
    pub regelzone: Option<String>,
    /// GaBi RLM Fallgruppe.
    pub fallgruppe: Option<String>,
    /// §14a EnWG „Status der Fernsteuerbarkeit" (`CCI+7037` `Z97`→`true` /
    /// `Z96`→`false`).
    pub fernsteuerbar: Option<bool>,
}

impl MaloStammdatenPatch {
    /// `true` when no column would change.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.netzebene.is_none()
            && self.bilanzierungsgebiet.is_none()
            && self.gasqualitaet.is_none()
            && self.energierichtung.is_none()
            && self.bilanzierungsmethode.is_none()
            && self.regelzone.is_none()
            && self.fallgruppe.is_none()
            && self.fernsteuerbar.is_none()
    }
}

/// Read/write access to `MARKTLOKATION` records.
#[allow(async_fn_in_trait)]
pub trait MaloRepository: Send + Sync {
    /// Insert or update a `MARKTLOKATION`.
    ///
    /// Validates optimistic concurrency via `if_match` (the caller's ETag).
    /// Pass `None` for unconditional upsert (first write).
    ///
    /// Returns the new version number.
    async fn upsert(
        &self,
        malo_id: &MaloId,
        sparte: Sparte,
        data: MaloPayload,
        rollenzuordnung: Vec<Rollenzuordnung>,
        if_match: Option<i64>,
        bo4e_version: &str,
    ) -> Result<i64, MdmError>;

    /// Patch the `bilanzierungsmethode` and/or `fallgruppe` typed columns on an
    /// existing MaLo row **without** touching the JSONB payload or version.
    ///
    /// Called by `marktd` event_ingest when it receives
    /// `de.mako.process.initiated` (PID 55001/44001) carrying
    /// `bilanzierungsmethode` and/or `fallgruppe` extracted from the UTILMD
    /// `TM+EM` / `TM+Z10` segments by the `makod` adapter (L1/N1).
    ///
    /// No-ops silently when the MaLo row does not yet exist — the values will
    /// be set on the first `PUT /api/v1/malo` call instead.
    async fn patch_typenmerkmal(
        &self,
        malo_id: &MaloId,
        bilanzierungsmethode: Option<&str>,
        fallgruppe: Option<&str>,
    ) -> Result<(), MdmError>;

    /// Apply a UTILMD Stammdatenänderung (GPKE Teil 4 / GeLi Gas) to the typed
    /// MaLo columns — the granular counterpart of
    /// [`patch_typenmerkmal`](Self::patch_typenmerkmal) over the full
    /// changeable attribute set.
    ///
    /// Each `Some` field overwrites its column; each `None` leaves it unchanged
    /// (`COALESCE`). The JSONB payload and the optimistic `version` are **not**
    /// touched — a Stammdatenänderung is authoritative master data arriving over
    /// EDIFACT, not an operator edit. Returns `true` when a row was updated and
    /// `false` when the MaLo is not yet known locally (the change is then a
    /// no-op; the row is created by the next `PUT /api/v1/malo`).
    async fn patch_stammdaten(
        &self,
        malo_id: &MaloId,
        patch: &MaloStammdatenPatch,
    ) -> Result<bool, MdmError>;

    /// Return the `MARKTLOKATION` with `rollenzuordnung` valid at `at`.
    ///
    /// `at` defaults to today (German local date).
    async fn find(&self, malo_id: &MaloId, at: Date) -> Result<Option<MaloRecord>, MdmError>;

    /// Return a paged list filtered by the given predicates.
    ///
    /// `at` is the reference date for `rollenzuordnung` validity.
    async fn list(&self, filter: MaloFilter, at: Date) -> Result<PageResult<MaloRecord>, MdmError>;
}

/// A GPKE Teil 4 / GeLi Gas Stammdatenänderung applied to the typed
/// `MESSLOKATION` columns (`LOC+Z17`, „Änderung Daten der MeLo").
///
/// The `makod` adapter builds one object-agnostic attribute map from the SG8
/// `SEQ`/SG10 `CCI`/`CAV` groups; each object's patch struct picks the subset
/// its table can hold via `serde(rename)`. For the MeLo that is (defensively)
/// the metering point's Netzebene (`netzebene` → `netzebene_messung`) and the
/// Regelzone.
///
/// **Verified against UTILMD AHB Strom 2.2 Kap. 9.1.5 (2026-07):** the MeLo
/// Änderungsmeldung (`STS 9013=ZX7`) does **not** carry Netzebene/Regelzone
/// characteristics — its actual payload is the **MSB-Zuordnung** (SG10
/// `CCI 7037=ZB3` Zugeordneter Marktpartner, `CAV 7111=Z91` MSB / `Z39`
/// grundzuständig / `ZF0` gMSB + MP-ID) plus NNE-Abrechnung info. That belongs
/// on the dated `melo_msb_zuordnungen` timeline, not a typed-column `COALESCE`
/// patch, and its GPKE-vs-WiM-MSB-Wechsel semantics make auto-applying it a
/// deliberate follow-up (roadmap). These fields are retained for robustness /
/// forward-compatibility but rarely fire in practice.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MeloStammdatenPatch {
    /// Netzebene at the metering point (generic `netzebene` attribute →
    /// `melo.netzebene_messung`).
    #[serde(rename = "netzebene")]
    pub netzebene_messung: Option<String>,
    /// Regelzone EIC (ÜNB assignment).
    pub regelzone: Option<String>,
}

impl MeloStammdatenPatch {
    /// `true` when no column would change.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.netzebene_messung.is_none() && self.regelzone.is_none()
    }
}

/// Read/write access to `MESSLOKATION` records.
#[allow(async_fn_in_trait)]
pub trait MeloRepository: Send + Sync {
    /// Insert or update a `MESSLOKATION`.
    ///
    /// Returns the new version number.
    async fn upsert(
        &self,
        melo_id: &MeloId,
        malo_id: Option<&MaloId>,
        data: MeloPayload,
        if_match: Option<i64>,
        bo4e_version: &str,
    ) -> Result<i64, MdmError>;

    /// Return the `MESSLOKATION` record.
    async fn find(&self, melo_id: &MeloId) -> Result<Option<MeloRecord>, MdmError>;

    /// Apply a UTILMD Stammdatenänderung (`LOC+Z17`) to the typed MeLo columns —
    /// the MeLo counterpart of [`MaloRepository::patch_stammdaten`].
    ///
    /// Each `Some` field overwrites its column via `COALESCE`; each `None` leaves
    /// it unchanged. The JSONB payload (`data`, `standorteigenschaften`) and the
    /// optimistic `version` are **not** touched. Returns `true` when a row was
    /// updated and `false` when the MeLo is not yet known locally (no-op).
    async fn patch_stammdaten(
        &self,
        melo_id: &MeloId,
        patch: &MeloStammdatenPatch,
    ) -> Result<bool, MdmError>;
}

/// Read/write access to ERP webhook subscriptions.
#[allow(async_fn_in_trait)]
pub trait SubscriptionRepository: Send + Sync {
    /// Insert or update a subscription.
    ///
    /// `webhook_secret` is stored encrypted at rest by the implementation.
    ///
    /// Returns the new version number.
    async fn upsert(&self, sub: Subscription) -> Result<i64, MdmError>;

    /// Return a subscription by subscriber ID.
    async fn find(&self, subscriber_id: &str) -> Result<Option<Subscription>, MdmError>;

    /// List all active subscriptions.
    async fn list_active(&self) -> Result<Vec<Subscription>, MdmError>;

    /// Return all active subscriptions that match a given event type and role.
    ///
    /// Used by the fan-out worker to select delivery targets.
    async fn list_matching(
        &self,
        event_type: &str,
        role: &str,
        sparte: Option<&str>,
    ) -> Result<Vec<Subscription>, MdmError>;
}

/// Read/write access to the process correlation index.
#[allow(async_fn_in_trait)]
pub trait CorrelationIndex: Send + Sync {
    /// Insert a new correlation entry (idempotent — duplicate `process_id` is a no-op).
    async fn insert(&self, entry: CorrelationEntry) -> Result<(), MdmError>;

    /// Update status and `completed_at` for a process.
    async fn update_status(
        &self,
        process_id: Uuid,
        status: ProcessStatus,
        completed_at: Option<time::OffsetDateTime>,
    ) -> Result<(), MdmError>;

    /// Update `edifact_conv_id` when the first `de.mako.*` event is received.
    async fn update_edifact_conv_id(&self, process_id: Uuid, conv_id: Uuid)
    -> Result<(), MdmError>;

    /// Look up by ERP order ID (`Idempotency-Key` from command submission).
    async fn find_by_erp_order_id(
        &self,
        erp_order_id: &str,
    ) -> Result<Option<CorrelationEntry>, MdmError>;

    /// Look up by `process_id`.
    async fn find_by_process_id(
        &self,
        process_id: Uuid,
    ) -> Result<Option<CorrelationEntry>, MdmError>;

    /// Return correlations matching the filter.
    async fn list(&self, filter: CorrelationFilter) -> Result<Vec<CorrelationEntry>, MdmError>;
}

/// Read/write access to the trading-partner directory.
#[allow(async_fn_in_trait)]
pub trait PartnerRepository: Send + Sync {
    /// Insert or update a trading partner.
    ///
    /// Returns the new version number.
    async fn upsert(&self, partner: PartnerRecord) -> Result<i64, MdmError>;

    /// Return a partner by their 13-digit `MarktpartnerId`.
    async fn find(&self, id: &MarktpartnerId) -> Result<Option<PartnerRecord>, MdmError>;

    /// List all partners.
    async fn list(&self) -> Result<Vec<PartnerRecord>, MdmError>;
}

// ── Preisblatt ───────────────────────────────────────────────────────────────

/// Discriminates how a price sheet entered the system.
///
/// Used for audit trails and to enforce operator-override protection:
/// an `Api`-sourced sheet is never silently overwritten by a `Mako` ingest.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PreisblattSource {
    /// Uploaded directly via the REST API (operator batch job or manual override).
    Api,
    /// Ingested automatically from a PRICAT 27003 message by the mako engine.
    Mako,
}

impl std::fmt::Display for PreisblattSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PreisblattSource::Api => f.write_str("api"),
            PreisblattSource::Mako => f.write_str("mako"),
        }
    }
}

impl std::str::FromStr for PreisblattSource {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "api" => Ok(PreisblattSource::Api),
            "mako" => Ok(PreisblattSource::Mako),
            other => Err(format!("unknown PreisblattSource: {other:?}")),
        }
    }
}

/// A stored `PreisblattNetznutzung` record.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PreisblattRecord {
    /// GLN of the NB that published this price sheet.
    pub nb_mp_id: String,
    /// The full BO4E `PreisblattNetznutzung` payload (stored as JSONB).
    pub data: serde_json::Value,
    /// BO4E schema version of `data`.
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
    /// How this record entered the system: `api` (operator upload) or `mako` (engine ingest).
    pub source: PreisblattSource,
    pub created_at: time::OffsetDateTime,
    pub updated_at: time::OffsetDateTime,
}

/// Read/write access to NB price sheets.
#[allow(async_fn_in_trait)]
pub trait PreisblattRepository: Send + Sync {
    /// Upsert a `PreisblattNetznutzung` for the given NB GLN.
    ///
    /// Multiple records per GLN are stored; they are distinguished by the
    /// `gueltigkeit.startdatum` inside `data`.
    ///
    /// `source` tracks how the record entered the system: `Api` for operator
    /// REST uploads, `Mako` for engine-ingested PRICAT 27003 messages.
    /// An `Api`-sourced sheet is never overwritten by a `Mako` ingest unless
    /// `force = true`.
    async fn upsert(
        &self,
        nb_mp_id: &str,
        data: serde_json::Value,
        bo4e_version: &str,
        source: PreisblattSource,
    ) -> Result<(), MdmError>;

    /// Return the price sheet for `nb_mp_id` that was valid on `billing_date`
    /// (ISO 8601 date string, e.g. `"2025-06-15"`).
    ///
    /// Returns `None` when no matching entry is found.
    async fn find_for_date(
        &self,
        nb_mp_id: &str,
        billing_date: &str,
    ) -> Result<Option<PreisblattRecord>, MdmError>;
}

// ── PreisblattMessung (MSB metering price sheets — B5) ───────────────────────

/// A stored `PreisblattMessung` record from the MSB.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PreisblattMessungRecord {
    /// MP-ID (BDEW-Codenummer) of the Messstellenbetreiber that published this sheet.
    pub msb_mp_id: String,
    /// The full BO4E `PreisblattMessung` payload (stored as JSONB).
    pub data: serde_json::Value,
    /// BO4E schema version of `data`.
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
    /// How this record entered the system: `api` (operator upload) or `mako` (engine ingest).
    pub source: PreisblattSource,
    /// Optional `AufAbschlag` list from the MSB PRICAT 27001–27003.
    ///
    /// `AufAbschlag` entries describe conditional price supplements and discounts
    /// (§14a ToU discounts, time-variable surcharges, etc.).  Each entry is a
    /// `rubo4e::current::AufAbschlag` JSONB object.
    ///
    /// `None` when the PRICAT does not carry any `AufAbschlag` entries (most
    /// conventional meters).  `invoic-checker` uses this field to validate
    /// whether a discount position in INVOIC 31009 is contractually authorised.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub auf_abschlaege: Vec<serde_json::Value>,
    pub created_at: time::OffsetDateTime,
    pub updated_at: time::OffsetDateTime,
}

/// Read/write access to MSB (Messstellenbetreiber) metering price sheets.
///
/// Used by `invoicd` for PID 31009 (`MSB-Rechnung`) tariff plausibility checks:
/// positions 4 (Grundpreis Messung) and 5 (Arbeitspreis Messung).
///
/// Source: WiM AHB BK6-24-174.
#[allow(async_fn_in_trait)]
pub trait PreisblattMessungRepository: Send + Sync {
    /// Upsert a `PreisblattMessung` for the given MSB MP-ID.
    ///
    /// Conflicts on `(msb_mp_id, valid_from)` perform an in-place update.
    /// An `Api`-sourced sheet is never overwritten by a `Mako` ingest.
    async fn upsert_messung(
        &self,
        msb_mp_id: &str,
        data: serde_json::Value,
        bo4e_version: &str,
        source: PreisblattSource,
    ) -> Result<(), MdmError>;

    /// Return the `PreisblattMessung` for `msb_mp_id` valid on `billing_date`
    /// (ISO 8601 date string, e.g. `"2025-06-15"`).
    ///
    /// Returns `None` when no matching entry is found.
    async fn find_messung_for_date(
        &self,
        msb_mp_id: &str,
        billing_date: &str,
    ) -> Result<Option<PreisblattMessungRecord>, MdmError>;
}

// ── PreisblattKonzessionsabgabe (B3) ─────────────────────────────────────────

/// A stored `PreisblattKonzessionsabgabe` record.
///
/// KAV §2 requires the NB to include Konzessionsabgabe (KA) as a separate
/// tariff position in every NNE invoice. `kundengruppe_ka` differentiates between
/// Tarifkunden and Sondervertragskunden.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PreisblattKaRecord {
    /// NB MP-ID (BDEW-Codenummer) that published this price sheet.
    pub nb_mp_id: String,
    /// Energy commodity (`STROM` or `GAS`).
    pub sparte: String,
    /// Customer group classification — `None` means applies to all groups.
    pub kundengruppe_ka: Option<String>,
    /// The full BO4E `PreisblattKonzessionsabgabe` payload.
    pub data: serde_json::Value,
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
    /// How this record entered the system.
    pub source: PreisblattSource,
    pub created_at: time::OffsetDateTime,
    pub updated_at: time::OffsetDateTime,
}

/// Read/write access to `PreisblattKonzessionsabgabe` records.
///
/// Used by `netzbilanzd` for INVOIC 31001/31002 KA tariff positions.
#[allow(async_fn_in_trait)]
pub trait PreisblattKaRepository: Send + Sync {
    /// Upsert a `PreisblattKonzessionsabgabe` for the given NB MP-ID.
    ///
    /// Conflicts on `(nb_mp_id, sparte, kundengruppe_ka, valid_from)` are updated in-place.
    /// `Api`-sourced sheets are never overwritten by `Mako` ingests.
    async fn upsert_ka(
        &self,
        nb_mp_id: &str,
        sparte: &str,
        kundengruppe_ka: Option<&str>,
        data: serde_json::Value,
        bo4e_version: &str,
        source: PreisblattSource,
    ) -> Result<(), MdmError>;

    /// Return the `PreisblattKonzessionsabgabe` valid on `billing_date` for the NB.
    ///
    /// Returns `None` when no matching entry is found.
    async fn find_ka_for_date(
        &self,
        nb_mp_id: &str,
        sparte: &str,
        kundengruppe_ka: Option<&str>,
        billing_date: &str,
    ) -> Result<Option<PreisblattKaRecord>, MdmError>;
}

// ── PreisblattDienstleistung (MSB service price sheets) ──────────────────────

/// A stored `PreisblattDienstleistung` record.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PreisblattDienstleistungRecord {
    pub msb_mp_id: String,
    pub data: serde_json::Value,
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
    pub source: PreisblattSource,
    pub created_at: time::OffsetDateTime,
    pub updated_at: time::OffsetDateTime,
}

/// Read/write access to MSB service price sheets.
///
/// Used by `invoic-checker` for INVOIC 31009 service position validation
/// and by `mako-wim` REQOTE/QUOTES (PIDs 35001–35005).
#[allow(async_fn_in_trait)]
pub trait PreisblattDienstleistungRepository: Send + Sync {
    async fn upsert_dienstleistung(
        &self,
        msb_mp_id: &str,
        data: serde_json::Value,
        bo4e_version: &str,
        source: PreisblattSource,
    ) -> Result<(), MdmError>;

    async fn find_dienstleistung_for_date(
        &self,
        msb_mp_id: &str,
        billing_date: &str,
    ) -> Result<Option<PreisblattDienstleistungRecord>, MdmError>;
}

// ── PreisblattHardware (MSB hardware rental price sheets) ────────────────────

/// A stored `PreisblattHardware` record.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PreisblattHardwareRecord {
    pub msb_mp_id: String,
    pub data: serde_json::Value,
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
    pub source: PreisblattSource,
    pub created_at: time::OffsetDateTime,
    pub updated_at: time::OffsetDateTime,
}

/// Read/write access to MSB hardware rental price sheets.
///
/// Required for NB → MSB settlement INVOIC 31009 hardware positions.
/// `invoic-checker` check 5 cannot validate hardware positions without it.
#[allow(async_fn_in_trait)]
pub trait PreisblattHardwareRepository: Send + Sync {
    async fn upsert_hardware(
        &self,
        msb_mp_id: &str,
        data: serde_json::Value,
        bo4e_version: &str,
        source: PreisblattSource,
    ) -> Result<(), MdmError>;

    async fn find_hardware_for_date(
        &self,
        msb_mp_id: &str,
        billing_date: &str,
    ) -> Result<Option<PreisblattHardwareRecord>, MdmError>;
}

// ── PriCat (versioned PreisblattNetznutzung history + dispatch) ──────────────

/// Dispatch state of a versioned PRICAT snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PriCatDispatchState {
    /// Not yet dispatched to any LF partner.
    Pending,
    /// Dispatch task has picked this version up; may be in-flight.
    Queued,
    /// All active LF partners for this NB have been successfully sent PRICAT 27003.
    Done,
    /// Dispatch failed (see `dispatch_error`); will be retried on next poll.
    Error,
}

impl std::fmt::Display for PriCatDispatchState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Pending => write!(f, "pending"),
            Self::Queued => write!(f, "queued"),
            Self::Done => write!(f, "done"),
            Self::Error => write!(f, "error"),
        }
    }
}

/// A single versioned PRICAT snapshot for an NB GLN.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PriCatVersion {
    /// Surrogate primary key (`UUID v4`).
    pub id: uuid::Uuid,
    /// GLN of the NB that published this price sheet.
    pub nb_mp_id: String,
    /// Tenant GLN (operator).
    pub tenant: String,
    /// Start of the validity period (extracted from `data.gueltigkeit.startdatum`).
    pub valid_from: time::Date,
    /// End of the validity period, `None` means open-ended.
    pub valid_to: Option<time::Date>,
    /// Full BO4E `PreisblattNetznutzung` payload (stored as JSONB).
    pub data: serde_json::Value,
    /// BO4E schema version of `data`.
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
    /// How this version entered the system.
    pub source: PreisblattSource,
    /// Current dispatch state.
    pub dispatch_state: PriCatDispatchState,
    /// Last dispatch error message, if any.
    pub dispatch_error: Option<String>,
    pub created_at: time::OffsetDateTime,
    pub updated_at: time::OffsetDateTime,
}

/// One row in the PRICAT dispatch audit log.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PriCatDispatchEntry {
    pub id: uuid::Uuid,
    pub pricat_version_id: uuid::Uuid,
    pub nb_mp_id: String,
    pub lf_mp_id: String,
    pub tenant: String,
    /// `makod` process ID returned by `MakodClient`, or `None` if dispatch failed.
    pub process_id: Option<uuid::Uuid>,
    pub dispatched_at: time::OffsetDateTime,
    pub outcome: String,
    pub error_detail: Option<String>,
}

/// Read/write access to versioned PRICAT snapshots and the dispatch audit log.
#[allow(async_fn_in_trait)]
pub trait PriCatRepository: Send + Sync {
    /// Insert or update a versioned PRICAT snapshot.
    ///
    /// Conflicts on `(nb_mp_id, tenant, valid_from)` perform an in-place update of
    /// the payload and reset `dispatch_done_at` so the new version is re-dispatched.
    ///
    /// Returns the `UUID` of the upserted row.
    #[allow(clippy::too_many_arguments)]
    async fn upsert_version(
        &self,
        nb_mp_id: &str,
        tenant: &str,
        valid_from: time::Date,
        valid_to: Option<time::Date>,
        data: serde_json::Value,
        bo4e_version: &str,
        source: PreisblattSource,
    ) -> Result<uuid::Uuid, MdmError>;

    /// Return all PRICAT versions for the given NB GLN, newest first.
    async fn list_versions(
        &self,
        nb_mp_id: &str,
        tenant: &str,
    ) -> Result<Vec<PriCatVersion>, MdmError>;

    /// Return the single most-recent PRICAT version for the given NB.
    async fn find_latest(
        &self,
        nb_mp_id: &str,
        tenant: &str,
    ) -> Result<Option<PriCatVersion>, MdmError>;

    /// Return all versions whose dispatch has not yet completed (state ≠ Done).
    async fn list_pending(&self, tenant: &str) -> Result<Vec<PriCatVersion>, MdmError>;

    /// Mark a version as queued for dispatch.
    async fn mark_queued(&self, id: uuid::Uuid) -> Result<(), MdmError>;

    /// Mark a version as fully dispatched (all LF partners reached).
    async fn mark_done(&self, id: uuid::Uuid) -> Result<(), MdmError>;

    /// Mark a version dispatch as failed with an error message.
    async fn mark_error(&self, id: uuid::Uuid, error: &str) -> Result<(), MdmError>;

    /// Append a dispatch audit entry for one NB × LF dispatch attempt.
    async fn log_dispatch(&self, entry: PriCatDispatchEntry) -> Result<(), MdmError>;

    /// Return dispatch log entries for the given PRICAT version.
    async fn dispatch_log(
        &self,
        pricat_version_id: uuid::Uuid,
    ) -> Result<Vec<PriCatDispatchEntry>, MdmError>;
}

// ── NbContract (NB network contracts — typed, not opaque JSONB) ──────────────

/// Billing frequency for NB network contracts.
///
/// Governs when `invoicd` triggers selbstausgestellt INVOIC 31006 MMM billing runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BillingSchedule {
    /// Invoice once per calendar month.
    #[default]
    Monthly,
    /// Invoice every calendar quarter.
    Quarterly,
    /// Invoice once per calendar year.
    Annually,
}

impl std::fmt::Display for BillingSchedule {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Monthly => write!(f, "MONTHLY"),
            Self::Quarterly => write!(f, "QUARTERLY"),
            Self::Annually => write!(f, "ANNUALLY"),
        }
    }
}

impl std::str::FromStr for BillingSchedule {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_uppercase().as_str() {
            "MONTHLY" => Ok(Self::Monthly),
            "QUARTERLY" => Ok(Self::Quarterly),
            "ANNUALLY" => Ok(Self::Annually),
            other => Err(format!("unknown BillingSchedule '{other}'")),
        }
    }
}

impl BillingSchedule {
    /// Infallible parse; returns `Monthly` on unknown input.
    #[must_use]
    pub fn from_str_or_default(s: &str) -> Self {
        s.parse().unwrap_or_default()
    }
}

/// A typed NB (Netzbetreiber) network contract record.
///
/// Unlike LF supply contracts (stored as opaque `JSONB`), NB contracts are
/// fully typed so that `invoicd` can query by
/// `netzebene` and `bilanzierungsmethode` without JSON path expressions.
///
/// Stored in the `nb_contracts` table.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NbContractRecord {
    /// ERP contract number or UUID.
    pub contract_id: String,
    /// 11-digit Marktlokations-ID.
    pub malo_id: crate::domain::MaloId,
    /// 13-digit BDEW/DVGW GLN of the Netzbetreiber.
    pub nb_mp_id: String,
    /// Energy commodity.
    pub sparte: crate::domain::Sparte,
    /// Voltage / pressure level: `NS` | `MS` | `MSP` | `HSP` | `HS` | `HöS` | `HöS/HS`
    /// (Gas: `GND` / `GMT` / `GHD`).
    pub netzebene: String,
    /// Metering / balancing method: `RLM` | `SLP` | `IMS` | `TLP_GEMEINSAM` | …
    pub bilanzierungsmethode: String,
    /// How often the NB bills for network usage.
    pub billing_schedule: BillingSchedule,
    /// Start of contract validity (local date in MEZ/MESZ).
    #[serde(with = "date_iso")]
    pub valid_from: time::Date,
    /// End of contract validity (`None` = currently active).
    #[serde(with = "date_iso::opt")]
    pub valid_to: Option<time::Date>,
    /// Full BO4E `Vertrag` payload (L1 — digital LRV exchange).
    ///
    /// `_typ` is auto-injected to `"VERTRAG"` on write.
    /// Rows created before L1 have `'{}'` (empty); re-PUT to populate.
    #[serde(default)]
    pub data: serde_json::Value,
    /// Contract type extracted from `data["vertragsart"]`.
    /// Default: `NETZNUTZUNGSVERTRAG`.
    #[serde(default)]
    pub vertragsart: Option<String>,
    /// Contract lifecycle status extracted from `data["vertragsstatus"]`.
    /// Default: `AKTIV`.
    #[serde(default)]
    pub vertragsstatus: Option<String>,
    /// Tenant ID for multi-tenant deployments.
    pub tenant: String,
    /// Optimistic-concurrency version counter.
    pub version: i64,
}

/// CRUD repository for NB network contracts.
#[allow(async_fn_in_trait)]
pub trait NbContractRepository: Send + Sync {
    /// Upsert a NB contract record.  Returns the new version number.
    #[must_use]
    async fn upsert(&self, rec: NbContractRecord) -> Result<i64, MdmError>;

    /// Find a contract by `contract_id`.
    #[must_use]
    async fn find(&self, contract_id: &str) -> Result<Option<NbContractRecord>, MdmError>;

    /// Find the contract active on `date` for `malo_id` within `tenant`.
    ///
    /// Returns the most recent contract whose `valid_from ≤ date < valid_to`
    /// (or `valid_to IS NULL`).
    #[must_use]
    async fn find_active(
        &self,
        malo_id: &str,
        date: time::Date,
        tenant: &str,
    ) -> Result<Option<NbContractRecord>, MdmError>;

    /// List all NB contracts for a given `nb_mp_id` and `tenant`.
    #[must_use]
    async fn list_by_nb(
        &self,
        nb_mp_id: &str,
        tenant: &str,
    ) -> Result<Vec<NbContractRecord>, MdmError>;
}

// ── VersorgungsStatus ─────────────────────────────────────────────────────────

/// Supply status of a Marktlokation.
///
/// Derived from `de.mako.process.completed` events by `marktd`'s
/// `event_ingest` handler and persisted in the `versorgungsstatus` table.
/// One row per MaLo per tenant — upserted on each relevant process completion.
///
/// Used by `processd` (M17) to drive fully-automated LFA E_0624 responses
/// without ERP involvement (GPKE Teil 1 §5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum LieferStatus {
    /// Active supply — an LF is assigned to this MaLo.
    Beliefert,
    /// No supply — after Lieferende or before first Lieferbeginn.
    Unbeliefert,
    /// Basic supply under §36 EnWG (Grundversorgung).
    Grundversorgung,
    /// Emergency supply under §38 EnWG (Ersatzversorgung, max 3 months).
    Ersatzversorgung,
    /// MaKo participation suspended (Ruhend).
    Ruhend,
    /// Decommissioned — no further MaKo processes possible.
    Stillgelegt,
}

impl std::fmt::Display for LieferStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Beliefert => write!(f, "Beliefert"),
            Self::Unbeliefert => write!(f, "Unbeliefert"),
            Self::Grundversorgung => write!(f, "Grundversorgung"),
            Self::Ersatzversorgung => write!(f, "Ersatzversorgung"),
            Self::Ruhend => write!(f, "Ruhend"),
            Self::Stillgelegt => write!(f, "Stillgelegt"),
        }
    }
}

impl std::str::FromStr for LieferStatus {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "Beliefert" => Ok(Self::Beliefert),
            "Unbeliefert" => Ok(Self::Unbeliefert),
            "Grundversorgung" => Ok(Self::Grundversorgung),
            "Ersatzversorgung" => Ok(Self::Ersatzversorgung),
            "Ruhend" => Ok(Self::Ruhend),
            "Stillgelegt" => Ok(Self::Stillgelegt),
            other => Err(format!("unknown LieferStatus '{other}'")),
        }
    }
}

/// Per-MaLo supply state record persisted in `marktd`.
///
/// One row per `(malo_id, tenant)`. Upserted atomically on each relevant
/// `de.mako.process.completed` event with optimistic concurrency control
/// (`WHERE version = $expected`). On conflict: read-retry once (at-least-once
/// EventBus delivery guarantees convergence).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersorgungsStatusRecord {
    /// 11-digit Marktlokations-ID.
    pub malo_id: MaloId,
    /// Current supply state.
    pub lieferstatus: LieferStatus,
    /// GLN of the active Lieferant (set when `lieferstatus == Beliefert`).
    pub lf_mp_id: Option<String>,
    /// MP-ID of the announced future Lieferant (post UTILMD 55001/44001, pre confirmation).
    ///
    /// At most ONE pending Lieferbeginn per MaLo at any time — the NB rejects a second
    /// 55001 with GPKE rule A06 while `lf_mp_id_next IS NOT NULL`.
    pub lf_mp_id_next: Option<String>,
    /// Announced Lieferbeginn date of the future Lieferant — set together with `lf_mp_id_next`.
    ///
    /// Together these two fields form the complete "pending transition" record: WHO takes
    /// over (`lf_mp_id_next`) and WHEN (`lf_next_lieferbeginn`).  Both are cleared atomically
    /// when the transition is confirmed (55003/44003) or rejected (55004/44004).
    ///
    /// Used by the NB to schedule Ersatz/Grundversorgung gap-closure (§38 EnWG) and by
    /// `netzbilanzd` for billing-period alignment.
    #[serde(default, with = "date_iso::opt")]
    pub lf_next_lieferbeginn: Option<Date>,
    /// Agreed Lieferbeginn date (set when supply is confirmed).
    #[serde(default, with = "date_iso::opt")]
    pub lieferbeginn: Option<Date>,
    /// Agreed Lieferende date (set when termination is initiated).
    #[serde(default, with = "date_iso::opt")]
    pub lieferende: Option<Date>,
    /// GLN of the active Messstellenbetreiber.
    pub msb_mp_id: Option<String>,
    /// GLN of the Netzbetreiber responsible for this MaLo.
    pub nb_mp_id: String,
    /// Start date of the running Ersatz-/Grundversorgung (§38/§36 EnWG).
    ///
    /// Set by `begin_eog_supply` when `lieferstatus` transitions to
    /// `Ersatzversorgung` or `Grundversorgung`; cleared on any other
    /// transition. For `Ersatzversorgung` this anchors the statutory
    /// 3-month maximum (§38 Abs. 2 EnWG) enforced by the `processd`
    /// EoG timer.
    #[serde(default, with = "date_iso::opt")]
    pub eog_seit: Option<Date>,
    /// `process_id` of the last process that triggered a state change.
    pub last_process_id: Option<Uuid>,
    /// Last time this record was updated (RFC 3339).
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
    /// Tenant identifier — data-isolation key written to every database row.
    ///
    /// Typically the operator's BDEW- or DVGW-Codenummer, but any stable unique
    /// string is valid (UUID, slug, etc.).  This is **not** a GLN.
    ///
    /// Not returned in API responses: `marktd` is a single-tenant daemon — every
    /// SQL query is already scoped by `AppState::tenant_gln`, so the client only
    /// ever sees their own data and the value is implicit from the server config.
    #[serde(skip_serializing, default)]
    pub tenant: String,
    /// Optimistic concurrency version; incremented on each update.
    pub version: i64,
}

/// Single entry in the supply-state change history of a MaLo.
///
/// Populated by `VersorgungsStatusRepository::upsert` — each successful write
/// appends one row to `versorgungsstatus_history`.  Used by
/// `GET /api/v1/versorgung/{malo_id}/history` and the `?at=YYYY-MM-DD`
/// point-in-time query.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersorgungsStatusHistoryRecord {
    /// Auto-incremented surrogate key (`BIGSERIAL`).
    pub id: i64,
    pub malo_id: MaloId,
    pub tenant: String,
    pub lieferstatus: LieferStatus,
    pub lf_mp_id: Option<String>,
    pub lf_mp_id_next: Option<String>,
    #[serde(default, with = "date_iso::opt")]
    pub lf_next_lieferbeginn: Option<Date>,
    #[serde(default, with = "date_iso::opt")]
    pub lieferbeginn: Option<Date>,
    #[serde(default, with = "date_iso::opt")]
    pub lieferende: Option<Date>,
    pub msb_mp_id: Option<String>,
    pub nb_mp_id: String,
    pub last_process_id: Option<Uuid>,
    /// Version of the `versorgungsstatus` row that this snapshot captures.
    pub version: i64,
    /// UTC instant when this state became active (set when the upsert commits).
    pub valid_from: time::OffsetDateTime,
}

/// Read/write access to `VersorgungsStatus` records.
///
/// Exactly one row per `(malo_id, tenant)`. All writes use optimistic
/// concurrency — callers must supply the version observed during the
/// last read. A `MdmError::Conflict` response means a concurrent update
/// won; retry after re-reading.
///
/// Every successful `upsert` atomically appends a row to
/// `versorgungsstatus_history`, enabling point-in-time queries via `find_at`.
#[allow(async_fn_in_trait)]
pub trait VersorgungsStatusRepository: Send + Sync {
    /// Insert (version 1) or update a `VersorgungsStatus` record.
    ///
    /// `if_version` is the caller's expected current version.
    /// Pass `None` on first insert.  Returns the new version.
    ///
    /// Returns `MdmError::Conflict` when `if_version` does not match the
    /// stored version (optimistic locking violation).
    ///
    /// Every successful write appends one row to `versorgungsstatus_history`.
    #[must_use]
    async fn upsert(
        &self,
        rec: VersorgungsStatusRecord,
        if_version: Option<i64>,
    ) -> Result<i64, MdmError>;

    /// Return the current `VersorgungsStatus` for a MaLo, or `None` if unknown.
    #[must_use]
    async fn find(
        &self,
        malo_id: &MaloId,
        tenant: &str,
    ) -> Result<Option<VersorgungsStatusRecord>, MdmError>;

    /// Return the supply state as it was on the given calendar date (German local
    /// time, i.e. CET/CEST).
    ///
    /// Uses the `versorgungsstatus_history` table. Returns `None` when no
    /// history exists on or before `at`.
    ///
    /// The SQL equivalent:
    /// ```sql
    /// SELECT * FROM versorgungsstatus_history
    /// WHERE malo_id = $1 AND tenant = $2
    ///   AND (valid_from AT TIME ZONE 'Europe/Berlin')::date <= $at
    /// ORDER BY valid_from DESC LIMIT 1
    /// ```
    #[must_use]
    async fn find_at(
        &self,
        malo_id: &MaloId,
        tenant: &str,
        at: Date,
    ) -> Result<Option<VersorgungsStatusRecord>, MdmError>;

    /// Return the full supply-state change history for a MaLo, newest first.
    ///
    /// Backed by the `versorgungsstatus_history` table.
    #[must_use]
    async fn find_history(
        &self,
        malo_id: &MaloId,
        tenant: &str,
        page: u32,
        size: u32,
    ) -> Result<PageResult<VersorgungsStatusHistoryRecord>, MdmError>;

    /// Return all records for a tenant (used for bulk replay / re-projection).
    #[must_use]
    async fn list_by_tenant(
        &self,
        tenant: &str,
        page: u32,
        size: u32,
    ) -> Result<PageResult<VersorgungsStatusRecord>, MdmError>;

    /// Record an announced incoming Lieferant (partial update).
    ///
    /// Called when a UTILMD 55001/44001 (`de.mako.process.initiated`, NB side)
    /// is received.  Sets `lf_mp_id_next` and `lf_next_lieferbeginn` without
    /// touching `lieferstatus`, `lf_mp_id`, `lieferbeginn`, or `lieferende`.
    ///
    /// Inserts a new row as `Unbeliefert` if none exists yet for this MaLo.
    /// Appends to `versorgungsstatus_history` on every successful write.
    #[must_use]
    async fn announce_lf_next(
        &self,
        malo_id: &MaloId,
        tenant: &str,
        lf_mp_id_next: &str,
        lf_next_lieferbeginn: Option<Date>,
        nb_mp_id: &str,
        process_id: Option<Uuid>,
    ) -> Result<(), MdmError>;

    /// Promote the announced future Lieferant to the active one.
    ///
    /// Called when UTILMD 55003/44003 (`de.mako.process.completed`, NB side)
    /// is sent.  Atomically:
    /// - `lf_mp_id = lf_mp_id_next`
    /// - `lieferbeginn = lf_next_lieferbeginn`
    /// - `lieferstatus = Beliefert`
    /// - `lf_mp_id_next = NULL`, `lf_next_lieferbeginn = NULL`
    ///
    /// No-ops if `lf_mp_id_next` is already `NULL` (idempotent re-delivery).
    /// Appends to `versorgungsstatus_history` on every successful write.
    #[must_use]
    async fn confirm_supply(
        &self,
        malo_id: &MaloId,
        tenant: &str,
        process_id: Option<Uuid>,
    ) -> Result<(), MdmError>;

    /// Mark a MaLo as `Unbeliefert` while preserving any pending announcement.
    ///
    /// Called when UTILMD 55013/44013 (`de.mako.process.completed`) is processed.
    /// The active LF has ended supply; clears `lf_mp_id` and `lieferbeginn` but
    /// leaves `lf_mp_id_next` / `lf_next_lieferbeginn` intact so a pending future
    /// Lieferant announcement is not lost.
    ///
    /// The NB is responsible for activating Ersatz/Grundversorgung (§38 EnWG)
    /// when `lieferstatus` becomes `Unbeliefert` and no `lf_mp_id_next` is set.
    /// Appends to `versorgungsstatus_history` on every successful write.
    #[must_use]
    async fn end_supply(
        &self,
        malo_id: &MaloId,
        tenant: &str,
        nb_mp_id: &str,
        process_id: Option<Uuid>,
    ) -> Result<(), MdmError>;

    /// Clear a pending future-Lieferant announcement without touching the
    /// active supply.
    ///
    /// Invoked when a Lieferbeginn is cancelled or rejected (GPKE 55004 /
    /// GeLi Gas 44004): the previously announced `lf_mp_id_next` /
    /// `lf_next_lieferbeginn` must be reset so downstream consumers do not act
    /// on a supplier switch that will not happen. Idempotent: a no-op when no
    /// pending announcement exists.
    async fn clear_lf_next(
        &self,
        malo_id: &MaloId,
        tenant: &str,
        process_id: Option<Uuid>,
    ) -> Result<(), MdmError>;

    /// Record the start of the statutory fallback supply (§38/§36 EnWG).
    ///
    /// Called when the EoG Zuordnung completes (UTILMD 55013/44013
    /// `de.mako.process.completed`): the Grundversorger becomes the supplier
    /// of record. Atomically sets
    /// - `lieferstatus = Ersatzversorgung` or `Grundversorgung`
    ///   (`eog_status` must be one of the two; any other value is an error),
    /// - `lf_mp_id = gv_mp_id`, `lieferbeginn = eog_seit`,
    /// - `eog_seit = start of the fallback supply` (anchors the §38 Abs. 2
    ///   3-month maximum for `Ersatzversorgung`),
    ///
    /// while preserving `lf_mp_id_next` / `lf_next_lieferbeginn` — a pending
    /// regular supplier switch ends the fallback supply on confirmation.
    /// Appends to `versorgungsstatus_history` on every successful write.
    #[must_use]
    #[allow(clippy::too_many_arguments)] // regulatory transition carries its full context
    async fn begin_eog_supply(
        &self,
        malo_id: &MaloId,
        tenant: &str,
        gv_mp_id: &str,
        nb_mp_id: &str,
        eog_status: LieferStatus,
        eog_seit: Option<Date>,
        process_id: Option<Uuid>,
    ) -> Result<(), MdmError>;
}

// ── Grundversorger (§36 EnWG) ─────────────────────────────────────────────────

/// The Grundversorger determined for a Netzgebiet per §36 Abs. 2 EnWG.
///
/// The supplier with the most Haushaltskunden in the Netzgebiet, festgestellt
/// by the NB every three years. Master data — maintained by the operator (or
/// an import), read by the `processd` gap-closure automation to address the
/// UTILMD 55013/44013 EoG Zuordnung.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GrundversorgerRecord {
    /// GLN of the Netzbetreiber whose Netzgebiet this entry covers.
    pub nb_mp_id: String,
    /// Commodity.
    pub sparte: Sparte,
    /// MP-ID of the Grundversorger (the LF addressed by the EoG Zuordnung).
    pub gv_mp_id: String,
    /// Date of the §36 Abs. 2 Feststellung (three-year cycle).
    #[serde(default, with = "date_iso::opt")]
    pub festgestellt_am: Option<Date>,
    /// Pre-deposited default Bilanzkreis for the E/G Zuordnung (GPKE Teil 4
    /// „Übermittlung von Informationen"). When an EoG completes without the
    /// E/G supplying its own Bilanzkreis in time (`ZugeordnetOhneAntwort`),
    /// this BK is the one the NB balances the MaLo against. `None` if the E/G
    /// has not deposited one.
    #[serde(default)]
    pub default_bilanzkreis: Option<String>,
    /// Last time this record was updated (RFC 3339).
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
    /// Tenant identifier (not serialized in API responses).
    #[serde(skip_serializing, default)]
    pub tenant: String,
}

/// Repository for the per-Netzgebiet Grundversorger determination (§36 EnWG).
#[allow(async_fn_in_trait)]
pub trait GrundversorgerRepository: Send + Sync {
    /// Fetch the Grundversorger for a Netzbetreiber and Sparte.
    async fn find(
        &self,
        tenant: &str,
        nb_mp_id: &str,
        sparte: Sparte,
    ) -> Result<Option<GrundversorgerRecord>, MdmError>;

    /// Insert or update the Grundversorger entry.
    async fn upsert(&self, record: &GrundversorgerRecord) -> Result<(), MdmError>;
}

// ── MSB-Zuordnung je Messlokation (dated timeline) ────────────────────────────

/// One dated MSB assignment for a Messlokation.
///
/// The per-MeLo MSB timeline is the authoritative source for point-in-time MSB
/// resolution — a WiM Teil 2 historical Werteanfrage (UC 4.1.1) must address the
/// MSB that served the MeLo **at the target period**, which MaLo-level MSB data
/// cannot answer when a MaLo bundles MeLos with divergent MSB history.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeloMsbZuordnung {
    /// Messlokations-ID.
    pub melo_id: String,
    /// GLN of the Messstellenbetreiber.
    pub msb_mp_id: String,
    /// Assignment start (inclusive).
    #[serde(with = "date_iso")]
    pub valid_from: Date,
    /// Assignment end (exclusive); `None` = currently valid.
    #[serde(default, with = "date_iso::opt")]
    pub valid_to: Option<Date>,
    /// Tenant identifier (not serialized in API responses).
    #[serde(skip_serializing, default)]
    pub tenant: String,
}

/// Repository for the per-Messlokation dated MSB timeline (WiM Teil 2 UC 4.1.1).
#[allow(async_fn_in_trait)]
pub trait MeloMsbRepository: Send + Sync {
    /// Record a new MSB assignment effective `valid_from`, closing the
    /// previously-open assignment (`valid_to = valid_from`) atomically. A
    /// re-assignment on an existing `valid_from` overwrites that row.
    async fn assign_msb(
        &self,
        tenant: &str,
        melo_id: &str,
        msb_mp_id: &str,
        valid_from: Date,
    ) -> Result<(), MdmError>;

    /// The MSB responsible for `melo_id` on `at` (point-in-time). `None` when no
    /// assignment covers the date.
    async fn find_msb_at(
        &self,
        tenant: &str,
        melo_id: &str,
        at: Date,
    ) -> Result<Option<String>, MdmError>;

    /// Full assignment history for a MeLo, newest first.
    async fn history(&self, tenant: &str, melo_id: &str)
    -> Result<Vec<MeloMsbZuordnung>, MdmError>;
}

// ── Bilanzierung (BO4E BO #3) ──────────────────────────────────────────────────

/// A BO4E `Bilanzierung` — the balancing-relevant data of a Marktlokation, as a
/// first-class resource with **identity and temporal validity**.
///
/// This subsumes the balancing concept otherwise smeared across `MaloRecord`
/// columns (`bilanzierungsmethode`, `fallgruppe`, `bilanzierungsgebiet` — kept as
/// denormalised current-values) together with the load profile (Prognosegrundlage).
/// The full BO4E object lives in [`Self::data`]; the typed fields are extracted
/// for indexing and query.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BilanzierungRecord {
    /// Marktlokations-ID this Bilanzierung belongs to (BO4E `marktlokationsId`).
    pub malo_id: String,
    /// Validity start (BO4E `bilanzierungsbeginn`).
    #[serde(with = "time::serde::rfc3339")]
    pub bilanzierungsbeginn: time::OffsetDateTime,
    /// Validity end, exclusive (BO4E `bilanzierungsende`). `None` = open-ended.
    #[serde(default, with = "time::serde::rfc3339::option")]
    pub bilanzierungsende: Option<time::OffsetDateTime>,
    /// Bilanzkreis EIC (BO4E `bilanzkreis`).
    #[serde(default)]
    pub bilanzkreis: Option<String>,
    /// Aggregationsverantwortung (`NB` / `ÜNB`).
    #[serde(default)]
    pub aggregationsverantwortung: Option<String>,
    /// Prognosegrundlage (`SLP` / `Prognose` / …).
    #[serde(default)]
    pub prognosegrundlage: Option<String>,
    /// GaBi Fallgruppenzuordnung.
    #[serde(default)]
    pub fallgruppenzuordnung: Option<String>,
    /// Full BO4E `Bilanzierung` object (round-trip-preserving).
    pub data: serde_json::Value,
    /// BO4E schema version the `data` was written against.
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
    /// Tenant identifier (not serialized in API responses).
    #[serde(skip_serializing, default)]
    pub tenant: String,
    /// Last update (RFC 3339).
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
}

/// Repository for the first-class temporal BO4E `Bilanzierung` resource.
#[allow(async_fn_in_trait)]
pub trait BilanzierungRepository: Send + Sync {
    /// Insert or update the Bilanzierung effective `bilanzierungsbeginn`; the
    /// natural key is `(tenant, malo_id, bilanzierungsbeginn)`.
    async fn upsert(&self, record: &BilanzierungRecord) -> Result<(), MdmError>;

    /// The Bilanzierung effective for `malo_id` at instant `at` (point-in-time):
    /// the newest one whose validity window contains `at`. `None` when none.
    async fn find_at(
        &self,
        tenant: &str,
        malo_id: &str,
        at: time::OffsetDateTime,
    ) -> Result<Option<BilanzierungRecord>, MdmError>;

    /// Full Bilanzierung history for a MaLo, newest validity-start first.
    async fn history(
        &self,
        tenant: &str,
        malo_id: &str,
    ) -> Result<Vec<BilanzierungRecord>, MdmError>;
}

// ── Netz-Element-Lokation (NeLo) ──────────────────────────────────────────────

/// Stored NeLo record.
///
/// A Netz-Element-Lokation (NeLo) is a network element location used in
/// BDEW Redispatch 2.0 processes.  The `nelo_id` is typically a 16-char
/// EIC code (ENTSO-E, NAD DE3055 = `ZEW`) or a 13-digit BDEW Codenummer.
///
/// Source: BDEW Redispatch 2.0 Implementierungsleitfaden v2.x.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NeLoRecord {
    /// EIC or BDEW Codenummer.
    pub nelo_id: String,
    pub tenant: String,
    /// Human-readable Bezeichnung.
    pub name: Option<String>,
    pub sparte: Sparte,
    /// Voltage / pressure level (`NS`, `MS`, …, `HöS/HS`).
    pub netzebene: Option<String>,
    /// Owning Netzbetreiber GLN.
    pub nb_mp_id: String,
    /// Whether this NeLo can be remote-controlled (Redispatch 2.0 `steuerkanal`).
    ///
    /// Required by DELORD/DELRES topology queries.
    pub steuerkanal: Option<bool>,
    /// `eigenschaftMsbLokation` — which Marktrolle is responsible for MSB at this NeLo.
    ///
    /// E.g. `"NB"` (grundzuständiger MSB = NB) or `"MSB"` (wechselbar).
    /// Used for WiM Gas gMSB routing.
    pub eigenschaft_msb_lokation: Option<String>,
    /// `grundzustaendigerMsbCodenr` — gMSB MP-ID (13-digit BDEW/DVGW Codenummer).
    pub grundzustaendiger_msb_codenr: Option<String>,
    /// Additional Redispatch 2.0 attributes (open-ended JSONB).
    pub data: serde_json::Value,
    pub version: i64,
    pub updated_at: time::OffsetDateTime,
}

/// A GPKE Teil 4 Stammdatenänderung applied to the typed `NETZLOKATION`
/// columns (`LOC+Z18`, „Änderung Daten der NeLo", §14a/Redispatch).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NeloStammdatenPatch {
    /// Voltage / pressure level (`netzebene` → `nelo.netzebene`).
    pub netzebene: Option<String>,
    /// §14a EnWG Steuerkanal presence (`nelo.steuerkanal`), from UTILMD
    /// `CCI+7059=Z49` / `CCI+7037` `ZF3` (vorhanden → `true`) / `ZF2` (kein → `false`).
    pub steuerkanal: Option<bool>,
}

impl NeloStammdatenPatch {
    /// `true` when no column would change.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.netzebene.is_none() && self.steuerkanal.is_none()
    }
}

/// Read/write access to `NeLo` records.
///
/// One row per `(nelo_id, tenant)`.
/// Writes use optimistic concurrency via `if_match` (ETag header version).
#[allow(async_fn_in_trait)]
pub trait NeLoRepository: Send + Sync {
    /// Insert or update a NeLo record.
    ///
    /// `if_match` = `None` for unconditional upsert (first write).
    /// Returns the new version number.
    #[must_use]
    async fn upsert(&self, rec: NeLoRecord, if_match: Option<i64>) -> Result<i64, MdmError>;

    /// Return a NeLo by `nelo_id`, or `None` if not found.
    #[must_use]
    async fn find(&self, nelo_id: &str, tenant: &str) -> Result<Option<NeLoRecord>, MdmError>;

    /// Apply a UTILMD Stammdatenänderung (`LOC+Z18`) to the typed NeLo columns.
    ///
    /// `COALESCE` per column; the JSONB payload and `version` are untouched.
    /// Returns `true` when a row was updated, `false` when the NeLo is unknown.
    async fn patch_stammdaten(
        &self,
        nelo_id: &str,
        tenant: &str,
        patch: &NeloStammdatenPatch,
    ) -> Result<bool, MdmError>;

    /// Return all NeLos owned by a Netzbetreiber GLN.
    #[must_use]
    async fn list_by_nb(
        &self,
        nb_mp_id: &str,
        tenant: &str,
        page: u32,
        size: u32,
    ) -> Result<PageResult<NeLoRecord>, MdmError>;

    /// Return all NeLos for a tenant (paged).
    #[must_use]
    async fn list_by_tenant(
        &self,
        tenant: &str,
        page: u32,
        size: u32,
    ) -> Result<PageResult<NeLoRecord>, MdmError>;
}

// ── Tranche ──────────────────────────────────────────────────────────────────

/// Stored Tranche record.
///
/// A **Tranche** is a share of a Marktlokation's energy assigned to a distinct
/// balancing responsibility (BO4E `Tranche`; GPKE Teil 4 „Daten der Tranche",
/// PIDs 55619/55642/55652/55662/55686). One row per `(tranche_id, tenant)`; the
/// parent MaLo is recorded for `list_by_malo` grouping.
///
/// Source: GPKE Teil 4 (BK6-24-174) §1.4; BO4E `Tranche`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrancheRecord {
    /// Tranche identifier (e.g. `<MaLo>-T01`).
    pub tranche_id: String,
    pub tenant: String,
    /// Parent Marktlokation this Tranche belongs to.
    pub malo_id: Option<String>,
    /// Bilanzierungsgebiet EIC (`LOC+237`).
    pub bilanzierungsgebiet: Option<String>,
    /// Netzebene (`netzebene`).
    pub netzebene: Option<String>,
    /// Energierichtung (`EINSPEISUNG` / `ENTNAHME`).
    pub energierichtung: Option<String>,
    /// Full BO4E `Tranche` payload (open-ended JSONB).
    pub data: serde_json::Value,
    pub version: i64,
    pub updated_at: time::OffsetDateTime,
}

/// A GPKE Teil 4 Stammdatenänderung applied to the typed `TRANCHE` columns
/// (`LOC+Z21`, „Änderung Daten der Tranche").
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TrancheStammdatenPatch {
    /// Bilanzierungsgebiet EIC.
    pub bilanzierungsgebiet: Option<String>,
    /// Netzebene.
    pub netzebene: Option<String>,
    /// Energierichtung.
    pub energierichtung: Option<String>,
}

impl TrancheStammdatenPatch {
    /// `true` when no column would change.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.bilanzierungsgebiet.is_none()
            && self.netzebene.is_none()
            && self.energierichtung.is_none()
    }
}

/// Read/write access to `Tranche` records.
///
/// One row per `(tranche_id, tenant)`.
#[allow(async_fn_in_trait)]
pub trait TrancheRepository: Send + Sync {
    /// Insert or update a Tranche record. `if_match` = `None` for unconditional
    /// upsert. Returns the new version number.
    async fn upsert(&self, rec: TrancheRecord, if_match: Option<i64>) -> Result<i64, MdmError>;

    /// Return a Tranche by `tranche_id`, or `None` if not found.
    async fn find(&self, tranche_id: &str, tenant: &str)
    -> Result<Option<TrancheRecord>, MdmError>;

    /// Return all Tranchen of a Marktlokation (paged).
    async fn list_by_malo(
        &self,
        malo_id: &str,
        tenant: &str,
        page: u32,
        size: u32,
    ) -> Result<PageResult<TrancheRecord>, MdmError>;

    /// Apply a UTILMD Stammdatenänderung (`LOC+Z21`) to the typed Tranche
    /// columns. `COALESCE` per column; JSONB and `version` untouched. Returns
    /// `true` when a row was updated, `false` when the Tranche is unknown.
    async fn patch_stammdaten(
        &self,
        tranche_id: &str,
        tenant: &str,
        patch: &TrancheStammdatenPatch,
    ) -> Result<bool, MdmError>;
}

/// Convenience bundle of all repositories, passed to handlers via `Arc<AppState<...>>`.
///
/// Uses concrete generic parameters (same pattern as `mako-engine`'s `EngineContext`)
/// so all trait methods are statically dispatched — AFIT is **not** dyn-compatible.
///
/// `services/marktd` instantiates this with the Postgres implementations:
/// ```text
/// AppState<PgMaloRepo, PgMeloRepo, PgSubscriptionRepo, PgCorrelationIndex, PgPartnerRepo>
/// ```
///
/// `testing` feature instantiates it with InMemory implementations.
#[derive(Clone)]
pub struct AppState<Ma, Me, Su, Ci, Pa>
where
    Ma: MaloRepository + Clone,
    Me: MeloRepository + Clone,
    Su: SubscriptionRepository + Clone,
    Ci: CorrelationIndex + Clone,
    Pa: PartnerRepository + Clone,
{
    pub malo_repo: Ma,
    pub melo_repo: Me,
    pub subscription_repo: Su,
    pub correlation_index: Ci,
    pub partner_repo: Pa,
    #[cfg(feature = "makod-client")]
    pub makod_client: std::sync::Arc<crate::makod_client::MakodClient>,
    /// Low-latency wake-up hint for the durable fan-out worker.
    ///
    /// Producers persist events to the `event_log` outbox (via
    /// `marktd::outbox::enqueue`) and then `notify_one()` this handle so the
    /// worker drains immediately instead of waiting for its next poll. It is a
    /// hint only — correctness rests on the outbox table, never on this signal.
    pub notify: std::sync::Arc<tokio::sync::Notify>,
    /// Operator primary GLN (matches `makod.toml` `[[party]] primary = true`).
    pub tenant_gln: String,
}

// ── MaloGridRecord ────────────────────────────────────────────────────────────

/// NB grid topology record for a single Marktlokation.
///
/// Written by the NB's **NIS/GIS adapter** (network information system) or
/// provisioned manually via `PUT /api/v1/malo/{id}/grid` on `marktd`.
/// Read by `processd` NB module for Anmeldung STP decisions (checks 1, 4).
///
/// NOTE: This is NOT MaStR data. MaStR (BNetzA) covers generation/consumption
/// units, not NB grid topology or Bilanzierungsgebiet assignments.
///
/// Without a grid record, `netz-checker` returns `NetzCheckResult::Escalate`
/// — the NB cannot auto-decide.
///
/// # STP impact
///
/// STP improves markedly when this record is present — provision it via the
/// NB-role `PUT /api/v1/malo/{malo_id}/grid` endpoint (manual / ERP integration).
/// Without a grid record, ~40 % of Anmeldungen escalate (missing grid records → cold cache).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaloGridRecord {
    /// 11-digit Marktlokations-ID (Strom) or Gas-MaLo-ID.
    pub malo_id: MaloId,
    /// GLN of the Netzbetreiber that owns this MaLo in their grid.
    pub nb_mp_id: String,
    /// Bilanzierungsgebiet-EIC (`LOC+237` in UTILMD), if known.
    ///
    /// `None` when the NIS has not yet provided this value.  Check 4 in
    /// `netz-checker` is skipped (not failed) when both this and the
    /// UTILMD value are absent.
    pub bilanzierungsgebiet: Option<String>,
    /// NB-internal Netzgebiet code (optional).
    pub netzgebiet: Option<String>,
    /// Energy commodity (`STROM` / `GAS`).
    pub sparte: Sparte,
    /// Source of this record (e.g. `"nis"`, `"manual"`).
    pub source: String,
    /// Last sync timestamp.
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
    /// Tenant GLN (operator). Not included in the REST API response;
    /// defaults to empty string when deserializing from the marktd API.
    #[serde(default)]
    pub tenant: String,
}

/// Read/write access to NB grid topology records (`malo_grid` table).
///
/// One row per `(malo_id, tenant)`.  Written by the NB's NIS adapter
/// and by manual provisioning; read by `processd` NB module for Anmeldung STP evaluation.
#[allow(async_fn_in_trait)]
pub trait MaloGridRepository: Send + Sync {
    /// Insert or replace the grid record for a MaLo.
    ///
    /// Idempotent — subsequent writes overwrite the previous record.
    /// `updated_at` is set to `now()` by the repository implementation.
    #[must_use]
    async fn upsert(&self, rec: MaloGridRecord) -> Result<(), MdmError>;

    /// Return the grid record for a MaLo, or `None` if not yet synced.
    #[must_use]
    async fn find(
        &self,
        malo_id: &MaloId,
        tenant: &str,
    ) -> Result<Option<MaloGridRecord>, MdmError>;

    /// List all grid records for a given NB GLN and tenant (e.g. for bulk export).
    #[must_use]
    async fn list_by_nb(
        &self,
        nb_mp_id: &str,
        tenant: &str,
    ) -> Result<Vec<MaloGridRecord>, MdmError>;

    /// Delete a grid record (e.g. when MaStR signals decommissioning).
    #[must_use]
    async fn delete(&self, malo_id: &MaloId, tenant: &str) -> Result<(), MdmError>;
}

// ── SteuerbareRessource (B4b) ─────────────────────────────────────────────────

/// A stored `SteuerbareRessource` record.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SteuerbareRessourceRecord {
    /// SR-ID (format: `C[A-Z0-9]{9}[0-9]`).
    pub sr_id: String,
    /// Tenant GLN.
    pub tenant: String,
    /// Associated MaLo-ID, if known.
    pub malo_id: Option<String>,
    /// Associated MeLo-ID, if known.
    pub melo_id: Option<String>,
    /// Full BO4E `SteuerbareRessource` payload (stored as JSONB).
    pub data: serde_json::Value,
    /// Contracted iMS control products (`Vec<Konfigurationsprodukt>` as JSONB array).
    ///
    /// `None` = not yet populated from WiM Stammdaten.
    /// `Some([])` = SR has no contracted control products.
    /// Required for pre-dispatch eligibility checks in `wim.steuerungsauftrag.bestaetigen`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub konfigurationsprodukte: Option<serde_json::Value>,
    /// BO4E schema version.
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
    /// Monotonic version counter (incremented on update).
    pub version: i64,
    pub updated_at: time::OffsetDateTime,
}

/// A GPKE Teil 4 Stammdatenänderung applied to the typed `STEUERBARE_RESSOURCE`
/// columns (`LOC+Z19`, „Änderung Daten der SR", §14a).
///
/// The grounded attribute is the contracted **Konfigurationsprodukte** — the SG8
/// `SEQ+Z79` product groups (produktcode `PIA+5` DE7140, zugeordneter Marktpartner
/// `CAV+Z91`/`ZF0`, Produkteigenschaft `CCI+Z66`), extracted as a BO4E
/// `Vec<Konfigurationsprodukt>` JSONB array. Applied by **replacing** the whole
/// array (the AHB carries the full contracted set per change), not merging.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SteuerbareRessourceStammdatenPatch {
    /// Full contracted `Konfigurationsprodukte` array (BO4E), or `None` to leave
    /// the column untouched.
    pub konfigurationsprodukte: Option<serde_json::Value>,
}

impl SteuerbareRessourceStammdatenPatch {
    /// `true` when no column would change.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.konfigurationsprodukte.is_none()
    }
}

/// Persistent store for `SteuerbareRessource` registrations.
///
/// Populated by the WiM iMS Steuerungsauftrag process (PID 55168)
/// and by operator REST uploads.
#[allow(async_fn_in_trait)]
pub trait SteuerbareRessourceRepository: Send + Sync {
    /// Upsert a `SteuerbareRessource` for the given `sr_id` + tenant.
    #[allow(clippy::too_many_arguments)]
    async fn upsert_sr(
        &self,
        sr_id: &str,
        tenant: &str,
        malo_id: Option<&str>,
        melo_id: Option<&str>,
        data: serde_json::Value,
        bo4e_version: &str,
        konfigurationsprodukte: Option<serde_json::Value>,
    ) -> Result<(), MdmError>;

    /// Return the `SteuerbareRessource` for `sr_id`, or `None` if not found.
    async fn find_sr(
        &self,
        sr_id: &str,
        tenant: &str,
    ) -> Result<Option<SteuerbareRessourceRecord>, MdmError>;

    /// Return all `SteuerbareRessource` records for a MaLo.
    async fn list_sr_by_malo(
        &self,
        malo_id: &str,
        tenant: &str,
    ) -> Result<Vec<SteuerbareRessourceRecord>, MdmError>;

    /// Replace the `konfigurationsprodukte` array for an existing SR (M1).
    ///
    /// Returns `Ok(true)` when the SR was found and updated,
    /// `Ok(false)` when the SR does not exist (caller should return 404).
    async fn replace_sr_konfigurationsprodukte(
        &self,
        sr_id: &str,
        tenant: &str,
        konfigurationsprodukte: serde_json::Value,
    ) -> Result<bool, MdmError>;
}

// ── TechnischeRessource (B9) ─────────────────────────────────────────────────

/// A stored `TechnischeRessource` record.
///
/// Covers E-mobility charging points (`EMobilitaetsart`), generation units
/// (`Erzeugungsart`), and storage (`Speicherart`).  Linked to `MaLo`/`MeLo` via
/// `Lokationszuordnung`.  Required for WiM iMS Steuerungsauftrag and Redispatch 2.0.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TechnischeRessourceRecord {
    /// `TrId` — Technische-Ressource identifier.
    pub tr_id: String,
    pub tenant: String,
    /// Linked `MaLo` (`zugeordnete_marktlokation_id`).
    pub malo_id: Option<String>,
    /// Linked `MeLo` (`vorgelagerte_messlokation_id`).
    pub melo_id: Option<String>,
    /// BO4E `TechnischeRessourceNutzung`: `"STROMVERBRAUCHSART"` |
    /// `"STROMERZEUGUNGSART"` | `"SPEICHER"`.
    pub nutzung: Option<String>,
    /// BO4E `TechnischeRessourceVerbrauchsart` (only for `STROMVERBRAUCHSART`):
    /// `"KRAFT_LICHT"` | `"WAERME"` | `"E_MOBILITAET"` | `"STRASSENBELEUCHTUNG"`.
    pub verbrauchsart: Option<String>,
    /// Whether the resource can be remote-controlled (Redispatch 2.0 `ist_fernschaltbar`).
    pub ist_fernschaltbar: Option<bool>,
    /// Full BO4E `TechnischeRessource` payload.
    pub data: serde_json::Value,
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
    pub version: i64,
    pub updated_at: time::OffsetDateTime,
}

/// A GPKE Teil 4 Stammdatenänderung applied to the typed `TECHNISCHE_RESSOURCE`
/// columns (`LOC+Z20`, „Änderung Daten der TR", §14a/Redispatch).
///
/// The grounded attributes are:
/// - **Fernschaltbarkeit** — UTILMD `CAV+7111=Z58` (Fernschaltung) / `CAV+7110`
///   `Z06` (vorhanden → `true`) / `Z07` (nicht vorhanden → `false`).
/// - **Art und Nutzung der Technischen Ressource** — the BO4E `nutzung`
///   (`CCI+7059` `Z17` Stromverbrauchsart / `Z50` Stromerzeugungsart / `Z56`
///   Speicher) and, for Stromverbrauchsart, the `verbrauchsart` (`CAV+7111`
///   `Z64` Kraft/Licht / `Z65` Wärme / `ZE5` E-Mobilität / `ZA8`
///   Straßenbeleuchtung). Note: this is the TR object's own classification, not
///   the MaLo `CCI+7059=Z69` „technische Einrichtung" Verbrauchsart.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TechnischeRessourceStammdatenPatch {
    /// BO4E `TechnischeRessourceNutzung` (`tr.nutzung`).
    pub nutzung: Option<String>,
    /// BO4E `TechnischeRessourceVerbrauchsart` (`tr.verbrauchsart`).
    pub verbrauchsart: Option<String>,
    /// Fernschaltbarkeit (`tr.ist_fernschaltbar`).
    pub ist_fernschaltbar: Option<bool>,
}

impl TechnischeRessourceStammdatenPatch {
    /// `true` when no column would change.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.nutzung.is_none() && self.verbrauchsart.is_none() && self.ist_fernschaltbar.is_none()
    }
}

/// Persistent store for `TechnischeRessource` registrations.
///
/// Populated by Redispatch 2.0 registration processes and by operator REST
/// uploads.  Used by iMS E-mobility `Steuerungsauftrag` routing and flex-market
/// clearing.
#[allow(async_fn_in_trait)]
pub trait TechnischeRessourceRepository: Send + Sync {
    #[allow(clippy::too_many_arguments)]
    async fn upsert_tr(
        &self,
        tr_id: &str,
        tenant: &str,
        malo_id: Option<&str>,
        melo_id: Option<&str>,
        nutzung: Option<&str>,
        verbrauchsart: Option<&str>,
        ist_fernschaltbar: Option<bool>,
        data: serde_json::Value,
        bo4e_version: &str,
    ) -> Result<(), MdmError>;

    async fn find_tr(
        &self,
        tr_id: &str,
        tenant: &str,
    ) -> Result<Option<TechnischeRessourceRecord>, MdmError>;

    /// Return all `TechnischeRessource` records for a `MaLo`.
    async fn list_tr_by_malo(
        &self,
        malo_id: &str,
        tenant: &str,
    ) -> Result<Vec<TechnischeRessourceRecord>, MdmError>;

    /// Return all `TechnischeRessource` records for a `MeLo`.
    async fn list_tr_by_melo(
        &self,
        melo_id: &str,
        tenant: &str,
    ) -> Result<Vec<TechnischeRessourceRecord>, MdmError>;

    /// Apply a UTILMD Stammdatenänderung (`LOC+Z20`) to the typed TR columns.
    ///
    /// `COALESCE` per column; the JSONB payload and `version` are untouched.
    /// Returns `true` when a row was updated, `false` when the TR is unknown.
    async fn patch_stammdaten(
        &self,
        tr_id: &str,
        tenant: &str,
        patch: &TechnischeRessourceStammdatenPatch,
    ) -> Result<bool, MdmError>;
}

// ── Lokationszuordnung graph (B5) ────────────────────────────────────────────

/// One directed edge of the MaKo location graph.
///
/// The graph models: `MaLo ↔ MeLo ↔ NeLo ↔ SteuerbareRessource ↔ TechnischeRessource`
///
/// Temporal validity: `valid_from IS NULL` means "from the beginning of time";
/// `valid_to IS NULL` means "open-ended (currently active)".
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LokationszuordnungEdge {
    pub id: uuid::Uuid,
    pub tenant: String,
    /// Source node ID (e.g. MaLo-ID, MeLo-ID).
    pub von_id: String,
    /// Source node type — the BO4E [`Lokationstyp`] (`MALO`/`MELO`/`NELO`/`SR`/`TR`).
    pub von_typ: Lokationstyp,
    /// Target node ID.
    pub nach_id: String,
    /// Target node type — the BO4E [`Lokationstyp`].
    pub nach_typ: Lokationstyp,
    pub valid_from: Option<time::Date>,
    /// `None` = open-ended (currently active).
    pub valid_to: Option<time::Date>,
    /// Lokationsbündelcode extracted from the BO4E payload
    /// (`data.lokationsbuendelcode`) on upsert — identifies the Lokationsbündel
    /// this edge belongs to (UTILMD Lokationsbündelstruktur).
    #[serde(default)]
    pub lokationsbuendelcode: Option<String>,
    /// Full BO4E `Lokationszuordnung` payload.
    pub data: serde_json::Value,
    /// BFS traversal depth from root (0 = direct edge from root).
    #[serde(default)]
    pub depth: i32,
}

/// Persistent store for the `Lokationszuordnung` location graph.
///
/// Enables single-query recursive traversal of the full MaLo → MeLo → NeLo →
/// SR/TR graph for topology-dependent operations (Redispatch 2.0, iMS E-mobility
/// Steuerungsauftrag routing, MSB Stammdaten hierarchy).
///
/// # Single-write-path invariant (MaLo ↔ MeLo)
///
/// The `melo → malo` edges of this graph are ALSO maintained by the MeLo write
/// path (`MeloRepository::upsert` in marktd's PG implementation) in the same
/// transaction that sets the `melo.malo_id` FK: the FK is a derived convenience
/// for "current parent", the graph is the authoritative temporal history, and
/// the two never contradict. Writers other than the MeLo PUT and the graph API
/// must not touch `melo.malo_id` directly.
#[allow(async_fn_in_trait)]
pub trait LokationszuordnungRepository: Send + Sync {
    /// Insert or replace a directed edge.
    ///
    /// For open-ended edges (`valid_from = None`), only one edge per
    /// `(tenant, von_id, nach_id)` pair is kept.  Dated edges
    /// (`valid_from = Some(date)`) allow temporal succession.
    #[allow(clippy::too_many_arguments)]
    async fn upsert_edge(
        &self,
        tenant: &str,
        von_id: &str,
        von_typ: Lokationstyp,
        nach_id: &str,
        nach_typ: Lokationstyp,
        valid_from: Option<time::Date>,
        valid_to: Option<time::Date>,
        data: serde_json::Value,
    ) -> Result<uuid::Uuid, MdmError>;

    /// Recursively traverse the full location graph reachable from `root_id`.
    ///
    /// Returns all edges BFS-ordered by depth (depth 0 = direct edges from root).
    /// Pass `at_date = None` to return all edges regardless of validity.
    /// Pass `at_date = Some(d)` to filter to edges valid on date `d`.
    ///
    /// Traversal is capped at depth 8 to prevent runaway queries on malformed data.
    async fn find_graph(
        &self,
        tenant: &str,
        root_id: &str,
        at_date: Option<time::Date>,
    ) -> Result<Vec<LokationszuordnungEdge>, MdmError>;

    /// Return direct (depth-0) edges FROM a given node, optionally filtered by date.
    async fn list_edges_from(
        &self,
        tenant: &str,
        von_id: &str,
        at_date: Option<time::Date>,
    ) -> Result<Vec<LokationszuordnungEdge>, MdmError>;

    /// Hard-delete an edge by `(tenant, von_id, nach_id)`.
    ///
    /// Removes all temporal variants of the edge pair.
    /// Returns `true` if at least one row was deleted.
    async fn delete_edge(
        &self,
        tenant: &str,
        von_id: &str,
        nach_id: &str,
    ) -> Result<bool, MdmError>;

    /// Load the [`Lokationsbuendel`] rooted at `malo_id`, projected from the
    /// typed edge graph (validity-filtered by `at_date`).
    ///
    /// Provided method — implementations get it for free on top of
    /// [`find_graph`](Self::find_graph).
    async fn load_buendel(
        &self,
        tenant: &str,
        malo_id: &str,
        at_date: Option<time::Date>,
    ) -> Result<Lokationsbuendel, MdmError> {
        let edges = self.find_graph(tenant, malo_id, at_date).await?;
        Ok(Lokationsbuendel::from_graph(malo_id, &edges))
    }
}

/// Error raised when a [`Lokationsbuendel`] violates a structural integrity rule.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum BuendelError {
    /// A consuming Marktlokation bundles no Messlokation.
    #[error(
        "Lokationsbündel for MaLo {malo_id} has no Messlokation \
         (a consuming MaLo must bundle at least one MeLo)"
    )]
    NoMesslokation { malo_id: String },
    /// The bundle's Messlokationen are operated by more than one MSB.
    #[error(
        "Lokationsbündel for MaLo {malo_id} spans divergent MSB assignments {msbs:?} \
         (all MeLos of a MaLo must share one Messstellenbetreiber)"
    )]
    DivergentMsb { malo_id: String, msbs: Vec<String> },
}

/// First-class **Lokationsbündel** (UTILMD Lokationsbündelstruktur) — the set of
/// locations bundled under one Marktlokation, projected from the typed
/// [`LokationszuordnungEdge`] graph. Its BO4E carrier is
/// `rubo4e::current::Lokationszuordnung`.
///
/// Modeling the bundle as an aggregate makes its integrity invariants
/// ([`validate`](Self::validate),
/// [`validate_msb_consistency`](Self::validate_msb_consistency)) enforceable at
/// the domain boundary rather than upheld only by the single-write-path
/// convention on `melo.malo_id`.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Lokationsbuendel {
    /// Root Marktlokation the bundle hangs off.
    pub malo_id: String,
    /// Codeliste der Lokationsbündelstrukturen (edi-energy id=38), when carried.
    pub lokationsbuendelcode: Option<String>,
    /// Referenced Messlokationen (≥ 1 for a valid consuming bundle).
    pub messlokationen: Vec<String>,
    /// Referenced Netzlokationen.
    pub netzlokationen: Vec<String>,
    /// Referenced steuerbare Ressourcen (§14a control).
    pub steuerbare_ressourcen: Vec<String>,
    /// Referenced technische Ressourcen.
    pub technische_ressourcen: Vec<String>,
}

impl Lokationsbuendel {
    /// Project the bundle rooted at `malo_id` from a set of graph edges
    /// (typically the output of [`LokationszuordnungRepository::find_graph`]).
    ///
    /// Nodes are collected by [`Lokationstyp`] across every edge in `edges`; the
    /// root MaLo itself is excluded from the lists, and ids are de-duplicated.
    #[must_use]
    pub fn from_graph(malo_id: &str, edges: &[LokationszuordnungEdge]) -> Self {
        use std::collections::BTreeSet;
        let (mut melo, mut nelo, mut sr, mut tr) = (
            BTreeSet::new(),
            BTreeSet::new(),
            BTreeSet::new(),
            BTreeSet::new(),
        );
        let mut lokationsbuendelcode: Option<String> = None;
        for e in edges {
            if lokationsbuendelcode.is_none() {
                lokationsbuendelcode.clone_from(&e.lokationsbuendelcode);
            }
            for (id, typ) in [(&e.von_id, e.von_typ), (&e.nach_id, e.nach_typ)] {
                if id == malo_id {
                    continue;
                }
                match typ {
                    Lokationstyp::Melo => melo.insert(id.clone()),
                    Lokationstyp::Nelo => nelo.insert(id.clone()),
                    Lokationstyp::Sr => sr.insert(id.clone()),
                    Lokationstyp::Tr => tr.insert(id.clone()),
                    _ => false,
                };
            }
        }
        Self {
            malo_id: malo_id.to_owned(),
            lokationsbuendelcode,
            messlokationen: melo.into_iter().collect(),
            netzlokationen: nelo.into_iter().collect(),
            steuerbare_ressourcen: sr.into_iter().collect(),
            technische_ressourcen: tr.into_iter().collect(),
        }
    }

    /// Structural integrity: a consuming Marktlokation must bundle at least one
    /// Messlokation.
    ///
    /// # Errors
    /// [`BuendelError::NoMesslokation`] when the bundle carries no MeLo.
    pub fn validate(&self) -> Result<(), BuendelError> {
        if self.messlokationen.is_empty() {
            return Err(BuendelError::NoMesslokation {
                malo_id: self.malo_id.clone(),
            });
        }
        Ok(())
    }

    /// MSB-consistency invariant: all Messlokationen of the bundle must be
    /// operated by the same Messstellenbetreiber. `msb_by_melo` maps each MeLo-ID
    /// to its current MSB MP-ID (`None` = no MSB assigned yet, which is ignored).
    ///
    /// # Errors
    /// [`BuendelError::DivergentMsb`] when the MeLos resolve to more than one MSB.
    pub fn validate_msb_consistency(
        &self,
        msb_by_melo: &std::collections::HashMap<String, Option<String>>,
    ) -> Result<(), BuendelError> {
        use std::collections::BTreeSet;
        let msbs: BTreeSet<String> = self
            .messlokationen
            .iter()
            .filter_map(|m| msb_by_melo.get(m).and_then(Clone::clone))
            .collect();
        if msbs.len() > 1 {
            return Err(BuendelError::DivergentMsb {
                malo_id: self.malo_id.clone(),
                msbs: msbs.into_iter().collect(),
            });
        }
        Ok(())
    }
}

// ── Device registry: Zaehler + Geraete (B3) ──────────────────────────────────

/// A stored `Zaehler` record.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ZaehlerRecord {
    /// Manufacturer serial number or UUID.
    pub zaehler_id: String,
    /// Tenant GLN.
    pub tenant: String,
    /// Owning MeLo-ID.
    pub melo_id: String,
    /// Zähler type string (e.g. `"DREHSTROMZAEHLER"`).
    pub zaehler_typ: Option<String>,
    /// Eichgültigkeitsdatum — calibration valid until.
    pub eichung_bis: Option<time::Date>,
    /// Full BO4E `Zaehler` payload.
    pub data: serde_json::Value,
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
    pub version: i64,
    pub updated_at: time::OffsetDateTime,
}

// ── Geraet device-configuration types (MsbG §23) ─────────────────────────────

/// Configuration parameter keys for `GeraetKonfiguration`.
///
/// These cover the full spectrum of properties that an MSB must track per device
/// under **MsbG §23** (device records), **BSI TR-03109-1/3** (SMGW firmware and
/// TLS certificates), **§14a EnWG BK6-22-300** (CLS remote-control capability),
/// and **§ 13 StromNZV** (calibration and maintenance intervals).
///
/// Values are always strings; use ISO 8601 (`YYYY-MM-DD`) for dates and
/// `"true"` / `"false"` for booleans.  Custom keys use `Sonstiges` with the
/// actual key name in `notiz`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Konfigurationsparameter {
    /// Firmware version string (e.g. `"2.4.1"`) — BSI TR-03109-1 §4.3.
    FirmwareVersion,
    /// Hardware revision string (e.g. `"Rev. B"`).
    HardwareRevision,
    /// Communication technology used by this device's communication module.
    ///
    /// Valid values correspond to `rubo4e::current::Geraetetyp` variants:
    /// `"GPRS"` (ModemGprs), `"PLC"` (PlcKom), `"ETHERNET"` (EthernetKom),
    /// `"FUNK"` (ModemFunk), `"FESTNETZ"` (ModemFestnetz), `"GSM"` (ModemGsm).
    Kommunikation,
    /// Whether the device supports remote (over-the-air) firmware update.
    /// String value `"true"` or `"false"`.
    FernUpdateFaehig,
    /// Whether the device supports §14a EnWG remote control via a CLS channel.
    /// String value `"true"` or `"false"`.
    ClsFaehig,
    /// BSI TR-03109-3 SMGW TLS certificate SHA-256 fingerprint (64 lowercase hex chars).
    ///
    /// Used by the `edmd` certificate-expiry background worker to emit
    /// `de.messwert.cls.compliance-issue` before expiry.
    SmgwTlsCertFingerprint,
    /// SMGW TLS certificate expiry date (`YYYY-MM-DD`).
    ///
    /// The `edmd` worker alerts when `SmgwCertAblaufdatum ≤ today + 30 days`.
    SmgwCertAblaufdatum,
    /// CLS channel identifier for §14a Steuerungsauftrag routing (opaque string).
    ClsKanalId,
    /// GWA (Gateway-Administrator) BDEW-Codenummer — routes WAN traffic to the
    /// correct GWA for SMGW reconfiguration.
    GwaCodenummer,
    /// Manufacturer name (Hersteller).
    Hersteller,
    /// Commissioning date (`YYYY-MM-DD`).
    Inbetriebnahmedatum,
    /// Last maintenance visit date (`YYYY-MM-DD`) — § 13 StromNZV Kalibrierpflicht.
    LetzteWartung,
    /// Next scheduled maintenance date (`YYYY-MM-DD`).
    NaechsteWartung,
    /// Readout protocol for EDL21/EDL40 meters: `"SML"` | `"DLMS"` | `"IEC62056"`.
    AusleseProtokoll,
    /// MSB contract number (Vertragsnummer) for this device.
    MsbVertragsnummer,
    /// Custom / proprietary parameter.  Use the `notiz` field for the actual key name.
    Sonstiges,
}

/// A single device-configuration entry stored per `Geraet` under MsbG §23.
///
/// Configuration entries are stored in an ordered, deduplicated list keyed by
/// `parameter` (last-write-wins within the same `parameter` value).
/// The list is replaced atomically on `PUT .../konfigurationen`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GeraetKonfiguration {
    /// Configuration key.
    pub parameter: Konfigurationsparameter,
    /// Configuration value (string-typed; ISO 8601 for dates, `"true"`/`"false"` for booleans).
    pub wert: String,
    /// Server-side timestamp of the last write (UTC).
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
    /// Free-text note or sub-key for `Konfigurationsparameter::Sonstiges` entries.
    pub notiz: Option<String>,
}

/// A stored `Geraet` record.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GeraetRecord {
    /// Manufacturer serial number or UUID.
    pub geraet_id: String,
    /// Tenant GLN.
    pub tenant: String,
    /// Owning `zaehler_id`.
    pub zaehler_id: String,
    /// Gerätetyp string (e.g. `"WANDLER"`).
    pub geraet_typ: Option<String>,
    /// Full BO4E `Geraet` payload.
    pub data: serde_json::Value,
    /// Typed device configuration entries per MsbG §23.
    ///
    /// Stored in the `geraet_konfigurationen` JSONB column (separate from `data`)
    /// so they can be updated without rewriting the full BO4E payload.  GIN-indexed
    /// for fast queries such as "all devices with `SMGW_CERT_ABLAUFDATUM ≤ 30 days"`.
    pub konfigurationen: Vec<GeraetKonfiguration>,
    #[serde(default = "default_bo4e_version")]
    pub bo4e_version: String,
    pub version: i64,
    pub updated_at: time::OffsetDateTime,
}

/// Persistent store for Zähler (meters) and Geräte (devices).
///
/// Populated by WiM MSB/NB device handover processes (ORDERS PIDs 17001–17011)
/// and operator REST uploads.
///
/// Source: WiM AHB BK6-24-174; BO4E Zaehler/Geraet schemas.
#[allow(async_fn_in_trait)]
pub trait DeviceRepository: Send + Sync {
    /// Upsert a `Zaehler` record.
    #[allow(clippy::too_many_arguments)]
    async fn upsert_zaehler(
        &self,
        zaehler_id: &str,
        tenant: &str,
        melo_id: &str,
        zaehler_typ: Option<&str>,
        eichung_bis: Option<time::Date>,
        data: serde_json::Value,
        bo4e_version: &str,
    ) -> Result<(), MdmError>;

    /// Return all `Zaehler` for a given MeLo-ID.
    async fn list_zaehler_by_melo(
        &self,
        melo_id: &str,
        tenant: &str,
    ) -> Result<Vec<ZaehlerRecord>, MdmError>;

    /// Return the `Zaehler` for a given `zaehler_id`, or `None` if not found.
    async fn find_zaehler(
        &self,
        zaehler_id: &str,
        tenant: &str,
    ) -> Result<Option<ZaehlerRecord>, MdmError>;

    /// Upsert a `Geraet` record.
    async fn upsert_geraet(
        &self,
        geraet_id: &str,
        tenant: &str,
        zaehler_id: &str,
        geraet_typ: Option<&str>,
        data: serde_json::Value,
        bo4e_version: &str,
    ) -> Result<(), MdmError>;

    /// Return all `Geraete` for a given `zaehler_id`.
    async fn list_geraete_by_zaehler(
        &self,
        zaehler_id: &str,
        tenant: &str,
    ) -> Result<Vec<GeraetRecord>, MdmError>;

    /// Return a single `Geraet` by its `geraet_id`, or `None` if not found.
    async fn find_geraet(
        &self,
        geraet_id: &str,
        tenant: &str,
    ) -> Result<Option<GeraetRecord>, MdmError>;

    /// Atomically replace all `GeraetKonfiguration` entries for a `Geraet`.
    ///
    /// Returns `true` if the Geraet was found and updated, `false` if not found.
    ///
    /// The `updated_at` timestamp on each entry is set server-side; callers
    /// should not set it in the request (it is overwritten).
    ///
    /// Emits `de.markt.geraet.konfiguration.updated` via the EventBus fan-out.
    async fn upsert_geraet_konfigurationen(
        &self,
        geraet_id: &str,
        tenant: &str,
        konfigurationen: Vec<GeraetKonfiguration>,
    ) -> Result<bool, MdmError>;
}

// ── iMSys TOU registers: ZaehlzeitRegister + ZaehlzeitSaison ─────────────────

/// A `ZaehlzeitRegister` defines one metering register of an iMSys
/// (Intelligentes Messsystem) smart meter.
///
/// German smart meters record separate totals for each tariff zone:
/// - `HT` (Hochtarif) — peak-time consumption, higher grid tariff
/// - `NT` (Niedertarif) — off-peak consumption, lower tariff
/// - `EINZEL` — single-tariff (no zone discrimination)
///
/// The applicable zone at any given time is determined by the `ZaehlzeitSaison`
/// entries linked to this register.
///
/// Source: MsbG §19; BO4E Zaehlwerk; BDEW AHB WiM Teil 3.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ZaehlzeitRegisterRecord {
    /// Primary key (UUID).
    pub id: uuid::Uuid,
    /// Owning Zähler serial number.
    pub zaehler_id: String,
    /// Tenant GLN.
    pub tenant: String,
    /// Register human-readable label (e.g. `"HT"`, `"NT"`, `"Gesamt"`).
    pub bezeichnung: String,
    /// BO4E `Zaehlerauspraegung`: `"HT"` | `"NT"` | `"EINZEL"`.
    pub zaehlerauspraegung: String,
    /// OBIS kennzahl identifying this register in MSCONS (e.g. `"1-1:1.29.0"`).
    pub obis_kennzahl: Option<String>,
    /// Measurement unit (default `"KWH"`).
    #[serde(default = "default_kwh")]
    pub einheit: String,
    /// Start of validity.
    pub valid_from: time::Date,
    /// End of validity — `None` = currently valid.
    pub valid_to: Option<time::Date>,
    pub updated_at: time::OffsetDateTime,
}

fn default_kwh() -> String {
    "KWH".to_owned()
}

/// Seasonal / weekly time-of-use window within a `ZaehlzeitRegister`.
///
/// Defines the time windows during which the linked register's tariff zone is
/// active (e.g. "HT applies Monday–Friday from 07:00 to 22:00 in winter").
///
/// Multiple `ZaehlzeitSaison` entries cover the full 168-hour week.
///
/// Source: BO4E Zaehlzeitdefinition; MsbG Anlage 1; BDEW Rolloutprofil.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ZaehlzeitSaisonRecord {
    /// Primary key (UUID).
    pub id: uuid::Uuid,
    /// Owning `ZaehlzeitRegister` ID.
    pub register_id: uuid::Uuid,
    /// Season key: `"SOMMER"` | `"WINTER"` | `"GESAMT"` (year-round).
    pub saison: String,
    /// Days of week this window applies: bitmask or JSON array of ISO weekday
    /// numbers 1 (Mon) through 7 (Sun).  Stored as a JSON array for clarity.
    /// Example: `[1,2,3,4,5]` = Monday–Friday.
    pub wochentage: serde_json::Value,
    /// Window start time (local German time, HH:MM).  Example: `"07:00"`.
    pub zeit_von: String,
    /// Window end time (local German time, HH:MM, exclusive).  Example: `"22:00"`.
    pub zeit_bis: String,
    pub updated_at: time::OffsetDateTime,
}

/// Persistence store for iMSys TOU registers.
///
/// Allows `edmd` to correctly classify MSCONS reads by tariff zone
/// (HT vs NT) for iMSys smart meters without relying on the OBIS code alone.
#[allow(async_fn_in_trait)]
pub trait ZaehlzeitRepository: Send + Sync {
    /// Upsert a `ZaehlzeitRegister`.
    async fn upsert_register(&self, rec: &ZaehlzeitRegisterRecord) -> Result<(), MdmError>;

    /// Return all registers for a given `zaehler_id`.
    async fn list_registers_by_zaehler(
        &self,
        zaehler_id: &str,
        tenant: &str,
    ) -> Result<Vec<ZaehlzeitRegisterRecord>, MdmError>;

    /// Upsert a `ZaehlzeitSaison` for a given register.
    async fn upsert_saison(&self, rec: &ZaehlzeitSaisonRecord) -> Result<(), MdmError>;

    /// Return all `ZaehlzeitSaison` entries for a register.
    async fn list_saisons_by_register(
        &self,
        register_id: uuid::Uuid,
        tenant: &str,
    ) -> Result<Vec<ZaehlzeitSaisonRecord>, MdmError>;

    /// Resolve the applicable tariff zone (`HT`|`NT`|`EINZEL`) for a Zähler at
    /// a given local datetime.  Returns `None` if no matching window is found
    /// (treat as `EINZEL` in that case).
    async fn resolve_tariff_zone(
        &self,
        zaehler_id: &str,
        tenant: &str,
        local_datetime: time::PrimitiveDateTime,
    ) -> Result<Option<String>, MdmError>;
}

// ── MMMA Gas settlement prices (Trading Hub Europe / MGV) ────────────────────

/// A stored Gas MMM Abrechnungspreis record.
///
/// Published monthly by Trading Hub Europe (THE). Used by `netzbilanzd` when
/// generating INVOIC 31007/31008 and by `invoicd` for MMM position check 6.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MmmaPreisGasRecord {
    /// First day of the billing month (German local time).
    pub price_month: time::Date,
    /// Marktgebiet — always `"THE"` in Germany since 2021.
    pub marktgebiet: String,
    /// Ausgleichsenergiepreis Überschuss (Mehrmengen) in ct/kWh.
    pub mehr_ct_kwh: rust_decimal::Decimal,
    /// Ausgleichsenergiepreis Defizit (Mindermengen) in ct/kWh.
    pub minder_ct_kwh: rust_decimal::Decimal,
    /// How this record entered the system: `"manual"` | `"the-api"` | `"csv-import"`.
    pub source: String,
    pub updated_at: time::OffsetDateTime,
}

/// Read/write access to Gas MMM Abrechnungspreise.
///
/// `netzbilanzd` fetches these instead of requiring manual ERP input per billing run.
/// `invoicd` uses them for MMM position plausibility check.
#[allow(async_fn_in_trait)]
pub trait MmmaPreisGasRepository: Send + Sync {
    /// Upsert the Gas MMM price pair for a billing month + Marktgebiet.
    async fn upsert_gas(
        &self,
        price_month: time::Date,
        marktgebiet: &str,
        mehr_ct_kwh: rust_decimal::Decimal,
        minder_ct_kwh: rust_decimal::Decimal,
        source: &str,
    ) -> Result<(), MdmError>;

    /// Return the Gas MMM prices for a billing month. Returns `None` if not yet imported.
    async fn find_gas(
        &self,
        price_month: time::Date,
        marktgebiet: &str,
    ) -> Result<Option<MmmaPreisGasRecord>, MdmError>;

    /// List all Gas MMM price records, newest first.
    async fn list_gas(&self, limit: i64) -> Result<Vec<MmmaPreisGasRecord>, MdmError>;
}

// ── MMM Strom settlement prices (VNB per GPKE (BK6-24-174) Teil 1 Kap. 8.4) ───────────────────────

/// A stored Strom MMM Ausgleichsenergie price record.
///
/// Published monthly by each ÜNB (50Hertz, TenneT, Amprion, TransnetBW).
/// Used by `netzbilanzd` (INVOIC 31002/31005) and `invoicd` (MMM check 6).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MmmPreisStromRecord {
    /// First day of the billing month.
    pub price_month: time::Date,
    /// ÜNB MP-ID (BDEW-Codenummer, `99…`).
    pub vnb_mp_id: String,
    /// Surplus energy price (Mehrmengen) in ct/kWh.
    pub mehr_ct_kwh: rust_decimal::Decimal,
    /// Deficit energy price (Mindermengen) in ct/kWh.
    pub minder_ct_kwh: rust_decimal::Decimal,
    pub source: String,
    pub updated_at: time::OffsetDateTime,
}

/// Read/write access to Strom MMM Ausgleichsenergie prices.
#[allow(async_fn_in_trait)]
pub trait MmmPreisStromRepository: Send + Sync {
    async fn upsert_strom(
        &self,
        price_month: time::Date,
        vnb_mp_id: &str,
        mehr_ct_kwh: rust_decimal::Decimal,
        minder_ct_kwh: rust_decimal::Decimal,
        source: &str,
    ) -> Result<(), MdmError>;

    async fn find_strom(
        &self,
        price_month: time::Date,
        vnb_mp_id: &str,
    ) -> Result<Option<MmmPreisStromRecord>, MdmError>;
}

// ── NB Energiemix (§42 EnWG annual grid-area renewable mix) ─────────────────

/// A stored `NbEnergiemix` record.
///
/// The NB publishes the annual renewable energy mix of their grid area under
/// §42 Abs. 5 EnWG.  Lieferanten use this to compute the Reststrommix
/// for customer bills and to label Ökostrom tariffs in `tarifbd`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NbEnergiemixRecord {
    /// 13-digit BDEW/DVGW/GS1 NB MP-ID.
    pub nb_mp_id: String,
    /// Calendar year this mix is valid for (e.g. `2025`).
    pub gueltig_fuer: i16,
    /// Full `rubo4e::current::Energiemix` COM payload (JSONB, camelCase).
    pub energiemix: serde_json::Value,
    /// Total EEG feed-in into this grid area in kWh (optional informational).
    pub eeg_einspeisung_kwh: Option<i64>,
    /// Total grid withdrawal (`Gesamtentnahme`) in kWh.
    pub gesamtentnahme_kwh: Option<i64>,
    /// Wall-clock time (UTC) when this record was last updated.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub updated_at: Option<time::OffsetDateTime>,
}

/// Read/write access to NB annual grid-area Energiemix (§42 EnWG).
#[allow(async_fn_in_trait)]
pub trait NbEnergiemixRepository: Send + Sync {
    /// Upsert the annual Energiemix for an NB.
    ///
    /// Idempotent: re-publishing the same year with updated values replaces
    /// the existing row.
    async fn upsert_energiemix(
        &self,
        tenant: &str,
        nb_mp_id: &str,
        gueltig_fuer: i16,
        energiemix: serde_json::Value,
        eeg_einspeisung_kwh: Option<i64>,
        gesamtentnahme_kwh: Option<i64>,
    ) -> Result<(), MdmError>;

    /// Return the `NbEnergiemix` for the given NB and year.
    ///
    /// When `year` is `None`, returns the most recent available year.
    async fn find_energiemix(
        &self,
        tenant: &str,
        nb_mp_id: &str,
        year: Option<i16>,
    ) -> Result<Option<NbEnergiemixRecord>, MdmError>;

    /// Return all available years for a given NB (for history/audit).
    async fn list_energiemix_years(
        &self,
        tenant: &str,
        nb_mp_id: &str,
    ) -> Result<Vec<i16>, MdmError>;
}

// ── ESA consent registry (§49 Abs. 2 Nr. 9 MsbG) ──────────────────────────────

/// One ESA consent (Einwilligung) — the ESA's lawful basis for holding a
/// location's metering values (§49 Abs. 2 Nr. 9 MsbG, GDPR Art. 7).
///
/// Evidence-agnostic: `evidence_uri`/`evidence_hash` are stored verbatim and
/// never validated for form (BNetzA forbids rejecting consent for deviating
/// from the BDEW template).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EinwilligungRecord {
    #[serde(default)]
    pub id: Uuid,
    #[serde(default)]
    pub tenant: String,
    /// Opaque reference to the Anschlussnutzer (no PII stored here).
    pub anschlussnutzer_ref: String,
    /// MP-ID of the ESA the consent authorises.
    pub esa_mp_id: String,
    /// Locations (MaLo/MeLo/NeLo/ZPB) the consent covers.
    pub location_ids: Vec<String>,
    #[serde(default = "default_scope")]
    pub scope: String,
    #[serde(default = "unix_epoch", with = "time::serde::rfc3339")]
    pub granted_at: time::OffsetDateTime,
    #[serde(with = "date_iso")]
    pub valid_from: Date,
    #[serde(default, with = "date_iso::opt")]
    pub valid_to: Option<Date>,
    /// GDPR Art. 7(3): non-`None` once revoked.
    #[serde(default, with = "time::serde::rfc3339::option")]
    pub revoked_at: Option<time::OffsetDateTime>,
    /// Opaque evidence pointer/hash — stored verbatim, never form-validated.
    #[serde(default)]
    pub evidence_uri: Option<String>,
    #[serde(default)]
    pub evidence_hash: Option<String>,
}

fn default_scope() -> String {
    "werte".to_owned()
}

/// Bilateral EDI@Energy framework agreement + AS4 cert state (MSB ↔ ESA).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EsaFrameworkAgreement {
    #[serde(default)]
    pub tenant: String,
    pub msb_mp_id: String,
    pub esa_mp_id: String,
    #[serde(default, with = "time::serde::rfc3339::option")]
    pub signed_at: Option<time::OffsetDateTime>,
    #[serde(default)]
    pub edi_agreement: bool,
    #[serde(default = "default_cert_state")]
    pub cert_state: String,
}

fn default_cert_state() -> String {
    "pending".to_owned()
}

/// Which side of the ESA relationship is gating a message.
///
/// The consent has **asymmetric** force. The MSB holds only the ESA's
/// self-assertion, so a missing record is not its problem to reject. The ESA is
/// the data controller that obtained the Einwilligung, so for the ESA a missing
/// record means no lawful basis at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConsentPerspective {
    /// MSB *receiving* an inbound ESA order. Lenient: a missing consent record
    /// is self-assertion and never blocks (BNetzA forbids form-based rejection).
    #[default]
    MsbInbound,
    /// ESA *originating* an outbound request (Werteanfrage/Bestellung), or about
    /// to hold values. Strict: the ESA must hold a recorded, non-revoked consent
    /// — a missing record is no lawful basis (GDPR Art. 7), so it blocks.
    EsaOutbound,
}

/// Why an ESA-message consent check allowed or blocked delivery.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConsentCode {
    /// An active, non-revoked consent covers the location — deliver.
    Active,
    /// No consent record for the location, seen from the **MSB** side. The ESA's
    /// self-assertion stands and BNetzA Mitteilung Nr. 3 (07.02.2024) forbids
    /// rejecting on consent *form*, so absence alone never blocks — deliver.
    SelfAssertion,
    /// No consent record for the location, seen from the **ESA** side. The ESA
    /// holds no lawful basis (GDPR Art. 7) and must not originate the request —
    /// block.
    NoConsent,
    /// A recorded consent for the location has been revoked (GDPR Art. 7(3)) and
    /// no active consent superseded it — block (the Widerruf clearing case).
    Revoked,
    /// A framework agreement exists but is not established (no EDI agreement or a
    /// negative cert state) — the UC 4.1.1 Vorbedingung is unmet, so block.
    FrameworkRejected,
}

impl ConsentCode {
    /// Whether this outcome permits the message.
    #[must_use]
    pub const fn allowed(self) -> bool {
        matches!(self, Self::Active | Self::SelfAssertion)
    }
}

/// Outcome of gating an inbound ESA message against the consent registry.
///
/// Absence of a consent record is **not** a block: the MSB holds the ESA's
/// self-assertion and BNetzA forbids rejecting on form. Only an explicit
/// negative signal — a revoked consent, or a framework agreement that is on
/// record but not established — blocks delivery.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConsentDecision {
    /// `true` when the inbound ESA message may be processed.
    pub allowed: bool,
    /// Machine-readable reason.
    pub code: ConsentCode,
    /// Human-readable reason (also used verbatim as the Ablehnung Begründung).
    pub reason: String,
}

impl ConsentDecision {
    /// Build a decision from a [`ConsentCode`], filling in the standard reason.
    #[must_use]
    pub fn from_code(code: ConsentCode) -> Self {
        let reason = match code {
            ConsentCode::Active => "aktive Einwilligung liegt vor",
            ConsentCode::SelfAssertion => {
                "keine Einwilligung erfasst — Zusicherung des ESA gilt (keine Formprüfung)"
            }
            ConsentCode::NoConsent => {
                "keine Einwilligung erfasst — der ESA hat keine Rechtsgrundlage (GDPR Art. 7)"
            }
            ConsentCode::Revoked => {
                "Einwilligung wurde widerrufen (GDPR Art. 7 Abs. 3) — keine Belieferung"
            }
            ConsentCode::FrameworkRejected => {
                "Rahmenvertrag/EDI-Vereinbarung nicht etabliert (Vorbedingung UC 4.1.1)"
            }
        };
        Self {
            allowed: code.allowed(),
            code,
            reason: reason.to_owned(),
        }
    }
}

/// Registry of ESA consents and framework agreements (`esa_einwilligungen`,
/// `esa_framework_agreements`).
#[allow(async_fn_in_trait)]
pub trait EinwilligungRepository: Send + Sync {
    /// Grant a consent, superseding any active consent for the same
    /// `(tenant, esa, Anschlussnutzer)`. Returns the new consent id.
    async fn grant(&self, rec: EinwilligungRecord) -> Result<Uuid, MdmError>;

    /// Fetch a consent by id (tenant-scoped).
    async fn get(&self, tenant: &str, id: Uuid) -> Result<Option<EinwilligungRecord>, MdmError>;

    /// List active (non-revoked) consents for an ESA.
    async fn list_for_esa(
        &self,
        tenant: &str,
        esa_mp_id: &str,
    ) -> Result<Vec<EinwilligungRecord>, MdmError>;

    /// Revoke a consent (Art. 7(3)). Returns the revoked record when it existed
    /// and was still active, so the caller can fire the 17008 Abbestellung.
    async fn revoke(&self, tenant: &str, id: Uuid) -> Result<Option<EinwilligungRecord>, MdmError>;

    /// Upsert a framework agreement.
    async fn upsert_framework(&self, rec: EsaFrameworkAgreement) -> Result<(), MdmError>;

    /// Fetch a framework agreement.
    async fn get_framework(
        &self,
        tenant: &str,
        msb_mp_id: &str,
        esa_mp_id: &str,
    ) -> Result<Option<EsaFrameworkAgreement>, MdmError>;

    /// Gate an ESA message for `location_id` against the registry.
    ///
    /// A revoked consent or an unestablished framework agreement always blocks.
    /// A *missing* consent record depends on `perspective`: lenient
    /// ([`ConsentPerspective::MsbInbound`]) treats it as self-assertion and
    /// allows; strict ([`ConsentPerspective::EsaOutbound`]) treats it as no
    /// lawful basis and blocks.
    async fn consent_check(
        &self,
        tenant: &str,
        esa_mp_id: &str,
        msb_mp_id: &str,
        location_id: &str,
        perspective: ConsentPerspective,
    ) -> Result<ConsentDecision, MdmError>;
}

// ── §20b EnWG Netzzugangsplattform ────────────────────────────────────────────

/// Use case of a §20b EnWG Netzzugangsplattform request (Abs. 2 Nr. 1–3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NetzzugangAntragTyp {
    /// §20b Abs. 2 Nr. 1 — Zählpunktanordnung (umgangssprachlich Messkonzept)
    /// hinter einem Netzanschluss.
    Zaehlpunktanordnung,
    /// §20b Abs. 2 Nr. 2 — Verrechnungskonzept (Verrechnungsformel) hinter
    /// einem Netzanschluss.
    Verrechnungskonzept,
    /// §20b Abs. 2 Nr. 3 — Registrierung einer Energy-Sharing-Vereinbarung
    /// nach §42c EnWG.
    EnergySharingVereinbarung,
}

impl NetzzugangAntragTyp {
    /// Stable snake_case string used in SQL CHECK constraints and JSON.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Zaehlpunktanordnung => "zaehlpunktanordnung",
            Self::Verrechnungskonzept => "verrechnungskonzept",
            Self::EnergySharingVereinbarung => "energysharing_vereinbarung",
        }
    }
}

/// Action on a §20b request. `Registrierung` applies only to
/// [`NetzzugangAntragTyp::EnergySharingVereinbarung`]; the other two use cases
/// carry the statutory Bestellung/Änderung/Abbestellung triple.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NetzzugangAktion {
    /// Erstmalige Bestellung.
    Bestellung,
    /// Änderung.
    Aenderung,
    /// Abbestellung.
    Abbestellung,
    /// Registrierung (§42c-Vereinbarung only).
    Registrierung,
}

impl NetzzugangAktion {
    /// Stable snake_case string used in SQL CHECK constraints and JSON.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Bestellung => "bestellung",
            Self::Aenderung => "aenderung",
            Self::Abbestellung => "abbestellung",
            Self::Registrierung => "registrierung",
        }
    }
}

/// Lifecycle state of a §20b request as tracked by the projection.
///
/// `Erfasst` on command acceptance, `Uebermittelt` once the makod outbox
/// sender delivered it (to the platform endpoint or, while none exists, to the
/// operator's ERP webhook for manual submission via the NB Webportal),
/// `Bestaetigt`/`Abgelehnt` when the answer arrives, `Fehlgeschlagen` when
/// delivery exhausted its retries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NetzzugangStatus {
    /// Recorded; not yet delivered.
    Erfasst,
    /// Delivered to the platform endpoint or handed to the operator.
    Uebermittelt,
    /// Confirmed by the platform / Netzbetreiber.
    Bestaetigt,
    /// Rejected by the platform / Netzbetreiber.
    Abgelehnt,
    /// Delivery failed permanently.
    Fehlgeschlagen,
}

impl NetzzugangStatus {
    /// Stable snake_case string used in SQL CHECK constraints and JSON.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Erfasst => "erfasst",
            Self::Uebermittelt => "uebermittelt",
            Self::Bestaetigt => "bestaetigt",
            Self::Abgelehnt => "abgelehnt",
            Self::Fehlgeschlagen => "fehlgeschlagen",
        }
    }
}

/// A §20b EnWG Netzzugangsplattform request (Antrag) and its lifecycle state.
///
/// The platform itself does not exist yet (no BNetzA Festlegung under §20b
/// Abs. 3 as of 2026-07); the record is transport-agnostic: the payload is the
/// canonical JSON the adapter delivers, `platform_ref` is the platform's
/// reference once one is assigned.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetzzugangAntrag {
    #[serde(default)]
    pub id: Uuid,
    #[serde(default)]
    pub tenant: String,
    /// §20b use case.
    pub antrag_typ: NetzzugangAntragTyp,
    /// Action within the use case.
    pub aktion: NetzzugangAktion,
    /// The Netzanschluss the request concerns (operator-scoped identifier).
    pub netzanschluss_id: String,
    /// MP-ID of the responsible Netzbetreiber.
    pub nb_mp_id: String,
    /// Requester on whose behalf the request is made (Anschlussnehmer /
    /// Anschlussnutzer / §20-Anspruchsberechtigter) — opaque reference, no PII.
    pub antragsteller_ref: String,
    /// Lifecycle state.
    #[serde(default = "default_netzzugang_status")]
    pub status: NetzzugangStatus,
    /// Canonical request payload delivered to the platform.
    #[serde(default)]
    pub payload: serde_json::Value,
    /// Reference assigned by the platform, once known.
    #[serde(default)]
    pub platform_ref: Option<String>,
    #[serde(default = "unix_epoch", with = "time::serde::rfc3339")]
    pub created_at: time::OffsetDateTime,
    #[serde(default, with = "time::serde::rfc3339::option")]
    pub submitted_at: Option<time::OffsetDateTime>,
}

fn default_netzzugang_status() -> NetzzugangStatus {
    NetzzugangStatus::Erfasst
}

/// Registry of §20b EnWG Netzzugangsplattform requests.
#[allow(async_fn_in_trait)]
pub trait NetzzugangRepository: Send + Sync {
    /// Insert or update a request by id (tenant-scoped). Returns the id.
    async fn upsert(&self, rec: NetzzugangAntrag) -> Result<Uuid, MdmError>;

    /// Fetch a request by id (tenant-scoped).
    async fn get(&self, tenant: &str, id: Uuid) -> Result<Option<NetzzugangAntrag>, MdmError>;

    /// List requests, optionally filtered by status and/or Netzanschluss.
    async fn list(
        &self,
        tenant: &str,
        status: Option<NetzzugangStatus>,
        netzanschluss_id: Option<&str>,
    ) -> Result<Vec<NetzzugangAntrag>, MdmError>;

    /// Update lifecycle state (and optionally the platform reference).
    /// Returns the updated record when it existed.
    async fn set_status(
        &self,
        tenant: &str,
        id: Uuid,
        status: NetzzugangStatus,
        platform_ref: Option<String>,
    ) -> Result<Option<NetzzugangAntrag>, MdmError>;
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod partner_record_tests {
    use super::*;

    fn sample_partner() -> PartnerRecord {
        PartnerRecord {
            mp_id: "9900357000004".parse().expect("valid MP-ID"),
            display_name: Some("Stadtwerke Musterstadt Netz GmbH".to_owned()),
            marktrolle: Some(rubo4e::current::Marktrolle::Nb),
            sparte: Some(Sparte::Strom),
            rollencodetyp: Some(rubo4e::current::Rollencodetyp::Bdew),
            makoadresse: vec!["https://as4.musterstadt.example/msh".to_owned()],
            channels: serde_json::json!({}),
            version: 1,
            updated_at: time::OffsetDateTime::UNIX_EPOCH,
        }
    }

    /// The typed enums keep the wire format the TEXT columns and existing API
    /// clients rely on: bare BDEW codes.
    #[test]
    fn typed_enums_stay_string_compatible() {
        let p = sample_partner();
        let json = serde_json::to_value(&p).expect("serialise");
        assert_eq!(json["marktrolle"], "NB");
        assert_eq!(json["rollencodetyp"], "BDEW");

        let round: PartnerRecord = serde_json::from_value(json).expect("deserialise");
        assert_eq!(round.marktrolle, Some(rubo4e::current::Marktrolle::Nb));
        assert_eq!(
            round.rollencodetyp,
            Some(rubo4e::current::Rollencodetyp::Bdew)
        );

        // strum Display matches the serde repr — the PG TEXT binding uses it.
        assert_eq!(rubo4e::current::Marktrolle::Nb.to_string(), "NB");
        assert_eq!(rubo4e::current::Rollencodetyp::Gln.to_string(), "GLN");
        assert_eq!("LF".parse(), Ok(rubo4e::current::Marktrolle::Lf));
    }

    /// `to_marktteilnehmer` maps every stored field into the BO4E shape.
    #[test]
    fn to_marktteilnehmer_maps_all_fields() {
        let p = sample_partner();
        let mt = p.to_marktteilnehmer();

        assert_eq!(
            mt.rollencodenummer.as_ref().map(ToString::to_string),
            Some("9900357000004".to_owned())
        );
        assert_eq!(mt.marktrolle, Some(rubo4e::current::Marktrolle::Nb));
        assert_eq!(mt.rollencodetyp, Some(rubo4e::current::Rollencodetyp::Bdew));
        assert_eq!(mt.sparte, Some(rubo4e::current::Sparte::Strom));
        assert_eq!(
            mt.makoadresse,
            Some(vec!["https://as4.musterstadt.example/msh".to_owned()])
        );
        assert_eq!(
            mt.geschaeftspartner
                .as_ref()
                .and_then(|g| g.organisationsname.clone()),
            Some("Stadtwerke Musterstadt Netz GmbH".to_owned())
        );
        // The BO discriminator is set by the type's Default.
        assert_eq!(mt.typ, Some(rubo4e::current::BoTyp::Marktteilnehmer));

        // An empty makoadresse list is omitted, not serialised as [].
        let mut bare = sample_partner();
        bare.makoadresse.clear();
        bare.display_name = None;
        let mt = bare.to_marktteilnehmer();
        assert_eq!(mt.makoadresse, None);
        assert!(mt.geschaeftspartner.is_none());
    }
}

#[cfg(test)]
mod lokationsbuendel_tests {
    use std::collections::HashMap;

    use super::*;

    fn edge(
        von: &str,
        von_typ: Lokationstyp,
        nach: &str,
        nach_typ: Lokationstyp,
    ) -> LokationszuordnungEdge {
        LokationszuordnungEdge {
            id: uuid::Uuid::nil(),
            tenant: "t".to_owned(),
            von_id: von.to_owned(),
            von_typ,
            nach_id: nach.to_owned(),
            nach_typ,
            valid_from: None,
            valid_to: None,
            lokationsbuendelcode: Some("9992000000125".to_owned()),
            data: serde_json::json!({}),
            depth: 0,
        }
    }

    /// `von_typ`/`nach_typ` are the BO4E `Lokationstyp` and stay wire-compatible
    /// with the canonical uppercase codes the TEXT column and API rely on.
    #[test]
    fn edge_typ_is_bo4e_lokationstyp() {
        let e = edge("MALO1", Lokationstyp::Malo, "MELO1", Lokationstyp::Melo);
        let json = serde_json::to_value(&e).expect("serialise");
        assert_eq!(json["von_typ"], "MALO");
        assert_eq!(json["nach_typ"], "MELO");
        assert_eq!(<&'static str>::from(Lokationstyp::Nelo), "NELO");
        assert_eq!("SR".parse(), Ok(Lokationstyp::Sr));
    }

    /// A bundle projects every non-root node by type and de-duplicates.
    #[test]
    fn from_graph_projects_nodes_by_type() {
        let edges = vec![
            edge("MALO1", Lokationstyp::Malo, "MELO1", Lokationstyp::Melo),
            edge("MALO1", Lokationstyp::Malo, "MELO2", Lokationstyp::Melo),
            edge("MELO1", Lokationstyp::Melo, "NELO1", Lokationstyp::Nelo),
            edge("MELO1", Lokationstyp::Melo, "SR1", Lokationstyp::Sr),
            edge("SR1", Lokationstyp::Sr, "TR1", Lokationstyp::Tr),
            // duplicate edge must not double-count
            edge("MALO1", Lokationstyp::Malo, "MELO1", Lokationstyp::Melo),
        ];
        let b = Lokationsbuendel::from_graph("MALO1", &edges);
        assert_eq!(b.malo_id, "MALO1");
        assert_eq!(b.lokationsbuendelcode.as_deref(), Some("9992000000125"));
        assert_eq!(b.messlokationen, vec!["MELO1", "MELO2"]);
        assert_eq!(b.netzlokationen, vec!["NELO1"]);
        assert_eq!(b.steuerbare_ressourcen, vec!["SR1"]);
        assert_eq!(b.technische_ressourcen, vec!["TR1"]);
        b.validate().expect("bundle with a MeLo is valid");
    }

    /// A consuming MaLo with no MeLo violates the structural invariant.
    #[test]
    fn validate_requires_at_least_one_melo() {
        let edges = vec![edge(
            "MALO1",
            Lokationstyp::Malo,
            "NELO1",
            Lokationstyp::Nelo,
        )];
        let b = Lokationsbuendel::from_graph("MALO1", &edges);
        assert!(b.messlokationen.is_empty());
        assert!(matches!(
            b.validate(),
            Err(BuendelError::NoMesslokation { .. })
        ));
    }

    /// All MeLos of one MaLo must share a single MSB.
    #[test]
    fn validate_msb_consistency_flags_divergent_msb() {
        let edges = vec![
            edge("MALO1", Lokationstyp::Malo, "MELO1", Lokationstyp::Melo),
            edge("MALO1", Lokationstyp::Malo, "MELO2", Lokationstyp::Melo),
        ];
        let b = Lokationsbuendel::from_graph("MALO1", &edges);

        // Same MSB → ok (unassigned MeLos are ignored).
        let mut consistent = HashMap::new();
        consistent.insert("MELO1".to_owned(), Some("MSB_A".to_owned()));
        consistent.insert("MELO2".to_owned(), None);
        b.validate_msb_consistency(&consistent)
            .expect("single MSB is consistent");

        // Two distinct MSBs → error.
        let mut divergent = HashMap::new();
        divergent.insert("MELO1".to_owned(), Some("MSB_A".to_owned()));
        divergent.insert("MELO2".to_owned(), Some("MSB_B".to_owned()));
        assert!(matches!(
            b.validate_msb_consistency(&divergent),
            Err(BuendelError::DivergentMsb { .. })
        ));
    }
}