package pgstore

import (
	"fmt"
	"testing"

	"textmachine/platform/internal/money"
)

// Where exactly the share turns negative. int64 max is 9223372036854775807, so balance*100 is exact
// up to 92233720368547758 micro-USD ($92,233,720,368.547758) and wraps one micro-dollar later.
func TestR1WhereTheUsageShareTurnsNegative(t *testing.T) {
	for _, balance := range []int64{92_233_720_368_547_758, 92_233_720_368_547_759} {
		t.Run(fmt.Sprint(balance), func(t *testing.T) {
			s, ctx := testDB(t)
			// Granted is one micro-dollar above the balance, so the `balance >= granted` arm is skipped
			// and the share is actually computed — the ordinary state of any account that has spent.
			now := fundedAccount(t, s, ctx, "u1", money.MicroUSD(balance+1).USD())
			if _, err := s.Adjust(ctx, "u1", -1, "test", "r1-nudge", "one micro-dollar of spend", now); err != nil {
				t.Fatal(err)
			}
			u, err := s.ReadUsage(ctx, "u1")
			if err != nil {
				t.Fatal(err)
			}
			acct, err := s.ReadAccount(ctx, "u1")
			if err != nil {
				t.Fatal(err)
			}
			t.Logf("balance %d micro-USD (%s) -> remaining_percent %d", int64(acct.Balance), acct.Balance.USD(), u.RemainingPercent)
			if int64(acct.Balance) != balance {
				t.Fatalf("fixture: balance %d, want %d", int64(acct.Balance), balance)
			}
		})
	}
}
