package agentk

import (
	"runtime"
	"testing"

	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"
	"k8s.io/apimachinery/pkg/util/wait"
)

func runFlakyTest(t require.TestingT, flakyTest func(t require.TestingT)) {
	totalAttempts := 3

	var mockTestRunner *mockT

	for range totalAttempts {
		mockTestRunner = &mockT{}

		var wg wait.Group
		wg.Start(func() {
			flakyTest(mockTestRunner)
		})

		wg.Wait()
		if !mockTestRunner.failed {
			return
		}
	}

	if errorDetails := mockTestRunner.lastErrorDetails; errorDetails != nil {
		t.Errorf(errorDetails.format, errorDetails.args...)
	}

	if mockTestRunner.failed {
		t.FailNow()
	}
}

// mockT is a test runner that implements require.TestingT interface. This is required because there
// is no way to run a test using *testing.T and ignore failures of subtests. However, assertions in the
// testify library do not explicitly require *testing.T but anything that implements require.TestingT interface.
// Hence, for scenarios where multiple attempts at testing are required, it is more convenient to use
// an instance of mockT and a test function that has require.TestingT in its function signature instead of *testing.T
type mockT struct {
	failed           bool
	lastErrorDetails *mockTErrorDetails
}

type mockTErrorDetails struct {
	format string
	args   []any
}

func (t *mockT) FailNow() {
	t.failed = true
	runtime.Goexit()
}

func (t *mockT) Errorf(format string, args ...any) {
	t.lastErrorDetails = &mockTErrorDetails{
		format: format,
		args:   args,
	}
}

func TestFlakyTestRunner(t *testing.T) {
	suite.Run(t, new(flakyTestRunnerSuite))
}

type flakyTestRunnerSuite struct {
	suite.Suite
}

func (f *flakyTestRunnerSuite) TestSuccessInFirstAttempt() {
	totalAttempts := 0

	runFlakyTest(f.T(), func(t require.TestingT) {
		totalAttempts++
	})

	f.Equal(1, totalAttempts)
}

func (f *flakyTestRunnerSuite) TestSuccessInLastAttempt() {
	totalAttempts := 0

	runFlakyTest(f.T(), func(t require.TestingT) {
		totalAttempts++
		if totalAttempts <= 2 {
			t.FailNow()
		}
	})

	f.Equal(3, totalAttempts)
}

func (f *flakyTestRunnerSuite) TestFailureInAllAttempts() {
	totalAttempts := 0
	mockTestRunner := &mockT{}

	// calling this in a goroutine as the failure in the last attempt
	// is expected to stop the goroutine following the convention of failed tests
	// in Golang's testing package
	var wg wait.Group
	wg.Start(func() {
		runFlakyTest(mockTestRunner, func(t require.TestingT) {
			totalAttempts++
			t.FailNow()
		})
	})
	wg.Wait()

	f.Equal(3, totalAttempts)
	f.True(mockTestRunner.failed)
}
