package main

import (
	"sync"
	"testing"
)

func Example() {
	demo()
	// Output:
	// unsafe balance: 200
	// first: true <nil>
	// redelivery: false <nil>
	// conflict: event ID reused with different payload
	// failed transaction: transaction aborted
	// safe balance: 100
	// temporary attempt 1: retry-later
	// temporary attempt 3: quarantine
	// invalid payload: quarantine
	// t=4 ready: []
	// t=8 ready: [cancel-unpaid]
	// drain seconds: 120
}

func TestConcurrentIdempotency(t *testing.T) {
	s := new(Store)
	var wg sync.WaitGroup
	for range 100 {
		wg.Go(func() {
			if _, err := s.Apply(Event{"e1", 100}, false); err != nil {
				t.Error(err)
			}
		})
	}
	wg.Wait()
	if s.balance != 100 {
		t.Fatalf("balance = %d", s.balance)
	}
}

func TestAbortCanRetry(t *testing.T) {
	s := new(Store)
	if _, err := s.Apply(Event{"e1", 100}, true); err == nil {
		t.Fatal("expected abort")
	}
	if applied, err := s.Apply(Event{"e1", 100}, false); !applied || err != nil {
		t.Fatalf("retry failed: %v %v", applied, err)
	}
}
