package wallet

import (
	"regexp"
	"testing"

	"hfb_sys/backend/internal/model"
)

func TestApplyEntryRoundsMoneyBeforeComparing(t *testing.T) {
	account := model.WalletAccount{
		UserID:            7,
		FrozenBalanceCent: 60641,
	}
	entry := Entry{
		UserID:      7,
		Direction:   "out",
		AmountCent:  60641,
		BalanceType: "frozen",
	}

	balanceAfter, err := applyEntry(&account, entry)
	if err != nil {
		t.Fatalf("applyEntry() error = %v", err)
	}
	if balanceAfter != 0 {
		t.Fatalf("balanceAfter = %v, want 0", balanceAfter)
	}
	if account.FrozenBalanceCent != 0 {
		t.Fatalf("FrozenBalanceCent = %d, want 0", account.FrozenBalanceCent)
	}
}

func TestApplyEntryKeepsWalletMoneyAtJiaoPrecision(t *testing.T) {
	account := model.WalletAccount{
		UserID:               8,
		AvailableBalanceCent: 0,
	}
	entry := Entry{
		UserID:      8,
		Direction:   "in",
		AmountCent:  230,
		BalanceType: "available",
	}

	balanceAfter, err := applyEntry(&account, entry)
	if err != nil {
		t.Fatalf("applyEntry() error = %v", err)
	}
	if balanceAfter != 230 {
		t.Fatalf("balanceAfter = %d, want 230", balanceAfter)
	}
	if account.AvailableBalanceCent != 230 {
		t.Fatalf("AvailableBalanceCent = %d, want 230", account.AvailableBalanceCent)
	}

	if rounded := roundWalletMoney(2.36); rounded != 2.4 {
		t.Fatalf("roundWalletMoney(2.36) = %v, want 2.4", rounded)
	}
}

func TestNewLedgerNoUsesReadableFormat(t *testing.T) {
	ledgerNo, err := newLedgerNo()
	if err != nil {
		t.Fatalf("newLedgerNo() error = %v", err)
	}
	matched := regexp.MustCompile(`^WL\d{21}$`).MatchString(ledgerNo)
	if !matched {
		t.Fatalf("ledgerNo = %q, want WL + 21 digits", ledgerNo)
	}
}
