package grpctool

import (
	"sync"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/mock_tool"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/testing/testlogger"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/tlstool"
	"go.uber.org/mock/gomock"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/credentials/insecure"
	clocktesting "k8s.io/utils/clock/testing"
)

const (
	t1 = "grpc://127.0.0.1:1"
	t2 = "grpc://127.0.0.1:2"
)

var (
	_ PoolInterface[URLTarget] = (*Pool[URLTarget])(nil)
	_ PoolConn                 = (*poolConn)(nil)
	_ PoolInterface[URLTarget] = (*PoolSelf[URLTarget])(nil)
	_ PoolConn                 = (*selfPoolConn)(nil)
)

func TestKASPool_DialConnDifferentPort(t *testing.T) {
	p, _ := newPool(t)
	defer p.Shutdown(time.Minute)
	c1, err := p.Dial(t1)
	require.NoError(t, err)
	c1.Done()
	c2, err := p.Dial(t2)
	require.NoError(t, err)
	assert.NotSame(t, c1, c2)
	c2.Done()
}

func TestKASPool_DialConnSequentialReuse(t *testing.T) {
	p, _ := newPool(t)
	defer p.Shutdown(time.Minute)
	c1, err := p.Dial(t1)
	require.NoError(t, err)
	c1.Done()
	c2, err := p.Dial(t1)
	require.NoError(t, err)
	assert.Same(t, c1.(*poolConn).ClientConn, c2.(*poolConn).ClientConn)
	c2.Done()
}

func TestKASPool_DialConnConcurrentReuse(t *testing.T) {
	p, _ := newPool(t)
	defer p.Shutdown(time.Minute)
	c1, err := p.Dial(t1)
	require.NoError(t, err)
	c2, err := p.Dial(t1)
	require.NoError(t, err)
	assert.Same(t, c1.(*poolConn).ClientConn, c2.(*poolConn).ClientConn)
	c1.Done()
	c2.Done()
}

func TestKASPool_CloseClosesAllConnectionsWhenNoUsersExist(t *testing.T) {
	p, _ := newPool(t)
	c, err := p.Dial(t1)
	require.NoError(t, err)
	c.Done()
	p.Shutdown(time.Minute)
	assert.Empty(t, p.conns)
}

func TestKASPool_CloseClosesAllConnectionsWhenDeadlineIsReached(t *testing.T) {
	p, rep := newPool(t)
	rep.EXPECT().HandleProcessingError(
		gomock.Any(),
		gomock.Any(),
		gomock.Any(),
		gomock.Any(),
		gomock.Any(),
	)
	_, err := p.Dial(t1)
	require.NoError(t, err)
	p.Shutdown(0) // no waiting
	assert.Empty(t, p.conns)
}

func TestKASPool_CloseClosesPoolBeforeDeadlineWhenChannelIsClosed(t *testing.T) {
	p, _ := newPool(t)
	c, err := p.Dial(t1)
	require.NoError(t, err)
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		p.Shutdown(time.Minute)
		assert.Empty(t, p.conns)
		wg.Done()
	}()

	c.Done()
	wg.Wait()
}

func TestKASPool_DonePanicsOnMultipleInvocations(t *testing.T) {
	p, _ := newPool(t)
	defer p.Shutdown(time.Minute)
	c, err := p.Dial(t1)
	require.NoError(t, err)
	c.Done()
	assert.PanicsWithValue(t, "pooled connection Done() called more than once", func() {
		c.Done()
	})
}

func TestKASPool_DoneEvictsExpiredIdleConnections(t *testing.T) {
	start := time.Now()
	tClock := clocktesting.NewFakePassiveClock(start)
	p := &Pool[URLTarget]{
		log:           testlogger.New(t),
		newConnection: DefaultNewConnection(insecure.NewCredentials()),
		conns:         map[URLTarget]*connHolder{},
		clk:           tClock,
		closePoolChan: make(chan struct{}),
	}
	defer p.Shutdown(time.Minute)
	c1, err := p.Dial(t1)
	require.NoError(t, err)
	c1.Done()
	tClock.SetTime(start.Add(2 * evictIdleConnAfter))
	p.runGCLocked()
	assert.Empty(t, p.conns)
}

func TestKASPool_DoesNotAllowDialAfterClose(t *testing.T) {
	p, _ := newPool(t)
	c, err := p.Dial(t1)
	require.NoError(t, err)
	c.Done()
	p.Shutdown(time.Minute)
	assert.Empty(t, p.conns)
	_, err = p.Dial(t1)
	assert.EqualError(t, err, "pool has been closed, cannot dial up new connections")
}

func newPool(t *testing.T) (*Pool[URLTarget], *mock_tool.MockErrReporter) {
	ctrl := gomock.NewController(t)
	rep := mock_tool.NewMockErrReporter(ctrl)
	return NewPool(testlogger.New(t), rep, DefaultNewConnection(credentials.NewTLS(tlstool.ClientConfig()))), rep
}
