package mock_test

import (
	"context"
	"errors"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	eventbus "code.justin.tv/eventbus/client"
	"code.justin.tv/eventbus/client/encryption"
	"code.justin.tv/eventbus/client/internal/testevents"
	"code.justin.tv/eventbus/client/internal/testschema/clock"
	"code.justin.tv/eventbus/client/mock"
	"code.justin.tv/eventbus/client/mock/fakeevents/foobar"
)

func TestPublisher(t *testing.T) {
	t.Run("Satisfies interfaces", func(t *testing.T) {
		pub := &mock.Publisher{}
		var _ eventbus.Publisher = pub
		var _ encryption.Provider = pub
		var _ encryption.Encrypter = pub
	})

	t.Run("Performs noop encryption", func(t *testing.T) {
		ctx := context.Background()
		pub := &mock.Publisher{}

		foobarCreate := &foobar.Create{
			Garply: "garply",
		}
		err := foobarCreate.SetEncryptedBaz(pub, "secret baz")

		require.NoError(t, err)
		assert.Len(t, pub.EncryptCalls, 1)
		assert.Equal(t, pub.EncryptCalls[0].AuthorizationContext["MessageName"], "FoobarCreate")
		assert.Equal(t, pub.EncryptCalls[0].AuthorizationContext["FieldName"], "Baz")
		assert.Equal(t, pub.EncryptCalls[0].AuthorizationContext["EventType"], "FoobarCreate")
		assert.Equal(t, pub.EncryptCalls[0].AuthorizationContext["Environment"], "mock")
		assert.Equal(t, pub.EncryptCalls[0].Plaintext, "secret baz")
		assert.Equal(t, string(foobarCreate.Baz.Payload), "secret baz")

		assert.NoError(t, pub.Publish(ctx, foobarCreate))
	})
}

func TestDispatchPublisher(t *testing.T) {
	var returnedError error
	var calls []*clock.ClockUpdate
	mux := eventbus.NewMux()
	clock.RegisterClockUpdateHandler(mux, func(ctx context.Context, h *eventbus.Header, tick *clock.ClockUpdate) error {
		calls = append(calls, tick)
		return returnedError
	})

	pub := mock.DispatchPublisher(mux.Dispatcher())

	t.Run("Sends ClockUpdate", func(t *testing.T) {
		err := pub.Publish(context.Background(), testevents.NewClockUpdate(105))
		assert.NoError(t, err)
		require.Len(t, calls, 1)
		assert.Equal(t, int64(105), calls[0].Time.GetSeconds())
	})

	t.Run("Returns Dispatch Error", func(t *testing.T) {
		returnedError = errors.New("Example")
		err := pub.Publish(context.Background(), testevents.NewClockUpdate(105))
		require.Error(t, err)
		require.Equal(t, "Example", err.Error())
	})
}
