mako-gpke 0.20.0

GPKE process engine for German electricity market communication (Lieferbeginn, Lieferende, Netznutzungsabrechnung)
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
//! GPKE Ersatz-/Grundversorgung (EoG) — Zuordnung by the Netzbetreiber.
//!
//! Covers the statutory fallback-supply process (GPKE Teil 2 Kap. 2.3):
//! every consuming Marktlokation must be assigned to exactly one
//! Bilanzkreis at all times. When a MaLo draws energy without an
//! assignable supply contract, the NB assigns it to the **E/G**
//! (Ersatz-/Grundversorger, §36 Abs. 2 EnWG) via UTILMD
//! "Anmeldung / Zuordnung EOG" — untermonatlich, into the future **and
//! retroactively**.
//!
//! This module implements **both perspectives**:
//!
//! - **NB (initiator)** — detects the supply gap, sends PID 55013 to the
//!   Grundversorger, and awaits Bestätigung 55014 / Ablehnung 55015. If
//!   the E/G does not answer in time, the NB **assigns anyway** using the
//!   default Bilanzkreis the E/G deposited via GPKE Teil 4 ("Übermittlung
//!   von Informationen") — silence never blocks the statutory fallback.
//! - **LF/E-G (responder)** — receives an inbound 55013 and answers with
//!   55014 (stating Ersatz- vs. Grundversorgung and the Bilanzkreis) or
//!   55015 (EBD E_0615 grounds: A02 keine Zuständigkeit, A04
//!   Doppelmeldung, A05 kein EoG-Fall).
//!
//! # Prüfidentifikatoren (UTILMD AHB Strom S2.1 Kap. 8.6)
//!
//! | PID   | Process name (AHB)              | Direction |
//! |-------|---------------------------------|-----------|
//! | 55013 | Anmeldung / Zuordnung EOG       | NB → LF   |
//! | 55014 | Bestätigung EOG Anmeldung       | LF → NB   |
//! | 55015 | Ablehnung EOG Anmeldung         | LF → NB   |
//!
//! Pre-LFW24 these were 11013–11015; the Gas twin is 44013–44015
//! (`mako-geli-gas`, `GasProcessVariant::EogAnmeldung`). PIDs 55010–55012
//! are the **separate** "Anfrage zur Beendigung der Zuordnung"
//! (NB Abmeldeanfrage) use case, not EoG, and are handled by
//! [`super::beendigung_zuordnung::GpkeBeendigungZuordnungWorkflow`].
//!
//! # Transaktionsgrund (SG4 STS DE9013, Anmeldung)
//!
//! `Z02` Kündigung Lieferantenrahmenvertrag · `Z36` EoG aus Ein-/Auszug ·
//! `Z37` EoG wegen Einzug in Neuanlage · `Z39` EoG aus vorübergehendem
//! Anschluss · `ZC6` EoG aus Bilanzkreisschließung · `ZC7` EoG aufgrund
//! Erlöschen der Zuordnungsermächtigung · `ZT6`/`ZT7` EoG wegen Kündigung
//! durch LF/Kunde · `E06` vertragliche Ersatzbelieferung (bilateral, only
//! outside the statutory 3-month window or above Niederspannung) · `ZZD`
//! Übergangsversorgung (§38a EnWG, from 2026-04-01).
//!
//! # Ersatz- vs. Grundversorgung — decided by the E/G, not the NB
//!
//! The **Bestätigung 55014** carries the classification (SG10 CCI+Z36
//! "Versorgungsart": `ZC9` Ersatzversorgung / `ZD0` Grundversorgung /
//! `ZE3` Ersatzbelieferung / `ZZD` Übergangsversorgung) plus the
//! Bilanzkreis. The Anmeldung only states the cause and whether the
//! Anschlussnutzer is a Haushaltskunde (CCI `Z15`/`Z18`), which drives
//! the E/G's classification: §38 Ersatzversorgung applies ipso iure to
//! every NSP-Letztverbraucher; Grundversorgung (§36) only to
//! Haushaltskunden.
//!
//! After **three months** (§38 Abs. 4 S. 1 EnWG — counted from the
//! (possibly retroactive) Zuordnungsbeginn, not from detection) the
//! Ersatzversorgung ends by law; for Haushaltskunden the transition into
//! Grundversorgung happens **automatically without a market message**
//! (GPKE Teil 2 Kap. 2.3.2.1). The `processd` EoG timer owns that clock.
//!
//! # Fristen (GPKE Teil 2 Kap. 2.3, SD Schritte 1–3)
//!
//! - Anmeldung: future Zuordnungsbeginn → by 13:00 of the last Werktag
//!   before it; otherwise **unverzüglich** (retroactive allowed).
//! - Antwort: **15:00 at the ÜT** (future case) or 15:00 of the first
//!   Werktag after the ÜT. Modeled here as a deadline at 15:00
//!   the published window per PID ([`eog_antwort_due_at`]).
//! - No answer → NB assigns anyway (15:00–16:00 window, default BK).
//!
//! # Regulatory basis
//!
//! - **§36 / §38 / §38a EnWG**, **§§2–3 StromGVV**
//! - **GPKE Teil 2 Kap. 2.3 (BK6-24-174)** — Beginn der Ersatz-/Grundversorgung
//! - **UTILMD AHB Strom S2.1/S2.2 Kap. 8.6**, **EBD E_0615**
//! - **APERAK AHB 1.0 §2.4.1** — Strom UTILMD 45-min APERAK Frist

use mako_engine::types::Pruefidentifikator;
use mako_engine::{
    deadline::Deadline,
    error::WorkflowError,
    ids::DeadlineId,
    outbox::PendingOutbox,
    types::{MaLo, MarktpartnerCode, MessageRef},
    workflow::{CommandPayload, EventPayload, PendingDeadline, Workflow, WorkflowOutput},
};
use mako_fristen::{APERAK_STROM_WINDOW_LABEL, aperak_strom_due_at};

// ── PID set ───────────────────────────────────────────────────────────────────

/// Workflow name used for PID routing and `WorkflowId` construction.
pub const WORKFLOW_NAME: &str = "gpke-eog";

/// Inbound Anfrage PID handled by [`GpkeEogWorkflow`] in the responder role.
pub const EOG_ANMELDUNG_PID: u32 = 55013;

/// All inbound PIDs routed to [`GpkeEogWorkflow`]:
/// 55013 spawns the responder role; 55014/55015 resume the initiator role.
pub const EOG_PIDS: &[u32] = &[55013, 55014, 55015];

/// Response PIDs (LF → NB): Bestätigung / Ablehnung.
pub const EOG_ANTWORT_PIDS: &[u32] = &[55014, 55015];

/// Deadline label for the E/G answer window (GPKE Teil 2 Kap. 2.3 SD Schritt 2).
pub const EOG_RESPONSE_WINDOW_LABEL: &str = "gpke-eog-response-window";

/// Derive the outbound ANTWORT PID for the EoG Anmeldung.
#[must_use]
pub fn eog_response_pid(accepted: bool) -> u32 {
    if accepted { 55014 } else { 55015 }
}

/// The published answer window for an inbound Anmeldung E/G.
///
/// Strom **55013** states two windows selected by a date in the payload — 15:00
/// Uhr *am ÜT* when the Zuordnungsbeginn lies in the future, and 15:00 Uhr des
/// ersten Werktags when it does not (GPKE Teil 2 § 2.3.2.2 Nr. 2). Gas **44013**
/// is a plain 2-Werktage window (BK7-24-01-009 Kap. 3.3.2).
///
/// Both come from [`mako_fristen::antwort`], which publishes the **tighter** of
/// the two Strom windows: a queue sized by the outer envelope reports a lapsed
/// Frist as still running, and that the NB eventually assigns the E/G anyway
/// (Nr. 3, „aufgrund fehlender Antwort") is a reason to answer in time, not a
/// reason to track a looser clock.
///
/// `None` for a PID that is not an Anmeldung E/G.
#[must_use]
pub fn eog_antwort_due_at(
    pid: u32,
    received_at: time::OffsetDateTime,
) -> Option<time::OffsetDateTime> {
    mako_fristen::antwort::antwort_deadline(pid, received_at)
}

// ── EoG classification ────────────────────────────────────────────────────────

/// Versorgungsart stated by the E/G in the Bestätigung 55014
/// (`SG10 CCI+Z36`, DE 7037).
///
/// **Three codes, not four.** UTILMD AHB Strom 2.2 („Versorgungsart der
/// Marktlokation", Muss on 55014) publishes exactly `ZC9`, `ZD0` and `ZE3` for
/// DE 7037. `ZZD` Übergangsversorgung is a **Transaktionsgrund** — `SG4 STS+7`
/// DE 9013 element 2, alongside `Z36`/`Z37`/`Z39`/`ZC6`/`ZC7`/`ZT6`/`ZT7`
/// (AHB Änd-ID 27001/27002, § 38a EnWG) — and appears in the same element on
/// the 55004 Abmeldung under Bedingung `[686]`. Carrying it here put a qualifier
/// into DE 7037 that the AHB does not define there, which the counterparty
/// rejects, and accepted one inbound that cannot legitimately arrive.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Versorgungsart {
    /// `ZC9` — §38 EnWG Ersatzversorgung (ipso iure, max. 3 months, NSP).
    Ersatzversorgung,
    /// `ZD0` — §36 EnWG Grundversorgung (Haushaltskunden in NSP).
    Grundversorgung,
    /// `ZE3` — vertragliche Ersatzbelieferung (bilateral agreement).
    ///
    /// The § 38a Übergangsversorgung (MSP/HSP, from 01.04.2026) is one of
    /// these: its Grundlage is a bilaterale Vereinbarung. What marks the case
    /// as § 38a is the Transaktionsgrund [`UEBERGANGSVERSORGUNG`], not a
    /// separate Versorgungsart.
    ///
    /// [`UEBERGANGSVERSORGUNG`]: crate::eog::UEBERGANGSVERSORGUNG
    Ersatzbelieferung,
}

/// `SG4 STS+7` DE 9013 — Transaktionsgrund „Übergangsversorgung" (§ 38a EnWG).
///
/// Belongs to the Transaktionsgrund code space of the 55013/55014/55015 and the
/// 55004/55005/55006, **not** to the Versorgungsart in `SG10 CCI+Z36`.
///
/// Restated here rather than imported: `edi-energy` is a dev-dependency of this
/// crate on purpose, and one string is not worth a production dependency on the
/// whole wire library. `the_code_matches_the_wire_table` holds the two together.
pub const UEBERGANGSVERSORGUNG: &str = "ZZD";

impl Versorgungsart {
    /// AHB code (`SG10 CCI+Z36` DE 7037).
    #[must_use]
    pub fn code(self) -> &'static str {
        match self {
            Self::Ersatzversorgung => "ZC9",
            Self::Grundversorgung => "ZD0",
            Self::Ersatzbelieferung => "ZE3",
        }
    }

    /// Parse from the AHB code. `ZZD` is deliberately absent — see the type docs.
    #[must_use]
    pub fn from_code(code: &str) -> Option<Self> {
        match code {
            "ZC9" => Some(Self::Ersatzversorgung),
            "ZD0" => Some(Self::Grundversorgung),
            "ZE3" => Some(Self::Ersatzbelieferung),
            _ => None,
        }
    }

    /// Stable wire label (used in outbox payloads and CloudEvents).
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ersatzversorgung => "ERSATZVERSORGUNG",
            Self::Grundversorgung => "GRUNDVERSORGUNG",
            Self::Ersatzbelieferung => "ERSATZBELIEFERUNG",
        }
    }
}

// ── Domain events ─────────────────────────────────────────────────────────────

/// Events emitted by the GPKE EoG workflow.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum EogEvent {
    /// NB (initiator) dispatched the UTILMD 55013 Zuordnung to the E/G.
    Angemeldet {
        /// Marktlokation.
        location_id: MaLo,
        /// GLN of the initiating NB.
        sender: MarktpartnerCode,
        /// GLN of the E/G (receiving LF).
        receiver: MarktpartnerCode,
        /// Zuordnungsbeginn (`YYYYMMDD`) — may be retroactive.
        process_date: String,
        /// BDEW Prüfidentifikator (55013).
        pruefidentifikator: Pruefidentifikator,
        /// SG4 STS Transaktionsgrund (e.g. `Z37`, `ZC7`).
        transaktionsgrund: String,
        /// Whether the Anschlussnutzer is a Haushaltskunde (CCI Z15/Z18),
        /// if known.
        haushaltskunde: Option<bool>,
    },
    /// NB (initiator) received the E/G's response (55014/55015).
    AntwortErhalten {
        /// Response PID: 55014 (Bestätigung) or 55015 (Ablehnung).
        response_pid: Pruefidentifikator,
        /// `true` = Bestätigung, `false` = Ablehnung.
        accepted: bool,
        /// Versorgungsart from the Bestätigung (`CCI+Z36`: ZC9/ZD0/ZE3).
        versorgungsart: Option<Versorgungsart>,
        /// Bilanzkreis (EIC) from the Bestätigung.
        bilanzkreis: Option<String>,
        /// Rejection reason / EBD code (A02/A04/A05) when rejected.
        reason: Option<String>,
    },
    /// NB (initiator): answer window expired — Zuordnung executed anyway
    /// with the E/G's pre-deposited default Bilanzkreis (GPKE Teil 2
    /// Kap. 2.3 SD Schritt 3).
    ZugeordnetOhneAntwort {
        /// The expired deadline.
        deadline_id: DeadlineId,
    },
    /// LF/E-G (responder): inbound PID 55013 Zuordnung received.
    AnmeldungErhalten {
        /// Marktlokation.
        location_id: MaLo,
        /// GLN of the sending NB.
        sender: MarktpartnerCode,
        /// GLN of the receiving LF (E/G).
        receiver: MarktpartnerCode,
        /// EDIFACT document date (`YYYYMMDD`).
        document_date: String,
        /// Zuordnungsbeginn (`YYYYMMDD`).
        process_date: String,
        /// EDIFACT message reference.
        message_ref: MessageRef,
        /// BDEW Prüfidentifikator (55013).
        pruefidentifikator: Pruefidentifikator,
        /// SG4 STS Transaktionsgrund.
        transaktionsgrund: String,
        /// Haushaltskunde flag (CCI Z15/Z18), if transmitted.
        haushaltskunde: Option<bool>,
    },
    /// EDIFACT message passed profile validation.
    ValidationPassed {
        /// Reference of the validated message.
        message_ref: MessageRef,
    },
    /// LF/E-G (responder): outbound response (55014/55015) dispatched.
    AntwortGesendet {
        /// Response PID: 55014 (Bestätigung) or 55015 (Ablehnung).
        response_pid: Pruefidentifikator,
        /// `true` = Bestätigung, `false` = Ablehnung.
        accepted: bool,
        /// Versorgungsart stated in the Bestätigung.
        versorgungsart: Option<Versorgungsart>,
        /// Bilanzkreis (EIC) stated in the Bestätigung.
        bilanzkreis: Option<String>,
        /// Rejection reason / EBD code (A02/A04/A05) when rejected.
        reason: Option<String>,
    },
    /// Process rejected (validation failure or responder answer timeout).
    Rejected {
        /// Human-readable reason.
        reason: String,
    },
    /// A registered deadline expired (responder-side bookkeeping).
    DeadlineExpired {
        /// Unique deadline ID.
        deadline_id: DeadlineId,
        /// Deadline label.
        label: Box<str>,
    },
}

impl EventPayload for EogEvent {
    fn event_type(&self) -> &'static str {
        match self {
            Self::Angemeldet { .. } => "EogAngemeldet",
            Self::AntwortErhalten { .. } => "EogAntwortErhalten",
            Self::ZugeordnetOhneAntwort { .. } => "EogZugeordnetOhneAntwort",
            Self::AnmeldungErhalten { .. } => "EogAnmeldungErhalten",
            Self::ValidationPassed { .. } => "EogValidationPassed",
            Self::AntwortGesendet { .. } => "EogAntwortGesendet",
            Self::Rejected { .. } => "EogRejected",
            Self::DeadlineExpired { .. } => "EogDeadlineExpired",
        }
    }
}

// ── Domain state ──────────────────────────────────────────────────────────────

/// Business data captured when the process starts (either role).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EogData {
    /// Marktlokation.
    pub location_id: MaLo,
    /// GLN of the NB.
    pub sender: MarktpartnerCode,
    /// GLN of the E/G (LF).
    pub receiver: MarktpartnerCode,
    /// Zuordnungsbeginn (`YYYYMMDD`) — may be retroactive; anchors the
    /// §38 Abs. 4 three-month maximum.
    pub process_date: String,
    /// BDEW Prüfidentifikator (55013).
    pub pruefidentifikator: Pruefidentifikator,
    /// SG4 STS Transaktionsgrund.
    pub transaktionsgrund: String,
    /// Haushaltskunde flag (CCI Z15/Z18), if known.
    pub haushaltskunde: Option<bool>,
}

/// State of a GPKE EoG process.
///
/// # Lifecycle
///
/// ```text
/// NB (initiator):    New → Angemeldet → Zugeordnet            (55014 / timeout)
///                                      ↘ Abgelehnt             (55015)
/// LF/E-G (responder): New → Eingegangen → ValidationPassed
///                         → AntwortGesendet                    (55014/55015)
///                         ↘ Rejected (failed validation / answer timeout)
/// ```
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "status", content = "data")]
#[derive(Default)]
pub enum EogState {
    /// No events yet.
    #[default]
    New,
    /// Initiator: UTILMD 55013 dispatched; awaiting the E/G's response.
    Angemeldet(EogData),
    /// Initiator: Zuordnung effective — either confirmed (55014) or
    /// executed without an answer (default Bilanzkreis).
    Zugeordnet {
        /// Data from the Anmeldung.
        data: EogData,
        /// Versorgungsart stated by the E/G. `None` when the Zuordnung was
        /// executed without an answer (classification then defaults to
        /// Ersatzversorgung ipso iure, §38 Abs. 1 EnWG).
        versorgungsart: Option<Versorgungsart>,
        /// Bilanzkreis (EIC). `None` = the pre-deposited default BK applies.
        bilanzkreis: Option<String>,
        /// `true` when assigned after the answer window expired.
        ohne_antwort: bool,
    },
    /// Initiator: E/G rejected (55015, EBD A02/A04/A05).
    Abgelehnt {
        /// Rejection reason.
        reason: String,
    },
    /// Responder: inbound Zuordnung received.
    Eingegangen(EogData),
    /// Responder: validation passed; response not yet sent.
    ValidationPassed(EogData),
    /// Responder: response dispatched.
    AntwortGesendet {
        /// Data from the Zuordnung.
        data: EogData,
        /// Response PID sent (55014 or 55015).
        response_pid: Pruefidentifikator,
        /// `true` = Bestätigung.
        accepted: bool,
        /// Versorgungsart stated in the Bestätigung.
        versorgungsart: Option<Versorgungsart>,
    },
    /// Process rejected (validation failure or answer timeout).
    Rejected {
        /// Human-readable reason.
        reason: String,
    },
}

impl mako_engine::workflow::OccupiesBusinessKey for EogState {
    fn occupies_business_key(&self) -> bool {
        match self {
            // Initiator side: awaiting the E/G, or the Zuordnung is effective
            // and the supply relationship is live.
            Self::Angemeldet(_) | Self::Zugeordnet { .. } => true,
            // Responder side: an inbound Zuordnung is being worked. Once the
            // answer is dispatched the responder's obligation is met, but the
            // Zuordnung it confirmed is live, so it still holds the MaLo.
            Self::Eingegangen(_) | Self::ValidationPassed(_) | Self::AntwortGesendet { .. } => true,
            // Terminal.
            Self::New | Self::Abgelehnt { .. } | Self::Rejected { .. } => false,
        }
    }
}

impl EogState {
    /// Stable string label for the current variant.
    #[must_use]
    pub fn label(&self) -> &'static str {
        match self {
            Self::New => "New",
            Self::Angemeldet(_) => "Angemeldet",
            Self::Zugeordnet { .. } => "Zugeordnet",
            Self::Abgelehnt { .. } => "Abgelehnt",
            Self::Eingegangen(_) => "Eingegangen",
            Self::ValidationPassed(_) => "ValidationPassed",
            Self::AntwortGesendet { .. } => "AntwortGesendet",
            Self::Rejected { .. } => "Rejected",
        }
    }

    /// Return `Some(&EogData)` if the process carries business data.
    #[must_use]
    pub fn data(&self) -> Option<&EogData> {
        match self {
            Self::Angemeldet(d) | Self::Eingegangen(d) | Self::ValidationPassed(d) => Some(d),
            Self::Zugeordnet { data, .. } | Self::AntwortGesendet { data, .. } => Some(data),
            Self::New | Self::Abgelehnt { .. } | Self::Rejected { .. } => None,
        }
    }

    /// `true` when the process is in a terminal state.
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            Self::Zugeordnet { .. }
                | Self::Abgelehnt { .. }
                | Self::AntwortGesendet { .. }
                | Self::Rejected { .. }
        )
    }
}

// ── Domain commands ───────────────────────────────────────────────────────────

/// Commands for the GPKE EoG workflow.
#[derive(Clone)]
pub enum EogCommand {
    /// NB (initiator): dispatch the UTILMD 55013 Zuordnung to the E/G.
    ///
    /// Triggered by the `gpke.eog.anmelden` ERP command (typically issued
    /// by the `processd` gap-closure automation).
    Anmelden {
        /// BDEW Prüfidentifikator (55013).
        pid: Pruefidentifikator,
        /// GLN of the initiating NB.
        sender: MarktpartnerCode,
        /// GLN of the E/G (Grundversorger).
        receiver: MarktpartnerCode,
        /// Marktlokation.
        location_id: MaLo,
        /// Zuordnungsbeginn (`YYYYMMDD`) — may be retroactive.
        process_date: String,
        /// SG4 STS Transaktionsgrund (Z02/Z36/Z37/Z39/ZC6/ZC7/ZT6/ZT7/E06/ZZD).
        transaktionsgrund: String,
        /// Haushaltskunde flag (CCI Z15/Z18), if known.
        haushaltskunde: Option<bool>,
    },
    /// NB (initiator): the E/G's response (55014/55015) arrived.
    ReceiveAntwort {
        /// Response PID (55014 or 55015).
        response_pid: Pruefidentifikator,
        /// `true` = Bestätigung (55014).
        accepted: bool,
        /// Versorgungsart from the Bestätigung (`CCI+Z36`: ZC9/ZD0/ZE3).
        versorgungsart: Option<Versorgungsart>,
        /// Bilanzkreis (EIC) from the Bestätigung.
        bilanzkreis: Option<String>,
        /// Rejection reason / EBD code (when rejected).
        reason: Option<String>,
    },
    /// LF/E-G (responder): inbound UTILMD 55013 received from the AS4 layer.
    ReceiveAnmeldung {
        /// BDEW Prüfidentifikator (55013).
        pid: Pruefidentifikator,
        /// GLN of the NB.
        sender: MarktpartnerCode,
        /// GLN of the LF (E/G).
        receiver: MarktpartnerCode,
        /// Marktlokation.
        location_id: MaLo,
        /// EDIFACT document date (`YYYYMMDD`).
        document_date: String,
        /// Zuordnungsbeginn (`YYYYMMDD`).
        process_date: String,
        /// EDIFACT message reference.
        message_ref: MessageRef,
        /// SG4 STS Transaktionsgrund.
        transaktionsgrund: String,
        /// Haushaltskunde flag (CCI Z15/Z18), if transmitted.
        haushaltskunde: Option<bool>,
        /// `true` if validation returned no errors.
        validation_passed: bool,
        /// Validation error strings.
        validation_errors: Vec<String>,
        /// Receipt timestamp (drives the APERAK + answer deadlines).
        received_at: time::OffsetDateTime,
    },
    /// LF/E-G (responder): send the outbound response (55014/55015).
    SendAntwort {
        /// `true` = Bestätigung (55014), `false` = Ablehnung (55015).
        accepted: bool,
        /// Versorgungsart (required for a Bestätigung: ZC9/ZD0/ZE3).
        versorgungsart: Option<Versorgungsart>,
        /// Bilanzkreis (EIC) the MaLo is assigned to (Bestätigung).
        bilanzkreis: Option<String>,
        /// Rejection reason / EBD code (required for an Ablehnung).
        reason: Option<String>,
    },
    /// A registered deadline fired.
    ///
    /// Initiator (`Angemeldet`): executes the Zuordnung without an answer
    /// (default Bilanzkreis) instead of failing — GPKE Teil 2 Kap. 2.3
    /// SD Schritt 3. Responder: closes the process as `Rejected` (the NB
    /// has assigned with the default BK on its side).
    TimeoutExpired {
        /// Unique deadline ID.
        deadline_id: DeadlineId,
        /// Deadline label.
        label: Box<str>,
    },
}

impl CommandPayload for EogCommand {}

// ── Workflow ──────────────────────────────────────────────────────────────────

/// Build the `ProcessCompleted` outbox payload that drives the marktd
/// VersorgungsStatus transition and the processd §38 timer.
fn process_completed_outbox(
    data: &EogData,
    versorgungsart: Option<Versorgungsart>,
    bilanzkreis: Option<&str>,
    ohne_antwort: bool,
) -> PendingOutbox {
    // Without an answer the classification defaults to Ersatzversorgung —
    // §38 Abs. 1 EnWG applies ipso iure to every NSP-Letztverbraucher.
    let art = versorgungsart.unwrap_or(Versorgungsart::Ersatzversorgung);
    PendingOutbox::new(
        "ProcessCompleted",
        "",
        serde_json::json!({
            "pid":               EOG_ANMELDUNG_PID,
            "malo_id":           data.location_id.as_str(),
            "new_supplier":      data.receiver.as_str(),
            "grid_operator":     data.sender.as_str(),
            "process_date":      data.process_date,
            "eog_art":           art.as_str(),
            "transaktionsgrund": data.transaktionsgrund,
            "haushaltskunde":    data.haushaltskunde,
            "bilanzkreis":       bilanzkreis,
            "ohne_antwort":      ohne_antwort,
        }),
    )
}

/// GPKE Ersatz-/Grundversorgung workflow (PIDs 55013–55015).
pub struct GpkeEogWorkflow;

impl Workflow for GpkeEogWorkflow {
    type State = EogState;
    type Event = EogEvent;
    type Command = EogCommand;

    fn on_deadline(deadline: &Deadline, state: &Self::State) -> Option<Self::Command> {
        match (deadline.label(), state) {
            (
                EOG_RESPONSE_WINDOW_LABEL | APERAK_STROM_WINDOW_LABEL,
                EogState::Angemeldet(_) | EogState::Eingegangen(_) | EogState::ValidationPassed(_),
            ) => Some(EogCommand::TimeoutExpired {
                deadline_id: deadline.deadline_id(),
                label: deadline.label().into(),
            }),
            _ => None,
        }
    }

    fn apply(state: Self::State, event: &Self::Event) -> Self::State {
        match event {
            EogEvent::Angemeldet {
                location_id,
                sender,
                receiver,
                process_date,
                pruefidentifikator,
                transaktionsgrund,
                haushaltskunde,
            } => EogState::Angemeldet(EogData {
                location_id: location_id.clone(),
                sender: sender.clone(),
                receiver: receiver.clone(),
                process_date: process_date.clone(),
                pruefidentifikator: *pruefidentifikator,
                transaktionsgrund: transaktionsgrund.clone(),
                haushaltskunde: *haushaltskunde,
            }),
            EogEvent::AntwortErhalten {
                accepted,
                versorgungsart,
                bilanzkreis,
                reason,
                ..
            } => match state {
                EogState::Angemeldet(data) => {
                    if *accepted {
                        EogState::Zugeordnet {
                            data,
                            versorgungsart: *versorgungsart,
                            bilanzkreis: bilanzkreis.clone(),
                            ohne_antwort: false,
                        }
                    } else {
                        EogState::Abgelehnt {
                            reason: reason
                                .clone()
                                .unwrap_or_else(|| "EoG Zuordnung abgelehnt".to_owned()),
                        }
                    }
                }
                other => other,
            },
            EogEvent::ZugeordnetOhneAntwort { .. } => match state {
                EogState::Angemeldet(data) => EogState::Zugeordnet {
                    data,
                    versorgungsart: None,
                    bilanzkreis: None,
                    ohne_antwort: true,
                },
                other => other,
            },
            EogEvent::AnmeldungErhalten {
                location_id,
                sender,
                receiver,
                process_date,
                pruefidentifikator,
                transaktionsgrund,
                haushaltskunde,
                ..
            } => EogState::Eingegangen(EogData {
                location_id: location_id.clone(),
                sender: sender.clone(),
                receiver: receiver.clone(),
                process_date: process_date.clone(),
                pruefidentifikator: *pruefidentifikator,
                transaktionsgrund: transaktionsgrund.clone(),
                haushaltskunde: *haushaltskunde,
            }),
            EogEvent::ValidationPassed { .. } => match state {
                EogState::Eingegangen(data) => EogState::ValidationPassed(data),
                other => other,
            },
            EogEvent::AntwortGesendet {
                response_pid,
                accepted,
                versorgungsart,
                ..
            } => match state {
                EogState::ValidationPassed(data) => EogState::AntwortGesendet {
                    data,
                    response_pid: *response_pid,
                    accepted: *accepted,
                    versorgungsart: *versorgungsart,
                },
                other => other,
            },
            EogEvent::Rejected { reason } => EogState::Rejected {
                reason: reason.clone(),
            },
            EogEvent::DeadlineExpired { label, .. } => {
                if state.is_terminal() {
                    state
                } else {
                    EogState::Rejected {
                        reason: format!("deadline expired: {label}"),
                    }
                }
            }
        }
    }

    fn handle(
        state: &Self::State,
        command: Self::Command,
    ) -> Result<WorkflowOutput<Self::Event>, WorkflowError> {
        match command {
            // ── NB initiator ─────────────────────────────────────────────────
            EogCommand::Anmelden {
                pid,
                sender,
                receiver,
                location_id,
                process_date,
                transaktionsgrund,
                haushaltskunde,
            } => {
                if !matches!(state, EogState::New) {
                    return Err(WorkflowError::invalid_state("New", state.label()));
                }
                if pid.as_u32() != EOG_ANMELDUNG_PID {
                    return Err(WorkflowError::rejected(format!(
                        "expected EoG Anmeldung PID ({EOG_ANMELDUNG_PID}), got {pid}",
                    )));
                }
                if transaktionsgrund.trim().is_empty() {
                    return Err(WorkflowError::rejected(
                        "EoG Anmeldung requires a Transaktionsgrund (SG4 STS DE9013)".to_owned(),
                    ));
                }

                // Outbound UTILMD 55013 — rendered by the makod EDIFACT
                // renderer (`message_type = "UTILMD"`).
                let utilmd = PendingOutbox::new(
                    "UTILMD",
                    receiver.as_str(),
                    serde_json::json!({
                        "direction":         "outbound",
                        "pid":               pid.as_u32(),
                        "sender":            sender.as_str(),
                        "receiver":          receiver.as_str(),
                        "malo":              location_id.as_str(),
                        "process_date":      process_date,
                        "transaktionsgrund": transaktionsgrund,
                    }),
                );
                // Notify observers (obsd, ERP) that the statutory fallback
                // process has been initiated.
                let initiated = PendingOutbox::new(
                    "ProcessInitiated",
                    receiver.as_str(),
                    serde_json::json!({
                        "pid":               pid.as_u32(),
                        "malo_id":           location_id.as_str(),
                        "new_supplier":      receiver.as_str(),
                        "grid_operator":     sender.as_str(),
                        "process_date":      process_date,
                        "transaktionsgrund": transaktionsgrund,
                    }),
                );

                let event = EogEvent::Angemeldet {
                    location_id,
                    sender,
                    receiver,
                    process_date,
                    pruefidentifikator: pid,
                    transaktionsgrund,
                    haushaltskunde,
                };
                Ok(WorkflowOutput::with_outbox(
                    vec![event],
                    vec![utilmd, initiated],
                ))
            }

            EogCommand::ReceiveAntwort {
                response_pid,
                accepted,
                versorgungsart,
                bilanzkreis,
                reason,
            } => {
                let data = match state {
                    EogState::Angemeldet(d) => d,
                    _ => {
                        return Err(WorkflowError::invalid_state("Angemeldet", state.label()));
                    }
                };
                if !EOG_ANTWORT_PIDS.contains(&response_pid.as_u32()) {
                    return Err(WorkflowError::rejected(format!(
                        "expected EoG Antwort PID (55014/55015), got {response_pid}",
                    )));
                }
                let mut outbox = Vec::new();
                if accepted {
                    outbox.push(process_completed_outbox(
                        data,
                        versorgungsart,
                        bilanzkreis.as_deref(),
                        false,
                    ));
                }
                Ok(WorkflowOutput::with_outbox(
                    vec![EogEvent::AntwortErhalten {
                        response_pid,
                        accepted,
                        versorgungsart,
                        bilanzkreis,
                        reason,
                    }],
                    outbox,
                ))
            }

            // ── LF/E-G responder ─────────────────────────────────────────────
            EogCommand::ReceiveAnmeldung {
                pid,
                sender,
                receiver,
                location_id,
                document_date,
                process_date,
                message_ref,
                transaktionsgrund,
                haushaltskunde,
                validation_passed,
                validation_errors,
                received_at,
            } => {
                if !matches!(state, EogState::New) {
                    return Err(WorkflowError::invalid_state("New", state.label()));
                }
                if pid.as_u32() != EOG_ANMELDUNG_PID {
                    return Err(WorkflowError::rejected(format!(
                        "expected EoG Anmeldung PID ({EOG_ANMELDUNG_PID}), got {pid}",
                    )));
                }
                // Clone before move for the notification and APERAK emission.
                let sender_mp_id = sender.clone();
                let receiver_gln = receiver.clone();
                let notify_malo = location_id.clone();
                let notify_termin = process_date.clone();
                let grund = transaktionsgrund.clone();

                let mut events = vec![EogEvent::AnmeldungErhalten {
                    location_id,
                    sender,
                    receiver,
                    document_date,
                    process_date,
                    message_ref: message_ref.clone(),
                    pruefidentifikator: pid,
                    transaktionsgrund,
                    haushaltskunde,
                }];
                if validation_passed {
                    events.push(EogEvent::ValidationPassed {
                        message_ref: message_ref.clone(),
                    });
                    // APERAK BGM+312 (Anerkennung) — Strom UTILMD 45-min Frist
                    // (APERAK AHB 1.0 §2.4.1).
                    let outbox = vec![
                        // The business notification. Without it `processd`'s LF
                        // module never sees the Zuordnung: `makod` delivers a
                        // CloudEvent only for an outbox entry, and an APERAK is
                        // a technical acknowledgement. The E/G's 15:00-Uhr-am-ÜT
                        // Frist would then lapse unanswered and unseen.
                        crate::LfVorgangsdaten {
                            transaktionsgrund: Some(grund.clone()),
                            ..crate::LfVorgangsdaten::default()
                        }
                        .process_initiated(
                            pid,
                            &notify_malo,
                            &sender_mp_id,
                            &receiver_gln,
                            &notify_termin,
                            &serde_json::json!({ "haushaltskunde": haushaltskunde }),
                        )
                        .caused_by(1),
                        PendingOutbox::aperak_anerkennung(
                            receiver_gln.as_str(),
                            sender_mp_id.as_str(),
                            message_ref.as_str(),
                        )
                        .caused_by(1),
                    ];
                    let deadlines: Vec<PendingDeadline> = core::iter::once(PendingDeadline::new(
                        APERAK_STROM_WINDOW_LABEL,
                        aperak_strom_due_at(received_at),
                    ))
                    .chain(
                        eog_antwort_due_at(pid.as_u32(), received_at)
                            .map(|due| PendingDeadline::new(EOG_RESPONSE_WINDOW_LABEL, due)),
                    )
                    .collect();
                    Ok(WorkflowOutput::with_outbox_and_deadlines(
                        events, outbox, deadlines,
                    ))
                } else {
                    let reason = if validation_errors.is_empty() {
                        "AHB validation failed".to_owned()
                    } else {
                        validation_errors.join("; ")
                    };
                    events.push(EogEvent::Rejected {
                        reason: reason.clone(),
                    });
                    // APERAK BGM+313 (Verarbeitbarkeitsfehler).
                    let outbox = vec![
                        PendingOutbox::aperak_fehler(
                            receiver_gln.as_str(),
                            sender_mp_id.as_str(),
                            message_ref.as_str(),
                            mako_engine::erc::codes::Z29,
                            reason,
                        )
                        .caused_by(0),
                    ];
                    Ok(WorkflowOutput::with_outbox(events, outbox))
                }
            }

            EogCommand::SendAntwort {
                accepted,
                versorgungsart,
                bilanzkreis,
                reason,
            } => {
                let data = match state {
                    EogState::ValidationPassed(d) => d,
                    _ => {
                        return Err(WorkflowError::invalid_state(
                            "ValidationPassed",
                            state.label(),
                        ));
                    }
                };
                if accepted && versorgungsart.is_none() {
                    return Err(WorkflowError::rejected(
                        "Bestätigung EOG requires the Versorgungsart (CCI+Z36: ZC9/ZD0/ZE3)"
                            .to_owned(),
                    ));
                }
                if !accepted && reason.is_none() {
                    return Err(WorkflowError::rejected(
                        "Ablehnung EOG requires a reason (EBD E_0615: A02/A04/A05)".to_owned(),
                    ));
                }
                let response_pid = Pruefidentifikator::new(eog_response_pid(accepted))
                    .map_err(|e| WorkflowError::rejected(e.clone()))?;

                // Outbound UTILMD 55014/55015 to the NB.
                let mut outbox = vec![PendingOutbox::new(
                    "UTILMD",
                    data.sender.as_str(),
                    serde_json::json!({
                        "direction":      "outbound",
                        "pid":            response_pid.as_u32(),
                        "sender":         data.receiver.as_str(),
                        "receiver":       data.sender.as_str(),
                        "malo":           data.location_id.as_str(),
                        "process_date":   data.process_date,
                        "versorgungsart": versorgungsart.map(Versorgungsart::code),
                        "bilanzkreis":    bilanzkreis,
                        "reason":         reason,
                    }),
                )];
                if accepted {
                    // The E/G's own marktd records the fallback supply from
                    // this event (it is now the supplier of record).
                    outbox.push(process_completed_outbox(
                        data,
                        versorgungsart,
                        bilanzkreis.as_deref(),
                        false,
                    ));
                }
                Ok(WorkflowOutput::with_outbox(
                    vec![EogEvent::AntwortGesendet {
                        response_pid,
                        accepted,
                        versorgungsart,
                        bilanzkreis,
                        reason,
                    }],
                    outbox,
                ))
            }

            EogCommand::TimeoutExpired { deadline_id, label } => match state {
                // Initiator: silence never blocks the statutory fallback —
                // assign with the pre-deposited default Bilanzkreis
                // (GPKE Teil 2 Kap. 2.3 SD Schritt 3).
                EogState::Angemeldet(data) if label.as_ref() == EOG_RESPONSE_WINDOW_LABEL => {
                    Ok(WorkflowOutput::with_outbox(
                        vec![EogEvent::ZugeordnetOhneAntwort { deadline_id }],
                        vec![process_completed_outbox(data, None, None, true)],
                    ))
                }
                s if s.is_terminal() => Ok(vec![].into()),
                _ => Ok(vec![EogEvent::DeadlineExpired { deadline_id, label }].into()),
            },
        }
    }
}

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

#[cfg(test)]
mod tests {
    use mako_engine::{ids::DeadlineId, workflow::Workflow};

    use super::*;

    fn pid(code: u32) -> Pruefidentifikator {
        Pruefidentifikator::new(code).unwrap()
    }
    fn mcod(s: &str) -> MarktpartnerCode {
        MarktpartnerCode::new(s)
    }
    fn malo(s: &str) -> MaLo {
        MaLo::new(s)
    }
    fn mref(s: &str) -> MessageRef {
        MessageRef::new(s)
    }
    fn now() -> time::OffsetDateTime {
        time::macros::datetime!(2026-07-01 10:00:00 UTC)
    }

    fn anmelden_cmd() -> EogCommand {
        EogCommand::Anmelden {
            pid: pid(55013),
            sender: mcod("9900357000004"),
            receiver: mcod("9900357000011"),
            location_id: malo("51238696781"),
            process_date: "20260615".to_owned(), // retroactive Zuordnungsbeginn
            transaktionsgrund: "ZT7".to_owned(), // Kündigung durch Kunde
            haushaltskunde: Some(true),
        }
    }

    fn receive_anmeldung_cmd(ok: bool) -> EogCommand {
        EogCommand::ReceiveAnmeldung {
            pid: pid(55013),
            sender: mcod("9900357000004"),
            receiver: mcod("9900357000011"),
            location_id: malo("51238696781"),
            document_date: "20260701".to_owned(),
            process_date: "20260615".to_owned(),
            message_ref: mref("EOG-001"),
            transaktionsgrund: "ZT7".to_owned(),
            haushaltskunde: Some(true),
            validation_passed: ok,
            validation_errors: if ok {
                vec![]
            } else {
                vec!["missing mandatory segment".to_owned()]
            },
            received_at: now(),
        }
    }

    fn apply_all(init: EogState, events: &[EogEvent]) -> EogState {
        events.iter().fold(init, GpkeEogWorkflow::apply)
    }

    // ── NB initiator ──────────────────────────────────────────────────────────

    #[test]
    fn initiator_happy_path_zugeordnet() {
        let out = GpkeEogWorkflow::handle(&EogState::New, anmelden_cmd()).unwrap();
        assert_eq!(out.events.len(), 1);
        // UTILMD 55013 wire message + ProcessInitiated notification.
        assert_eq!(out.outbox.len(), 2);
        assert_eq!(out.outbox[0].message_type.as_ref(), "UTILMD");
        assert_eq!(out.outbox[0].payload["transaktionsgrund"], "ZT7");
        assert_eq!(out.outbox[1].message_type.as_ref(), "ProcessInitiated");
        let state = apply_all(EogState::New, &out.events);
        assert!(matches!(state, EogState::Angemeldet(_)));

        let out = GpkeEogWorkflow::handle(
            &state,
            EogCommand::ReceiveAntwort {
                response_pid: pid(55014),
                accepted: true,
                versorgungsart: Some(Versorgungsart::Ersatzversorgung),
                bilanzkreis: Some("11XGRUNDV-BK--I".to_owned()),
                reason: None,
            },
        )
        .unwrap();
        // ProcessCompleted drives marktd's Ersatzversorgung transition.
        assert_eq!(out.outbox.len(), 1);
        assert_eq!(out.outbox[0].message_type.as_ref(), "ProcessCompleted");
        let payload = &out.outbox[0].payload;
        assert_eq!(payload["pid"], 55013);
        assert_eq!(payload["eog_art"], "ERSATZVERSORGUNG");
        assert_eq!(payload["process_date"], "20260615");
        assert_eq!(payload["ohne_antwort"], false);
        let state = apply_all(state, &out.events);
        assert!(matches!(
            state,
            EogState::Zugeordnet {
                versorgungsart: Some(Versorgungsart::Ersatzversorgung),
                ohne_antwort: false,
                ..
            }
        ));
    }

    #[test]
    fn initiator_grundversorgung_classification_from_antwort() {
        let out = GpkeEogWorkflow::handle(&EogState::New, anmelden_cmd()).unwrap();
        let state = apply_all(EogState::New, &out.events);
        let out = GpkeEogWorkflow::handle(
            &state,
            EogCommand::ReceiveAntwort {
                response_pid: pid(55014),
                accepted: true,
                versorgungsart: Some(Versorgungsart::Grundversorgung),
                bilanzkreis: Some("11XGRUNDV-BK--I".to_owned()),
                reason: None,
            },
        )
        .unwrap();
        assert_eq!(out.outbox[0].payload["eog_art"], "GRUNDVERSORGUNG");
    }

    #[test]
    fn initiator_ablehnung() {
        let out = GpkeEogWorkflow::handle(&EogState::New, anmelden_cmd()).unwrap();
        let state = apply_all(EogState::New, &out.events);
        let out = GpkeEogWorkflow::handle(
            &state,
            EogCommand::ReceiveAntwort {
                response_pid: pid(55015),
                accepted: false,
                versorgungsart: None,
                bilanzkreis: None,
                reason: Some("A02".to_owned()),
            },
        )
        .unwrap();
        assert!(out.outbox.is_empty());
        let state = apply_all(state, &out.events);
        assert!(matches!(state, EogState::Abgelehnt { .. }));
    }

    #[test]
    fn initiator_timeout_assigns_with_default_bk() {
        // GPKE Teil 2 Kap. 2.3 SD Schritt 3: silence never blocks the
        // statutory fallback supply.
        let out = GpkeEogWorkflow::handle(&EogState::New, anmelden_cmd()).unwrap();
        let state = apply_all(EogState::New, &out.events);
        let out = GpkeEogWorkflow::handle(
            &state,
            EogCommand::TimeoutExpired {
                deadline_id: DeadlineId::new(),
                label: EOG_RESPONSE_WINDOW_LABEL.into(),
            },
        )
        .unwrap();
        assert_eq!(out.outbox.len(), 1);
        assert_eq!(out.outbox[0].message_type.as_ref(), "ProcessCompleted");
        // Classification defaults to Ersatzversorgung (ipso iure, §38 Abs. 1).
        assert_eq!(out.outbox[0].payload["eog_art"], "ERSATZVERSORGUNG");
        assert_eq!(out.outbox[0].payload["ohne_antwort"], true);
        let state = apply_all(state, &out.events);
        assert!(matches!(
            state,
            EogState::Zugeordnet {
                versorgungsart: None,
                ohne_antwort: true,
                ..
            }
        ));
    }

    #[test]
    fn initiator_requires_transaktionsgrund() {
        let result = GpkeEogWorkflow::handle(
            &EogState::New,
            EogCommand::Anmelden {
                pid: pid(55013),
                sender: mcod("9900357000004"),
                receiver: mcod("9900357000011"),
                location_id: malo("51238696781"),
                process_date: "20260701".to_owned(),
                transaktionsgrund: "  ".to_owned(),
                haushaltskunde: None,
            },
        );
        assert!(result.is_err());
    }

    #[test]
    fn initiator_wrong_pid_rejected() {
        let result = GpkeEogWorkflow::handle(
            &EogState::New,
            EogCommand::Anmelden {
                pid: pid(55001),
                sender: mcod("9900357000004"),
                receiver: mcod("9900357000011"),
                location_id: malo("51238696781"),
                process_date: "20260701".to_owned(),
                transaktionsgrund: "ZT7".to_owned(),
                haushaltskunde: None,
            },
        );
        assert!(result.is_err());
    }

    // ── LF/E-G responder ──────────────────────────────────────────────────────

    #[test]
    fn responder_happy_path_bestaetigung() {
        let out = GpkeEogWorkflow::handle(&EogState::New, receive_anmeldung_cmd(true)).unwrap();
        assert_eq!(out.events.len(), 2); // AnmeldungErhalten + ValidationPassed
        assert_eq!(out.deadlines.len(), 2); // APERAK 45-min + answer window
        let state = apply_all(EogState::New, &out.events);
        assert!(matches!(state, EogState::ValidationPassed(_)));

        let out = GpkeEogWorkflow::handle(
            &state,
            EogCommand::SendAntwort {
                accepted: true,
                versorgungsart: Some(Versorgungsart::Grundversorgung),
                bilanzkreis: Some("11XGRUNDV-BK--I".to_owned()),
                reason: None,
            },
        )
        .unwrap();
        // UTILMD 55014 wire message + ProcessCompleted for the E/G's marktd.
        assert_eq!(out.outbox.len(), 2);
        assert_eq!(out.outbox[0].message_type.as_ref(), "UTILMD");
        assert_eq!(out.outbox[0].payload["pid"], 55014);
        assert_eq!(out.outbox[0].payload["versorgungsart"], "ZD0");
        assert_eq!(out.outbox[1].message_type.as_ref(), "ProcessCompleted");
        assert_eq!(out.outbox[1].payload["eog_art"], "GRUNDVERSORGUNG");
        let state = apply_all(state, &out.events);
        assert!(
            matches!(state, EogState::AntwortGesendet { response_pid, accepted: true, .. }
                if response_pid.as_u32() == 55014)
        );
    }

    #[test]
    fn responder_bestaetigung_requires_versorgungsart() {
        let out = GpkeEogWorkflow::handle(&EogState::New, receive_anmeldung_cmd(true)).unwrap();
        let state = apply_all(EogState::New, &out.events);
        let result = GpkeEogWorkflow::handle(
            &state,
            EogCommand::SendAntwort {
                accepted: true,
                versorgungsart: None,
                bilanzkreis: None,
                reason: None,
            },
        );
        assert!(result.is_err());
    }

    #[test]
    fn responder_ablehnung_requires_reason() {
        let out = GpkeEogWorkflow::handle(&EogState::New, receive_anmeldung_cmd(true)).unwrap();
        let state = apply_all(EogState::New, &out.events);
        let result = GpkeEogWorkflow::handle(
            &state,
            EogCommand::SendAntwort {
                accepted: false,
                versorgungsart: None,
                bilanzkreis: None,
                reason: None,
            },
        );
        assert!(result.is_err());
    }

    #[test]
    fn responder_ablehnung() {
        let out = GpkeEogWorkflow::handle(&EogState::New, receive_anmeldung_cmd(true)).unwrap();
        let state = apply_all(EogState::New, &out.events);
        let out = GpkeEogWorkflow::handle(
            &state,
            EogCommand::SendAntwort {
                accepted: false,
                versorgungsart: None,
                bilanzkreis: None,
                reason: Some("A05".to_owned()),
            },
        )
        .unwrap();
        assert_eq!(out.outbox.len(), 1); // UTILMD 55015 only — no ProcessCompleted
        assert_eq!(out.outbox[0].payload["pid"], 55015);
        let state = apply_all(state, &out.events);
        assert!(
            matches!(state, EogState::AntwortGesendet { response_pid, accepted: false, .. }
                if response_pid.as_u32() == 55015)
        );
    }

    #[test]
    fn responder_validation_failure_rejects_with_aperak() {
        let out = GpkeEogWorkflow::handle(&EogState::New, receive_anmeldung_cmd(false)).unwrap();
        assert_eq!(out.outbox.len(), 1);
        assert_eq!(out.outbox[0].message_type.as_ref(), "APERAK");
        let state = apply_all(EogState::New, &out.events);
        assert!(matches!(state, EogState::Rejected { .. }));
    }

    #[test]
    fn responder_timeout_rejects() {
        let out = GpkeEogWorkflow::handle(&EogState::New, receive_anmeldung_cmd(true)).unwrap();
        let state = apply_all(EogState::New, &out.events);
        let out = GpkeEogWorkflow::handle(
            &state,
            EogCommand::TimeoutExpired {
                deadline_id: DeadlineId::new(),
                label: EOG_RESPONSE_WINDOW_LABEL.into(),
            },
        )
        .unwrap();
        let state = apply_all(state, &out.events);
        assert!(matches!(state, EogState::Rejected { .. }));
    }

    // ── Versorgungsart codes ──────────────────────────────────────────────────

    /// **The E/G must be told.** `makod` delivers a CloudEvent only for an
    /// outbox entry, and an APERAK is a technical acknowledgement — so without
    /// its own `ProcessInitiated` the inbound 55013 never reaches `processd`'s
    /// LF module and the 15:00-Uhr-am-ÜT Frist lapses unanswered and unseen.
    #[test]
    fn an_inbound_anmeldung_notifies_the_eog_supplier() {
        let out = GpkeEogWorkflow::handle(&EogState::New, receive_anmeldung_cmd(true)).unwrap();
        let notification = out
            .outbox
            .iter()
            .find(|o| &*o.message_type == "ProcessInitiated")
            .expect("the E/G is notified of the Zuordnung");
        assert_eq!(notification.payload["pid"], EOG_ANMELDUNG_PID);
        assert_eq!(notification.payload["malo_id"], "51238696781");
        // The Transaktionsgrund reaches the walk; without it `E_0615` cannot
        // tell a Grundversorgungs- from an Ersatzversorgungsfall.
        assert!(notification.payload.get("transaktionsgrund").is_some());
        assert_eq!(&*notification.recipient, "9900357000011");
    }

    #[test]
    fn versorgungsart_code_roundtrip() {
        for art in [
            Versorgungsart::Ersatzversorgung,
            Versorgungsart::Grundversorgung,
            Versorgungsart::Ersatzbelieferung,
        ] {
            assert_eq!(Versorgungsart::from_code(art.code()), Some(art));
        }
        assert_eq!(Versorgungsart::from_code("E06"), None);
    }

    /// **`ZZD` is a Transaktionsgrund, not a Versorgungsart.** UTILMD AHB Strom
    /// 2.2 publishes exactly `ZC9`, `ZD0` and `ZE3` for `SG10 CCI+Z36` DE 7037;
    /// `ZZD` Übergangsversorgung lives in `SG4 STS+7` DE 9013 element 2, on the
    /// 55013/55014/55015 and on the 55004/55005/55006 under Bedingung `[686]`.
    /// Accepting it here put a qualifier into DE 7037 the AHB does not define,
    /// and the counterparty rejects the message.
    #[test]
    fn zzd_is_not_a_versorgungsart() {
        assert_eq!(Versorgungsart::from_code(UEBERGANGSVERSORGUNG), None);
        assert!(
            [
                Versorgungsart::Ersatzversorgung,
                Versorgungsart::Grundversorgung,
                Versorgungsart::Ersatzbelieferung,
            ]
            .iter()
            .all(|a| a.code() != UEBERGANGSVERSORGUNG)
        );
    }

    #[test]
    fn timeout_in_terminal_state_is_noop() {
        let out = GpkeEogWorkflow::handle(&EogState::New, anmelden_cmd()).unwrap();
        let state = apply_all(EogState::New, &out.events);
        let out = GpkeEogWorkflow::handle(
            &state,
            EogCommand::ReceiveAntwort {
                response_pid: pid(55014),
                accepted: true,
                versorgungsart: Some(Versorgungsart::Ersatzversorgung),
                bilanzkreis: None,
                reason: None,
            },
        )
        .unwrap();
        let state = apply_all(state, &out.events);

        let out = GpkeEogWorkflow::handle(
            &state,
            EogCommand::TimeoutExpired {
                deadline_id: DeadlineId::new(),
                label: EOG_RESPONSE_WINDOW_LABEL.into(),
            },
        )
        .unwrap();
        assert!(out.events.is_empty());
    }

    /// One wire code, one spelling. `edi-energy` carries the DE 9013 table this
    /// crate restates a single value from, and the two must not drift.
    #[test]
    fn the_code_matches_the_wire_table() {
        assert_eq!(
            super::UEBERGANGSVERSORGUNG,
            edi_energy::utilmd_codes::transaktionsgrund::UEBERGANGSVERSORGUNG
        );
    }
}