package localapiready

import (
	"context"
	"errors"
	"testing"
	"time"
)

func TestWaitRetriesUntilProbeSucceeds(t *testing.T) {
	attempts := 0
	err := Wait(context.Background(), func(context.Context) error {
		attempts++
		if attempts < 3 {
			return errors.New("pipe not ready")
		}
		return nil
	}, Config{
		Timeout:  time.Second,
		Interval: time.Millisecond,
		Sleep:    func(time.Duration) {},
	})
	if err != nil {
		t.Fatalf("Wait returned error: %v", err)
	}
	if attempts != 3 {
		t.Fatalf("attempts = %d, want 3", attempts)
	}
}

func TestWaitReturnsLastProbeErrorAfterTimeout(t *testing.T) {
	wantErr := errors.New("pipe not ready")
	err := Wait(context.Background(), func(context.Context) error {
		return wantErr
	}, Config{
		Timeout:  3 * time.Millisecond,
		Interval: time.Millisecond,
		Sleep:    time.Sleep,
	})
	if !errors.Is(err, wantErr) {
		t.Fatalf("Wait error = %v, want %v", err, wantErr)
	}
}

func TestWaitReturnsContextError(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()

	err := Wait(ctx, func(context.Context) error {
		t.Fatal("probe should not be called after context cancellation")
		return nil
	}, Config{
		Timeout:  time.Second,
		Interval: time.Millisecond,
		Sleep:    func(time.Duration) {},
	})
	if !errors.Is(err, context.Canceled) {
		t.Fatalf("Wait error = %v, want %v", err, context.Canceled)
	}
}
