package eventpublisher

//go:generate mockgen -destination ../../internal/mocks/mock_kinesisiface/mock_kinesisiface.go github.com/aws/aws-sdk-go/service/kinesis/kinesisiface KinesisAPI
//go:generate mockgen -destination ../../internal/mocks/mock_client/mock_client.go github.com/aws/aws-sdk-go/aws/client ConfigProvider

import (
	"fmt"
	"testing"
	"time"

	"code.justin.tv/dta/rockpaperscissors/internal/mocks/mock_client"
	"code.justin.tv/dta/rockpaperscissors/internal/mocks/mock_kinesisiface"
	"code.justin.tv/dta/rockpaperscissors/internal/testutil"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/kinesis"
	"github.com/golang/mock/gomock"
	"github.com/golang/protobuf/proto"
)

func TestBasic(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	mockSession := mock_client.NewMockConfigProvider(mockCtrl)
	mockKinesis := mock_kinesisiface.NewMockKinesisAPI(mockCtrl)

	source := "TestSource"
	publisher, err := NewEventPublisher(source,
		&Config{AwsSession: mockSession, KinesisSvc: mockKinesis})
	testutil.AssertNotNil(t, "NewEventPublisher returned publisher", publisher)
	testutil.AssertNil(t, "NewEventPublisher returned err", err)
	testutil.AssertEquals(t, "EventPublisher.Source", publisher.config.Source,
		source)
	testutil.AssertEquals(t, "EventPublisher.Environment",
		publisher.config.Environment, PRODUCTION)

	timestamp := time.Unix(1, 0)
	eventType := "TestEventType"
	body := []byte("TestBody")
	event, err := CreateEvent(timestamp, eventType, body, nil)
	testutil.AssertNotNil(t, "CreateEvent returned event", event)
	testutil.AssertNil(t, "CreateEvent returned err", err)
	testutil.AssertEquals(t, "len(Event.Uuid)", len(event.GetUuid()), 16)
	testutil.AssertEquals(t, "Event.Timestamp", int64(event.GetTimestamp()),
		timestamp.Unix())
	testutil.AssertEquals(t, "Event.Type", event.GetType(), eventType)
	testutil.AssertBytesEqual(t, "Event.Body", event.GetBody(), body)

	data, err := proto.Marshal(event)
	testutil.AssertNil(t, "Event couldn't be marshalled into bytes", err)
	mockKinesis.EXPECT().PutRecord(&kinesis.PutRecordInput{
		Data:         data,
		PartitionKey: aws.String(fmt.Sprintf("%x", event.GetUuid())),
		StreamName:   aws.String(streamName[publisher.config.Environment]),
	})
	err = publisher.PublishEvent(event)
	testutil.AssertNil(t, "PublishEvent returned err", err)
}
