package event_tracker //nolint:staticcheck

import (
	"fmt"
	"testing"

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

type TestEvent struct {
	UserID    int64
	ProjectID int64
}

func (e TestEvent) DeduplicateKey() string {
	return fmt.Sprintf("%d-%d", e.UserID, e.ProjectID)
}

func TestEventTracker(t *testing.T) {
	et := NewEventTracker()
	e := et.RegisterEvent("x")
	require.Contains(t, et.eventLists, "x")

	ed := et.CloneEventData()
	expectedEvents := map[string][]Event{}
	require.Equal(t, expectedEvents, ed.Events)

	e.EmitEvent(TestEvent{UserID: 1, ProjectID: 2})
	e.EmitEvent(TestEvent{UserID: 4, ProjectID: 5})
	// Duplicate event should be ignored
	e.EmitEvent(TestEvent{UserID: 1, ProjectID: 2})
	e.EmitEvent(TestEvent{UserID: 1, ProjectID: 3})
	assert.EqualValues(t, 3, et.AccumulatedEvents())

	ed = et.CloneEventData()
	expectedEvents = map[string][]Event{
		"x": {
			TestEvent{
				UserID:    1,
				ProjectID: 2,
			},
			TestEvent{
				UserID:    4,
				ProjectID: 5,
			},
			TestEvent{
				UserID:    1,
				ProjectID: 3,
			},
		},
	}
	require.Equal(t, expectedEvents, ed.Events)

	et.Subtract(ed)
	ed = et.CloneEventData()
	require.Empty(t, ed.Events)
	assert.Zero(t, et.AccumulatedEvents())
}

func TestEventTracker_Subtract(t *testing.T) {
	et := NewEventTracker()
	e := et.RegisterEvent("x")
	require.Contains(t, et.eventLists, "x")

	e.EmitEvent(TestEvent{UserID: 1, ProjectID: 1})
	e.EmitEvent(TestEvent{UserID: 2, ProjectID: 2})
	e.EmitEvent(TestEvent{UserID: 3, ProjectID: 3})
	e.EmitEvent(TestEvent{UserID: 4, ProjectID: 4})
	e.EmitEvent(TestEvent{UserID: 5, ProjectID: 5})
	require.Len(t, et.eventLists["x"].events, 5)
	assert.EqualValues(t, 5, et.AccumulatedEvents())

	et.Subtract(&EventData{
		Events: map[string][]Event{
			"x": {
				TestEvent{
					UserID:    1,
					ProjectID: 1,
				},
				TestEvent{
					UserID:    2,
					ProjectID: 2,
				},
				TestEvent{
					UserID:    3,
					ProjectID: 3,
				},
			},
		},
	})
	require.Len(t, et.eventLists["x"].events, 2)
	assert.EqualValues(t, 2, et.AccumulatedEvents())

	e.EmitEvent(TestEvent{UserID: 6, ProjectID: 6})
	assert.EqualValues(t, 3, et.AccumulatedEvents())

	et.Subtract(&EventData{
		Events: map[string][]Event{
			"x": {
				TestEvent{
					UserID:    4,
					ProjectID: 4,
				},
				TestEvent{
					UserID:    5,
					ProjectID: 5,
				},
				TestEvent{
					UserID:    6,
					ProjectID: 6,
				},
			},
		},
	})
	require.Empty(t, et.eventLists["x"].events)
	assert.Zero(t, et.AccumulatedEvents())
}
