File size: 37,755 Bytes
1c4c66b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package billing

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/samber/lo"
	"github.com/samber/mo"

	"github.com/openmeterio/openmeter/openmeter/app"
	"github.com/openmeterio/openmeter/openmeter/billing/models/externalid"
	"github.com/openmeterio/openmeter/openmeter/billing/models/totals"
	"github.com/openmeterio/openmeter/openmeter/customer"
	"github.com/openmeterio/openmeter/openmeter/streaming"
	"github.com/openmeterio/openmeter/pkg/currencyx"
	"github.com/openmeterio/openmeter/pkg/expand"
	"github.com/openmeterio/openmeter/pkg/models"
	"github.com/openmeterio/openmeter/pkg/pagination"
	"github.com/openmeterio/openmeter/pkg/slicesx"
	"github.com/openmeterio/openmeter/pkg/timeutil"
)

type StandardInvoiceStatusCategory string

const (
	StandardInvoiceStatusCategoryGathering         StandardInvoiceStatusCategory = "gathering"
	StandardInvoiceStatusCategoryDraft             StandardInvoiceStatusCategory = "draft"
	StandardInvoiceStatusCategoryDelete            StandardInvoiceStatusCategory = "delete"
	StandardInvoiceStatusCategoryDeleted           StandardInvoiceStatusCategory = "deleted"
	StandardInvoiceStatusCategoryIssuing           StandardInvoiceStatusCategory = "issuing"
	StandardInvoiceStatusCategoryIssued            StandardInvoiceStatusCategory = "issued"
	StandardInvoiceStatusCategoryPaymentProcessing StandardInvoiceStatusCategory = "payment_processing"
	StandardInvoiceStatusCategoryOverdue           StandardInvoiceStatusCategory = "overdue"
	StandardInvoiceStatusCategoryPaid              StandardInvoiceStatusCategory = "paid"
	StandardInvoiceStatusCategoryUncollectible     StandardInvoiceStatusCategory = "uncollectible"
	StandardInvoiceStatusCategoryVoided            StandardInvoiceStatusCategory = "voided"
)

func (s StandardInvoiceStatusCategory) MatchesInvoiceStatus(status StandardInvoiceStatus) bool {
	return status.ShortStatus() == string(s)
}

type StandardInvoiceStatus string

const (
	// StandardInvoiceStatusGathering is the status of an invoice that is gathering the items to be invoiced.
	StandardInvoiceStatusGathering StandardInvoiceStatus = "gathering"

	StandardInvoiceStatusDraftCreated StandardInvoiceStatus = "draft.created"
	// StandardInvoiceStatusDraftWaitingForCollection is the status of an invoice that is waiting for the collection to be possible (e.g. collection period has passed)
	StandardInvoiceStatusDraftWaitingForCollection StandardInvoiceStatus = "draft.waiting_for_collection"
	// StandardInvoiceStatusDraftCollecting is the status of an invoice that is collecting the items to be invoiced.
	StandardInvoiceStatusDraftCollecting           StandardInvoiceStatus = "draft.collecting"
	StandardInvoiceStatusDraftUpdating             StandardInvoiceStatus = "draft.updating"
	StandardInvoiceStatusDraftManualApprovalNeeded StandardInvoiceStatus = "draft.manual_approval_needed"
	StandardInvoiceStatusDraftValidating           StandardInvoiceStatus = "draft.validating"
	StandardInvoiceStatusDraftInvalid              StandardInvoiceStatus = "draft.invalid"
	StandardInvoiceStatusDraftSyncing              StandardInvoiceStatus = "draft.syncing"
	StandardInvoiceStatusDraftSyncFailed           StandardInvoiceStatus = "draft.sync_failed"
	StandardInvoiceStatusDraftWaitingAutoApproval  StandardInvoiceStatus = "draft.waiting_auto_approval"
	StandardInvoiceStatusDraftReadyToIssue         StandardInvoiceStatus = "draft.ready_to_issue"

	StandardInvoiceStatusDeleteInProgress StandardInvoiceStatus = "delete.in_progress"
	StandardInvoiceStatusDeleteSyncing    StandardInvoiceStatus = "delete.syncing"
	StandardInvoiceStatusDeleteFailed     StandardInvoiceStatus = "delete.failed"
	StandardInvoiceStatusDeleted          StandardInvoiceStatus = "deleted"

	StandardInvoiceStatusIssuingSyncing             StandardInvoiceStatus = "issuing.syncing"
	StandardInvoiceStatusIssuingSyncFailed          StandardInvoiceStatus = "issuing.failed"
	StandardInvoiceStatusIssuingChargeBooking       StandardInvoiceStatus = "issuing.charge_booking"
	StandardInvoiceStatusIssuingChargeBookingFailed StandardInvoiceStatus = "issuing.charge_booking_failed"

	StandardInvoiceStatusIssued StandardInvoiceStatus = "issued"

	StandardInvoiceStatusPaymentProcessingPending                           StandardInvoiceStatus = "payment_processing.pending"
	StandardInvoiceStatusPaymentProcessingBookingAuthorized                 StandardInvoiceStatus = "payment_processing.booking_authorized"
	StandardInvoiceStatusPaymentProcessingBookingAuthorizedFailed           StandardInvoiceStatus = "payment_processing.booking_authorized_failed"
	StandardInvoiceStatusPaymentProcessingBookingAuthorizedAndSettled       StandardInvoiceStatus = "payment_processing.booking_authorized_and_settled"
	StandardInvoiceStatusPaymentProcessingBookingAuthorizedAndSettledFailed StandardInvoiceStatus = "payment_processing.booking_authorized_and_settled_failed"
	StandardInvoiceStatusPaymentProcessingAuthorized                        StandardInvoiceStatus = "payment_processing.authorized"
	StandardInvoiceStatusPaymentProcessingFailed                            StandardInvoiceStatus = "payment_processing.failed"
	StandardInvoiceStatusPaymentProcessingActionRequired                    StandardInvoiceStatus = "payment_processing.action_required"
	StandardInvoiceStatusPaymentProcessingBookingSettled                    StandardInvoiceStatus = "payment_processing.booking_settled"
	StandardInvoiceStatusPaymentProcessingBookingSettledFailed              StandardInvoiceStatus = "payment_processing.booking_settled_failed"

	// These are separate statuses to allow for more gradual filtering on the API without having to understand sub-statuses

	StandardInvoiceStatusOverdue StandardInvoiceStatus = "overdue"

	StandardInvoiceStatusPaid StandardInvoiceStatus = "paid"

	StandardInvoiceStatusUncollectible StandardInvoiceStatus = "uncollectible"

	StandardInvoiceStatusVoided StandardInvoiceStatus = "voided"
)

var validStatuses = []StandardInvoiceStatus{
	StandardInvoiceStatusGathering,
	StandardInvoiceStatusDraftCreated,
	StandardInvoiceStatusDraftWaitingForCollection,
	StandardInvoiceStatusDraftCollecting,
	StandardInvoiceStatusDraftUpdating,
	StandardInvoiceStatusDraftManualApprovalNeeded,
	StandardInvoiceStatusDraftValidating,
	StandardInvoiceStatusDraftInvalid,
	StandardInvoiceStatusDraftSyncing,
	StandardInvoiceStatusDraftSyncFailed,
	StandardInvoiceStatusDraftWaitingAutoApproval,
	StandardInvoiceStatusDraftReadyToIssue,

	StandardInvoiceStatusDeleteInProgress,
	StandardInvoiceStatusDeleteSyncing,
	StandardInvoiceStatusDeleteFailed,
	StandardInvoiceStatusDeleted,

	StandardInvoiceStatusIssuingSyncing,
	StandardInvoiceStatusIssuingSyncFailed,
	StandardInvoiceStatusIssuingChargeBooking,
	StandardInvoiceStatusIssuingChargeBookingFailed,

	StandardInvoiceStatusIssued,

	StandardInvoiceStatusPaymentProcessingPending,
	StandardInvoiceStatusPaymentProcessingBookingAuthorized,
	StandardInvoiceStatusPaymentProcessingBookingAuthorizedFailed,
	StandardInvoiceStatusPaymentProcessingBookingAuthorizedAndSettled,
	StandardInvoiceStatusPaymentProcessingBookingAuthorizedAndSettledFailed,
	StandardInvoiceStatusPaymentProcessingAuthorized,
	StandardInvoiceStatusPaymentProcessingFailed,
	StandardInvoiceStatusPaymentProcessingActionRequired,
	StandardInvoiceStatusPaymentProcessingBookingSettled,
	StandardInvoiceStatusPaymentProcessingBookingSettledFailed,

	StandardInvoiceStatusOverdue,

	StandardInvoiceStatusPaid,

	StandardInvoiceStatusUncollectible,

	StandardInvoiceStatusVoided,
}

func (s StandardInvoiceStatus) Values() []string {
	return lo.Map(
		validStatuses,
		func(item StandardInvoiceStatus, _ int) string {
			return string(item)
		},
	)
}

func (s StandardInvoiceStatus) ShortStatus() string {
	parts := strings.SplitN(string(s), ".", 2)
	return parts[0]
}

type StandardInvoiceStatusMatcher interface {
	MatchesInvoiceStatus(StandardInvoiceStatus) bool
}

func (s StandardInvoiceStatus) Matches(statuses ...StandardInvoiceStatusMatcher) bool {
	for _, matcher := range statuses {
		if matcher.MatchesInvoiceStatus(s) {
			return true
		}
	}

	return false
}

func (s StandardInvoiceStatus) MatchesInvoiceStatus(status StandardInvoiceStatus) bool {
	return s == status
}

var failedStatuses = []StandardInvoiceStatus{
	StandardInvoiceStatusDraftSyncFailed,
	StandardInvoiceStatusIssuingSyncFailed,
	StandardInvoiceStatusIssuingChargeBookingFailed,
	StandardInvoiceStatusDeleteFailed,
	StandardInvoiceStatusPaymentProcessingBookingAuthorizedFailed,
	StandardInvoiceStatusPaymentProcessingBookingAuthorizedAndSettledFailed,
	StandardInvoiceStatusPaymentProcessingFailed,
	StandardInvoiceStatusPaymentProcessingBookingSettledFailed,
}

func (s StandardInvoiceStatus) IsFailed() bool {
	return lo.Contains(failedStatuses, s)
}

var finalStatuses = []StandardInvoiceStatus{
	StandardInvoiceStatusDeleted,
	StandardInvoiceStatusPaid,
	StandardInvoiceStatusUncollectible,
	StandardInvoiceStatusVoided,
}

func (s StandardInvoiceStatus) IsFinal() bool {
	return lo.Contains(finalStatuses, s)
}

func (s StandardInvoiceStatus) Validate() error {
	if !lo.Contains(validStatuses, s) {
		return fmt.Errorf("invalid invoice status: %s", s)
	}

	return nil
}

// InvoiceShortStatus represents the top-level status category of an invoice
// (e.g. "draft", "issued") as exposed in the API, in contrast to
// StandardInvoiceStatus which carries the full extended value (e.g. "draft.created").
// Valid values are derived from validStatuses via ShortStatus().
type InvoiceShortStatus string

// Values returns all valid short status values except the gathering, derived from the extended statuses.
// Satisfies expand.Expandable[InvoiceShortStatus] and the FromAPIStatusFilter constraint.
func (s InvoiceShortStatus) Values() []InvoiceShortStatus {
	unsupportedStatuses := []StandardInvoiceStatus{
		StandardInvoiceStatusGathering,
		StandardInvoiceStatusDeleteInProgress,
		StandardInvoiceStatusDeleteSyncing,
		StandardInvoiceStatusDeleteFailed,
		StandardInvoiceStatusDeleted,
	}
	return lo.Uniq(lo.Map(lo.Without(validStatuses, unsupportedStatuses...), func(st StandardInvoiceStatus, _ int) InvoiceShortStatus {
		return InvoiceShortStatus(st.ShortStatus())
	}))
}

func (s InvoiceShortStatus) Validate() error {
	if !lo.Contains(s.Values(), s) {
		return fmt.Errorf("invalid invoice short status: %s", s)
	}

	return nil
}

type StandardInvoiceBase struct {
	Namespace string `json:"namespace"`
	ID        string `json:"id"`

	Number      string  `json:"number"`
	Description *string `json:"description,omitempty"`

	Type InvoiceType `json:"type"`

	Metadata map[string]string `json:"metadata"`

	Currency      currencyx.Code               `json:"currency,omitempty"`
	Status        StandardInvoiceStatus        `json:"status"`
	StatusDetails StandardInvoiceStatusDetails `json:"statusDetail,omitempty"`

	Period *timeutil.ClosedPeriod `json:"period,omitempty"`

	DueAt *time.Time `json:"dueDate,omitempty"`

	CreatedAt            time.Time    `json:"createdAt"`
	UpdatedAt            time.Time    `json:"updatedAt"`
	VoidedAt             *time.Time   `json:"voidedAt,omitempty"`
	DraftUntil           *time.Time   `json:"draftUntil,omitempty"`
	IssuedAt             *time.Time   `json:"issuedAt,omitempty"`
	DeletedAt            *time.Time   `json:"deletedAt,omitempty"`
	DeletionSource       ChangeSource `json:"deletionSource,omitempty"`
	SentToCustomerAt     *time.Time   `json:"sentToCustomerAt,omitempty"`
	QuantitySnapshotedAt *time.Time   `json:"quantitySnapshotedAt,omitempty"`

	CollectionAt *time.Time `json:"collectionAt,omitempty"`
	// PaymentProcessingEnteredAt stores when the invoice first entered payment processing
	PaymentProcessingEnteredAt *time.Time `json:"paymentProcessingEnteredAt,omitempty"`

	// Customer is either a snapshot of the contact information of the customer at the time of invoice being sent
	// or the data from the customer entity (draft state)
	// This is required so that we are not modifying the invoice after it has been sent to the customer.
	Customer InvoiceCustomer `json:"customer"`
	Supplier SupplierContact `json:"supplier"`
	Workflow InvoiceWorkflow `json:"workflow,omitempty"`

	ExternalIDs externalid.InvoiceExternalIDs `json:"externalIds,omitempty"`

	SchemaLevel int `json:"schemaLevel"`

	// TODO[later]: Let's also include the totals here, as that's part of the invoice db table
}

func (i StandardInvoiceBase) Validate() error {
	var outErr error

	if err := i.Type.Validate(); err != nil {
		outErr = errors.Join(outErr, ValidationWithFieldPrefix("type", err))
	}

	if err := i.Currency.Validate(); err != nil {
		outErr = errors.Join(outErr, ValidationWithFieldPrefix("currency", err))
	}

	if err := i.Status.Validate(); err != nil {
		outErr = errors.Join(outErr, ValidationWithFieldPrefix("status", err))
	}

	if err := i.Customer.Validate(); err != nil {
		outErr = errors.Join(outErr, ValidationWithFieldPrefix("customer", err))
	}

	if err := i.Supplier.Validate(); err != nil {
		outErr = errors.Join(outErr, ValidationWithFieldPrefix("supplier", err))
	}

	if i.Period != nil {
		if err := i.Period.Validate(); err != nil {
			outErr = errors.Join(outErr, ValidationWithFieldPrefix("period", err))
		}
	}

	return outErr
}

func (i StandardInvoiceBase) DefaultCollectionAtForStandardInvoice() time.Time {
	if i.CollectionAt == nil {
		return i.CreatedAt
	}

	return lo.FromPtr(i.CollectionAt)
}

func (i StandardInvoiceBase) GetDeletedAt() *time.Time {
	return i.DeletedAt
}

func (i StandardInvoiceBase) GetID() string {
	return i.ID
}

func (i StandardInvoiceBase) GetInvoiceID() InvoiceID {
	return InvoiceID{
		Namespace: i.Namespace,
		ID:        i.ID,
	}
}

func (i StandardInvoiceBase) GetCustomerID() customer.CustomerID {
	return customer.CustomerID{
		Namespace: i.Namespace,
		ID:        i.Customer.CustomerID,
	}
}

var _ GenericInvoice = (*StandardInvoice)(nil)

type StandardInvoice struct {
	StandardInvoiceBase `json:",inline"`

	// Entities external to the invoice itself
	Lines            StandardInvoiceLines `json:"lines,omitempty"`
	ValidationIssues ValidationIssues     `json:"validationIssues,omitempty"`

	Totals totals.Totals `json:"totals"`

	// private fields required by the service
	ExpandedFields StandardInvoiceExpands `json:"-"`
}

func (i StandardInvoice) Validate() error {
	var outErr error

	if err := i.StandardInvoiceBase.Validate(); err != nil {
		outErr = errors.Join(outErr, err)
	}

	if err := i.Lines.Validate(); err != nil {
		outErr = errors.Join(outErr, ValidationWithFieldPrefix("lines", err))
	}

	if i.Lines.IsPresent() {
		for _, line := range i.Lines.OrEmpty() {
			if line.Currency != i.Currency {
				outErr = errors.Join(outErr, fmt.Errorf("line[%s]: currency[%s] is not equal to invoice currency[%s]", line.ID, line.Currency, i.Currency))
			}
		}
	}

	return outErr
}

func (i StandardInvoice) CustomerID() customer.CustomerID {
	return customer.CustomerID{
		Namespace: i.Namespace,
		ID:        i.Customer.CustomerID,
	}
}

func (i StandardInvoice) AsInvoice() Invoice {
	return Invoice{
		t:               InvoiceTypeStandard,
		standardInvoice: &i,
	}
}

func (i StandardInvoice) GetType() InvoiceType {
	return InvoiceTypeStandard
}

func (i StandardInvoice) CloneAsGenericInvoice() (GenericInvoice, error) {
	cloned, err := i.Clone()
	if err != nil {
		return nil, err
	}

	return &cloned, nil
}

func (i StandardInvoice) GetGenericLines() mo.Option[[]GenericInvoiceLine] {
	if !i.Lines.IsPresent() {
		return mo.None[[]GenericInvoiceLine]()
	}

	return mo.Some(lo.Map(i.Lines.OrEmpty(), func(l *StandardLine, _ int) GenericInvoiceLine {
		return &standardInvoiceLineGenericWrapper{StandardLine: l}
	}))
}

func (i *StandardInvoice) SetLines(lines []GenericInvoiceLine) error {
	mappedLines, err := slicesx.MapWithErr(lines, func(l GenericInvoiceLine) (*StandardLine, error) {
		line, err := l.AsInvoiceLine().AsStandardLine()
		if err != nil {
			return nil, err
		}

		return &line, nil
	})
	if err != nil {
		return fmt.Errorf("mapping lines: %w", err)
	}

	i.Lines = NewStandardInvoiceLines(mappedLines)
	return nil
}

func (i *StandardInvoice) UnsetLines() {
	i.Lines = StandardInvoiceLines{}
}

func (i *StandardInvoice) MergeValidationIssues(errIn error, reportingComponent ComponentName) error {
	i.ValidationIssues = lo.Filter(i.ValidationIssues, func(issue ValidationIssue, _ int) bool {
		return issue.Component != reportingComponent
	})

	// Regardless of the errors we need to add them to the invoice, in case the upstream service
	// decides to save the invoice.
	newIssues, finalErrs := ToValidationIssues(errIn)
	i.ValidationIssues = append(i.ValidationIssues, newIssues...)

	return finalErrs
}

func (i *StandardInvoice) HasCriticalValidationIssues() bool {
	_, found := lo.Find(i.ValidationIssues, func(issue ValidationIssue) bool {
		return issue.Severity == ValidationIssueSeverityCritical
	})

	return found
}

// RemoveMetaForCompare returns a copy of the invoice without the fields that are not relevant for higher level
// tests that compare invoices. What gets removed:
// - Line's DB state
// - Line's dependencies are marked as resolved
// - Parent pointers are removed
func (i StandardInvoice) RemoveMetaForCompare() (StandardInvoice, error) {
	invoice := i
	newLines, err := i.Lines.MapWithErr(func(line *StandardLine) (*StandardLine, error) {
		return line.RemoveMetaForCompare()
	})
	if err != nil {
		return StandardInvoice{}, err
	}

	invoice.Lines = newLines

	return invoice, nil
}

// getLeafLines returns the leaf lines
func (i *StandardInvoice) getLeafLines() DetailedLines {
	out := []DetailedLine{}

	for _, line := range i.Lines.OrEmpty() {
		// Skip non leaf nodes

		out = append(out, line.DetailedLines...)
	}

	return out
}

type DetailedLineWithResolvedTaxConfig struct {
	DetailedLine
	TaxConfig *TaxConfig
}

// GetLeafLinesWithResolvedTaxConfig returns invoice leaf lines together with the effective tax
// config inherited from the parent standard line.
func (i *StandardInvoice) GetLeafLinesWithResolvedTaxConfig() []DetailedLineWithResolvedTaxConfig {
	out := make([]DetailedLineWithResolvedTaxConfig, 0)

	for _, parentLine := range i.Lines.OrEmpty() {
		taxConfig := MergeTaxConfigs(FromProductCatalog(i.Workflow.Config.Invoicing.DefaultTaxConfig), parentLine.TaxConfig)
		for _, line := range parentLine.DetailedLines {
			out = append(out, DetailedLineWithResolvedTaxConfig{
				DetailedLine: line,
				TaxConfig:    taxConfig,
			})
		}
	}

	return out
}

func (i StandardInvoice) Clone() (StandardInvoice, error) {
	clone := i

	clonedLines, err := i.Lines.Clone()
	if err != nil {
		return StandardInvoice{}, err
	}

	clone.Lines = clonedLines
	clone.ValidationIssues = i.ValidationIssues.Clone()
	clone.Totals = i.Totals

	return clone, nil
}

func (i StandardInvoice) RemoveCircularReferences() (StandardInvoice, error) {
	clone, err := i.Clone()
	if err != nil {
		return StandardInvoice{}, err
	}

	clone.Lines, err = clone.Lines.MapWithErr(func(line *StandardLine) (*StandardLine, error) {
		return line.RemoveCircularReferences()
	})
	if err != nil {
		return StandardInvoice{}, err
	}

	return clone, nil
}

func (i *StandardInvoice) SortLines() {
	if !i.Lines.IsPresent() {
		return
	}

	i.Lines.Sort()
}

type StandardInvoiceLines struct {
	mo.Option[StandardLines]
}

func NewStandardInvoiceLines(children []*StandardLine) StandardInvoiceLines {
	// Note: this helps with test equality checks
	if len(children) == 0 {
		children = nil
	}

	return StandardInvoiceLines{mo.Some(StandardLines(children))}
}

func (i StandardInvoiceLines) Validate() error {
	return errors.Join(lo.Map(i.OrEmpty(), func(line *StandardLine, idx int) error {
		return ValidationWithFieldPrefix(fmt.Sprintf("%d", idx), line.Validate())
	})...)
}

func (c StandardInvoiceLines) Map(fn func(*StandardLine) *StandardLine) StandardInvoiceLines {
	if !c.IsPresent() {
		return c
	}

	return StandardInvoiceLines{
		mo.Some(
			c.OrEmpty().Map(fn),
		),
	}
}

func (c StandardInvoiceLines) MapWithErr(fn func(*StandardLine) (*StandardLine, error)) (StandardInvoiceLines, error) {
	if !c.IsPresent() {
		return c, nil
	}

	res, err := slicesx.MapWithErr(c.OrEmpty(), fn)
	if err != nil {
		return StandardInvoiceLines{}, err
	}

	return StandardInvoiceLines{mo.Some(StandardLines(res))}, nil
}

func (c StandardInvoiceLines) WithNormalizedValues() (StandardInvoiceLines, error) {
	return c.MapWithErr(func(line *StandardLine) (*StandardLine, error) {
		return line.WithNormalizedValues()
	})
}

func (c StandardInvoiceLines) Clone() (StandardInvoiceLines, error) {
	return c.MapWithErr(func(l *StandardLine) (*StandardLine, error) {
		return l.Clone()
	})
}

func (c StandardInvoiceLines) GetByID(id string) *StandardLine {
	return lo.FindOrElse(c.Option.OrEmpty(), nil, func(line *StandardLine) bool {
		return line.ID == id
	})
}

func (c *StandardInvoiceLines) ReplaceByID(id string, newLine *StandardLine) bool {
	if c.IsAbsent() {
		return false
	}

	lines := c.OrEmpty()

	for i, line := range lines {
		if line.ID == id {
			// Let's preserve the DB state of the original line (as we are only replacing the current state)
			originalDBState := line.DBState

			lines[i] = newLine
			lines[i].DBState = originalDBState
			return true
		}
	}

	return false
}

func (c *StandardInvoiceLines) ReplaceLinesByID(lines ...*StandardLine) error {
	for _, line := range lines {
		if line == nil {
			return fmt.Errorf("line is required")
		}

		if c.GetByID(line.ID) == nil {
			return fmt.Errorf("replacing line[%s]: line not found", line.ID)
		}
	}

	for _, line := range lines {
		if ok := c.ReplaceByID(line.ID, line); !ok {
			return fmt.Errorf("replacing line[%s]", line.ID)
		}
	}

	return nil
}

func (c *StandardInvoiceLines) Sort() {
	if c.IsAbsent() {
		return
	}

	lines := c.OrEmpty()
	lines.Sort()
	c.Option = mo.Some(lines)
}

// NonDeletedLineCount returns the number of lines that are not deleted and have a valid status (e.g. we are ignoring split lines)
func (c StandardInvoiceLines) NonDeletedLineCount() int {
	return lo.CountBy(c.OrEmpty(), func(l *StandardLine) bool {
		return l.DeletedAt == nil
	})
}

func (c *StandardInvoiceLines) Append(l ...*StandardLine) {
	c.Option = mo.Some(append(c.OrEmpty(), l...))
}

func (c *StandardInvoiceLines) RemoveByID(id string) bool {
	toBeRemoved := c.GetByID(id)
	if toBeRemoved == nil {
		return false
	}

	c.Option = mo.Some(
		lo.Filter(c.Option.OrEmpty(), func(l *StandardLine, _ int) bool {
			return l.ID != id
		}),
	)

	return true
}

func (c StandardInvoiceLines) GetReferencedFeatureKeys() ([]string, error) {
	if c.IsAbsent() {
		return nil, nil
	}

	return c.OrEmpty().GetReferencedFeatureKeys()
}

type StandardInvoiceAvailableActions struct {
	Advance            *StandardInvoiceAvailableActionDetails `json:"advance,omitempty"`
	Approve            *StandardInvoiceAvailableActionDetails `json:"approve,omitempty"`
	Delete             *StandardInvoiceAvailableActionDetails `json:"delete,omitempty"`
	Retry              *StandardInvoiceAvailableActionDetails `json:"retry,omitempty"`
	Void               *StandardInvoiceAvailableActionDetails `json:"void,omitempty"`
	SnapshotQuantities *StandardInvoiceAvailableActionDetails `json:"snapshotQuantities,omitempty"`

	Invoice *StandardInvoiceAvailableActionInvoiceDetails `json:"invoice,omitempty"`
}

type StandardInvoiceAvailableActionDetails struct {
	ResultingState StandardInvoiceStatus `json:"resultingState"`
}

type StandardInvoiceAvailableActionInvoiceDetails struct{}

type StandardInvoiceStatusDetails struct {
	Immutable        bool                            `json:"immutable"`
	Failed           bool                            `json:"failed"`
	AvailableActions StandardInvoiceAvailableActions `json:"availableActions"`
}

const (
	CustomerUsageAttributionTypeVersionV1 = "customer_usage_attribution.v1"
	CustomerUsageAttributionTypeVersionV2 = "customer_usage_attribution.v2"
)

type (
	VersionedCustomerUsageAttribution struct {
		streaming.CustomerUsageAttribution `json:",inline"`
		Type                               string `json:"type"`
	}
)

type CreateInvoiceAdapterInput struct {
	Namespace string
	Customer  customer.Customer
	Profile   Profile
	Number    string
	Currency  currencyx.Code
	Status    StandardInvoiceStatus
	Metadata  map[string]string
	IssuedAt  time.Time

	Type         InvoiceType
	Description  *string
	DueAt        *time.Time
	CollectionAt *time.Time

	Totals totals.Totals
}

func (c CreateInvoiceAdapterInput) Validate() error {
	if c.Namespace == "" {
		return errors.New("namespace is required")
	}

	if err := c.Customer.Validate(); err != nil {
		return fmt.Errorf("customer: %w", err)
	}

	if err := c.Profile.Validate(); err != nil {
		return fmt.Errorf("profile: %w", err)
	}

	if c.Profile.Apps == nil {
		return errors.New("profile: apps must be expanded")
	}

	if err := c.Currency.Validate(); err != nil {
		return fmt.Errorf("currency: %w", err)
	}

	if err := c.Status.Validate(); err != nil {
		return fmt.Errorf("status: %w", err)
	}

	if err := c.Type.Validate(); err != nil {
		return fmt.Errorf("type: %w", err)
	}

	if err := c.Totals.Validate(); err != nil {
		return fmt.Errorf("totals: %w", err)
	}

	if c.Number == "" {
		return errors.New("invoice number is required")
	}

	if c.CollectionAt != nil && c.Status != StandardInvoiceStatusGathering {
		return errors.New("setting collectionAt is only allowed when creating gathering invoices")
	}

	return nil
}

type CreateInvoiceAdapterRespone = StandardInvoice

type AssociatedLineCountsAdapterResponse struct {
	Counts map[InvoiceID]int64
}

type (
	AdvanceInvoiceInput      = InvoiceID
	ApproveInvoiceInput      = InvoiceID
	ForceCollectInvoiceInput = InvoiceID
	PaymentAuthorizedInput   = InvoiceID
	RetryInvoiceInput        = InvoiceID
)

type UpdateStandardInvoiceAdapterInput = StandardInvoice

type GetInvoiceOwnershipAdapterInput = InvoiceID

type GetOwnershipAdapterResponse struct {
	Namespace  string
	InvoiceID  string
	CustomerID string
}

type DeleteInvoiceInput struct {
	// Invoice identifies the standard invoice to delete.
	Invoice InvoiceID
	// DeletionSource classifies why the invoice is being deleted.
	//
	// ChangeSourceAPIRequest means the delete came from the public invoice API.
	// ChangeSourceSystem means the delete came from internal billing, charge, or
	// subscription lifecycle code and should notify line engines about system
	// standard-line deletion.
	DeletionSource ChangeSource
}

func (i DeleteInvoiceInput) Validate() error {
	var errs []error

	if err := i.Invoice.Validate(); err != nil {
		errs = append(errs, fmt.Errorf("invoice: %w", err))
	}

	if err := i.DeletionSource.Validate(); err != nil {
		errs = append(errs, fmt.Errorf("deletion source: %w", err))
	}

	return errors.Join(errs...)
}

type DeleteInvoiceTriggerInput struct {
	Source ChangeSource
}

func (i DeleteInvoiceTriggerInput) Validate() error {
	if err := i.Source.Validate(); err != nil {
		return fmt.Errorf("source: %w", err)
	}

	return nil
}

var _ models.Validator = DeleteInvoiceTriggerInput{}

type UpdateInvoiceLinesInternalInput struct {
	Namespace  string
	CustomerID string
	Lines      []*StandardLine
}

func (i UpdateInvoiceLinesInternalInput) Validate() error {
	if i.Namespace == "" {
		return errors.New("namespace is required")
	}

	if i.CustomerID == "" {
		return errors.New("customer ID is required")
	}

	return nil
}

// UpdateStandardInvoiceInput updates a mutable standard invoice by applying EditFn,
// diffing the edited lines against the original invoice, and letting line engines
// canonicalize line changes according to ChangeSource before persistence.
type UpdateStandardInvoiceInput struct {
	// Invoice identifies the standard invoice to update.
	Invoice InvoiceID
	// EditFn mutates the loaded invoice into the caller's desired state.
	EditFn func(*StandardInvoice) error
	// ChangeSource classifies why line changes are being applied.
	//
	// ChangeSourceAPIRequest means the update came from the public
	// invoice editing API and should be treated as a user override: invoice-owned
	// lines may become manually managed, while charge-owned lines may reject the
	// change.
	//
	// ChangeSourceSystem means the update came from internal billing,
	// charge, or subscription lifecycle code. These updates should preserve system
	// ownership semantics and allow engines to reconcile their own managed lines.
	ChangeSource ChangeSource
	// IncludeDeletedLines populates deleted lines into the invoice lines field before EditFn is called.
	IncludeDeletedLines bool
}

func (i UpdateStandardInvoiceInput) Validate() error {
	if err := i.Invoice.Validate(); err != nil {
		return fmt.Errorf("id: %w", err)
	}

	if i.EditFn == nil {
		return errors.New("edit function is required")
	}

	if err := i.ChangeSource.Validate(); err != nil {
		return fmt.Errorf("line change source: %w", err)
	}

	return nil
}

type SimulateInvoiceInput struct {
	Namespace  string
	CustomerID *string
	Customer   *customer.Customer

	Number   *string
	Currency currencyx.Code
	Lines    StandardInvoiceLines
}

func (i SimulateInvoiceInput) Validate() error {
	if i.CustomerID != nil {
		if *i.CustomerID == "" {
			return errors.New("customer ID is required")
		}
	}

	if i.Customer != nil {
		if err := i.Customer.Validate(); err != nil {
			return fmt.Errorf("customer: %w", err)
		}
	}

	if i.CustomerID == nil && i.Customer == nil {
		return errors.New("either customer ID or customer is required")
	}

	if i.CustomerID != nil && i.Customer != nil {
		return errors.New("only one of customer ID or customer can be specified")
	}

	if i.Namespace == "" {
		return errors.New("namespace is required")
	}

	if i.Currency == "" {
		return errors.New("currency is required")
	}

	if len(i.Lines.OrEmpty()) == 0 {
		return errors.New("lines are required")
	}

	return nil
}

type UpsertValidationIssuesInput struct {
	Invoice InvoiceID
	Issues  ValidationIssues
}

func (i UpsertValidationIssuesInput) Validate() error {
	if err := i.Invoice.Validate(); err != nil {
		return fmt.Errorf("id: %w", err)
	}

	if len(i.Issues) == 0 {
		return errors.New("issues are required")
	}

	return nil
}

type InvoiceTriggerValidationInput struct {
	// Operation specifies the operation that yielded the validation errors
	// previous validation errors from this operation will be replaced by this one
	Operation StandardInvoiceOperation
	Errors    []error
}

func (i InvoiceTriggerValidationInput) Validate() error {
	if err := i.Operation.Validate(); err != nil {
		return fmt.Errorf("operation: %w", err)
	}

	if len(i.Errors) == 0 {
		return errors.New("validation errors are required")
	}

	return nil
}

type InvoiceTriggerInput struct {
	Invoice InvoiceID
	// Trigger specifies the trigger that caused the invoice to be changed, only triggerPaid and triggerPayment* are allowed
	Trigger InvoiceTrigger

	ValidationErrors *InvoiceTriggerValidationInput
}

func (i InvoiceTriggerInput) Validate() error {
	if err := i.Invoice.Validate(); err != nil {
		return fmt.Errorf("id: %w", err)
	}

	if i.Trigger == "" {
		return errors.New("trigger is required")
	}

	if i.ValidationErrors != nil {
		if err := i.ValidationErrors.Validate(); err != nil {
			return fmt.Errorf("validation errors: %w", err)
		}
	}

	return nil
}

type InvoiceTriggerServiceInput struct {
	InvoiceTriggerInput

	// AppType is the type of the app that triggered the invoice
	AppType app.AppType
	// Capability is the capability of the app that was processing this trigger
	Capability app.CapabilityType
}

func (i InvoiceTriggerServiceInput) Validate() error {
	if err := i.InvoiceTriggerInput.Validate(); err != nil {
		return fmt.Errorf("trigger: %w", err)
	}

	if i.AppType == "" {
		return errors.New("app type is required")
	}

	if i.Capability == "" {
		return errors.New("capability is required")
	}

	return nil
}

type UpdateInvoiceFieldsInput struct {
	Invoice          InvoiceID
	SentToCustomerAt mo.Option[*time.Time]
}

func (i UpdateInvoiceFieldsInput) Validate() error {
	if err := i.Invoice.Validate(); err != nil {
		return fmt.Errorf("id: %w", err)
	}

	return nil
}

type RecalculateGatheringInvoicesInput = customer.CustomerID

type StandardInvoiceExpand string

const (
	StandardInvoiceExpandLines        StandardInvoiceExpand = "lines"
	StandardInvoiceExpandDeletedLines StandardInvoiceExpand = "deletedLines"
)

func (e StandardInvoiceExpand) Values() []StandardInvoiceExpand {
	return []StandardInvoiceExpand{
		StandardInvoiceExpandLines,
		StandardInvoiceExpandDeletedLines,
	}
}

type StandardInvoiceExpands = expand.Expand[StandardInvoiceExpand]

var StandardInvoiceExpandAll = StandardInvoiceExpands{
	StandardInvoiceExpandLines,
	// Deleted lines are not expanded by default
}

// InvoicePendingAdvancementFilter selects invoices that have been eligible for
// automatic advancement for at least MinimumAge as of AsOf. Scheduled states
// use their explicit due timestamp; states without one use the invoice's last
// update as the start of the pending period.
type InvoicePendingAdvancementFilter struct {
	AsOf       time.Time
	MinimumAge time.Duration
}

var _ models.Validator = (*InvoicePendingAdvancementFilter)(nil)

func (f InvoicePendingAdvancementFilter) Validate() error {
	var errs []error

	if f.AsOf.IsZero() {
		errs = append(errs, errors.New("as of is required"))
	}

	if f.MinimumAge < 0 {
		errs = append(errs, errors.New("minimum age cannot be negative"))
	}

	return models.NewNillableGenericValidationError(errors.Join(errs...))
}

// ListStandardInvoicesPendingAdvancementInput configures retrieval of standard
// invoices that are due for automatic advancement.
type ListStandardInvoicesPendingAdvancementInput struct {
	Namespaces []string
	IDs        []string
	AsOf       time.Time
	MinimumAge time.Duration
}

var _ models.Validator = (*ListStandardInvoicesPendingAdvancementInput)(nil)

func (i ListStandardInvoicesPendingAdvancementInput) Validate() error {
	return InvoicePendingAdvancementFilter{
		AsOf:       i.AsOf,
		MinimumAge: i.MinimumAge,
	}.Validate()
}

// CountStandardInvoicesPendingAdvancementInput configures an aggregate count
// of advancement candidates while allowing operationally disabled namespaces
// to be excluded.
type CountStandardInvoicesPendingAdvancementInput struct {
	Filter             InvoicePendingAdvancementFilter
	ExcludedNamespaces []string
}

var _ models.Validator = (*CountStandardInvoicesPendingAdvancementInput)(nil)

func (i CountStandardInvoicesPendingAdvancementInput) Validate() error {
	return i.Filter.Validate()
}

type GetStandardInvoiceByIdInput struct {
	Invoice InvoiceID
	Expand  StandardInvoiceExpands
}

func (i GetStandardInvoiceByIdInput) Validate() error {
	var errs []error

	if err := i.Invoice.Validate(); err != nil {
		errs = append(errs, fmt.Errorf("id: %w", err))
	}

	if err := i.Expand.Validate(); err != nil {
		errs = append(errs, fmt.Errorf("expand: %w", err))
	}

	return errors.Join(errs...)
}

type ListStandardInvoicesInput struct {
	pagination.Page

	Namespaces         []string
	IDs                []string
	Statuses           []string
	ExtendedStatuses   []StandardInvoiceStatus
	HasAvailableAction []InvoiceAvailableActionsFilter

	Expand          StandardInvoiceExpands
	ExternalIDs     *ListInvoicesExternalIDFilter
	DraftUntilLTE   *time.Time
	CollectionAtLTE *time.Time

	IncludeDeleted bool
}

func (i ListStandardInvoicesInput) Validate() error {
	var errs []error

	// Page is not validated here, as for internal use we don't want to use pagination unless
	// explicitly requested.

	// It's the httpdriver's responsibility to validate the page size and page number.

	if err := i.Expand.Validate(); err != nil {
		errs = append(errs, fmt.Errorf("expand: %w", err))
	}

	if i.ExternalIDs != nil {
		if err := i.ExternalIDs.Validate(); err != nil {
			errs = append(errs, fmt.Errorf("externalIDs: %w", err))
		}
	}

	return errors.Join(errs...)
}

type ListStandardInvoicesResponse = pagination.Result[StandardInvoice]

type CreateStandardInvoiceFromGatheringLinesInput struct {
	Customer    customer.CustomerID
	Currency    currencyx.Code
	Description *string

	Lines                       GatheringLines
	PostCreationCalculationHook PostCreationCalculationHook
	ForceAsyncAdvance           bool
}

type (
	PostCreationCalculationHook func(StandardInvoice, StandardLine) (LineMutators, error)
	LineMutator                 func(*StandardLine) error
	LineMutators                = []LineMutator
)

func (i CreateStandardInvoiceFromGatheringLinesInput) Validate() error {
	var errs []error

	if err := i.Customer.Validate(); err != nil {
		errs = append(errs, fmt.Errorf("customer: %w", err))
	}

	if err := i.Currency.Validate(); err != nil {
		errs = append(errs, fmt.Errorf("currency: %w", err))
	}

	if len(i.Lines) == 0 {
		errs = append(errs, fmt.Errorf("lines are required"))
	}

	for _, line := range i.Lines {
		if err := line.Validate(); err != nil {
			errs = append(errs, fmt.Errorf("line[%s]: %w", line.ID, err))
		}

		if line.Currency != i.Currency {
			errs = append(errs, fmt.Errorf("line[%s]: currency[%s] is not equal to invoice currency[%s]", line.ID, line.Currency, i.Currency))
		}

		if line.Namespace != i.Customer.Namespace {
			errs = append(errs, fmt.Errorf("line[%s]: namespace[%s] is not equal to invoice namespace[%s]", line.ID, line.Namespace, i.Customer.Namespace))
		}
	}

	return errors.Join(errs...)
}

type (
	StandardInvoiceHook  = models.ServiceHook[StandardInvoice]
	StandardInvoiceHooks = models.ServiceHookRegistry[StandardInvoice]
)

func NewSetCreditsAppliedOperation(creditsApplied CreditsApplied) LineMutator {
	return func(line *StandardLine) error {
		line.CreditsApplied = creditsApplied
		return nil
	}
}