package redis

import (
	"context"
	"testing"

	"github.com/fiskerinc/cloud-services/pkg/testhelper"
)

func TestInitPubsub(t *testing.T) {
	MockRedisConnection()
	var listener Listener
	listener = NewPubSub()

	if listener == nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestInitPubSub", "PubSub", listener)
	}

	numSubs := 0
	if listener.Length() != 0 {
		t.Errorf(testhelper.TestErrorTemplate, "TestInitPubSub", 0, numSubs)
	}
}

func TestAddSubscription(t *testing.T) {
	MockRedisConnection()
	listener := NewPubSub(GetMockPool().Get())

	err := listener.Add("TESTVIN123")
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestAddSubscription", nil, err)
	}

	numSubs := 1
	if listener.Length() != numSubs {
		t.Errorf(testhelper.TestErrorTemplate, "TestAddSubscription", numSubs, listener.Length())
	}
}

func TestRemoveSubscription(t *testing.T) {
	MockRedisConnection()
	listener := NewPubSub(GetMockPool().Get())

	err := listener.Add("TESTVIN123")
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestRemoveSubscription", nil, err)
	}

	numSubs := 1
	if listener.Length() != numSubs {
		t.Errorf(testhelper.TestErrorTemplate, "TestRemoveSubscription", numSubs, listener.Length())
	}

	err = listener.Remove("TESTVIN123")
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestRemoveSubscription", nil, err)
	}

	numSubs = 0
	if listener.Length() != numSubs {
		t.Errorf(testhelper.TestErrorTemplate, "TestRemoveSubscription", numSubs, listener.Length())
	}
}

func TestSubscriptionListen(t *testing.T) {
	MockRedisConnection()
	listener := NewPubSub(GetMockPool().Get())

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	mockFunc := func(string, []byte) error {
		return nil
	}

	go listener.Listen(ctx, mockFunc)
}

func TestSubscriptionRestart(t *testing.T) {
	MockRedisConnection()
	listener := NewPubSub(GetMockPool().Get())
	err := listener.Restart()
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestSubscriptionRestart", nil, err)
	}
}
