package apps

import (
	"sync"
	"sync/atomic"
	"testing"
	"time"
)

func TestSingleflightDedupes(t *testing.T) {
	var g singleflightGroup
	var calls atomic.Int64
	fn := func() (any, error) {
		calls.Add(1)
		time.Sleep(50 * time.Millisecond) // hold the lock long enough for races
		return "result", nil
	}
	var wg sync.WaitGroup
	const N = 50
	for i := 0; i < N; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			val, err := g.Do("the-key", fn)
			if err != nil {
				t.Errorf("Do err: %v", err)
				return
			}
			if val.(string) != "result" {
				t.Errorf("got %v, want 'result'", val)
			}
		}()
	}
	wg.Wait()
	if got := calls.Load(); got != 1 {
		t.Errorf("fn called %d times, want exactly 1", got)
	}
}

func TestSingleflightDifferentKeysParallel(t *testing.T) {
	var g singleflightGroup
	var calls atomic.Int64
	fn := func() (any, error) {
		calls.Add(1)
		return "ok", nil
	}
	for _, k := range []string{"a", "b", "c"} {
		_, _ = g.Do(k, fn)
	}
	if got := calls.Load(); got != 3 {
		t.Errorf("fn called %d times, want 3", got)
	}
}

func TestSingleflightSecondCallAfterFirstResolves(t *testing.T) {
	var g singleflightGroup
	var calls atomic.Int64
	fn := func() (any, error) {
		calls.Add(1)
		return "x", nil
	}
	_, _ = g.Do("k", fn)
	_, _ = g.Do("k", fn)
	if got := calls.Load(); got != 2 {
		t.Errorf("fn called %d times, want 2 (second call sees no in-flight entry)", got)
	}
}
