package main

import (
	"testing"

	"github.com/shopspring/decimal"

	"github.com/TaruLab/keluargamart-backend/internal/accounting"
)

// The accrual draft must balance by construction and never emit a
// zero-amount line (resolveLines rejects those).
func TestGRAccrualLines(t *testing.T) {
	withTax := grAccrualLines("PABRIK", "GR-1", decimal.NewFromInt(1000), decimal.NewFromInt(110))
	if len(withTax) != 3 {
		t.Fatalf("lines = %d, want 3", len(withTax))
	}
	assertAccrualBalanced(t, withTax)
	if withTax[0].AccountCode != "500.03" || !withTax[0].Debit.Equal(decimal.NewFromInt(1000)) {
		t.Errorf("DPP line = %s/%s, want 500.03/1000", withTax[0].AccountCode, withTax[0].Debit)
	}
	if withTax[1].AccountCode != "110701" || !withTax[1].Debit.Equal(decimal.NewFromInt(110)) {
		t.Errorf("PPN line = %s/%s, want 110701/110", withTax[1].AccountCode, withTax[1].Debit)
	}
	if withTax[2].AccountCode != "211.03" || !withTax[2].Credit.Equal(decimal.NewFromInt(1110)) {
		t.Errorf("credit line = %s/%s, want 211.03/1110", withTax[2].AccountCode, withTax[2].Credit)
	}

	noTax := grAccrualLines("PABRIK", "GR-2", decimal.NewFromInt(1000), decimal.Zero)
	if len(noTax) != 2 {
		t.Fatalf("lines = %d, want 2 (taxless PO gets no zero PPN line)", len(noTax))
	}
	assertAccrualBalanced(t, noTax)
	for _, l := range noTax {
		if !l.Debit.IsPositive() && !l.Credit.IsPositive() {
			t.Errorf("zero-amount line on %s would fail resolveLines", l.AccountCode)
		}
	}
}

func assertAccrualBalanced(t *testing.T, lines []accounting.JournalLineInput) {
	t.Helper()
	var debit, credit decimal.Decimal
	for _, l := range lines {
		debit = debit.Add(l.Debit)
		credit = credit.Add(l.Credit)
	}
	if !debit.Equal(credit) || debit.IsZero() {
		t.Errorf("debit %s != credit %s (or both zero)", debit, credit)
	}
}
