package bulk

import (
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"code.justin.tv/d8a/buddy/lib/config"
	"code.justin.tv/d8a/iceman/lib/bulk"
)

func TestGetWorkableBulk(t *testing.T) {
	store := &BulkRecordStore{
		cache:           make(CachedBulkRecords),
		lastRefreshTime: make(map[string]time.Time),
	}
	store.lastRefreshTime["test"] = time.Now()
	conf := &config.ConfigFile{
		Cluster: []*config.Cluster{
			&config.Cluster{
				Name: "test",
			},
		},
	}
	store.cache["test"] = make(map[string]*StatusEntry)

	rec, err := store.GetWorkableBulk(conf)
	require.Nil(t, err)
	require.Nil(t, rec)

	recentBulk := &StatusEntry{
		bulk.BulkRecord{
			Name:       "recent",
			Complete:   false,
			NextRow:    0,
			ExecutedAt: time.Now(),
		},
		StatusData{
			Cluster: "test",
		},
	}

	oldBulk := &StatusEntry{
		bulk.BulkRecord{
			Name:       "old",
			Complete:   false,
			NextRow:    0,
			ExecutedAt: time.Now().Add(-5 * time.Minute),
		},
		StatusData{
			Cluster: "test",
		},
	}

	completedBulk := &StatusEntry{
		bulk.BulkRecord{
			Name:       "completed",
			Complete:   true,
			NextRow:    0,
			ExecutedAt: time.Now(),
		},
		StatusData{
			Cluster: "test",
		},
	}

	store.cache["test"]["recent"] = recentBulk
	rec, err = store.GetWorkableBulk(conf)
	require.Nil(t, err)
	require.Equal(t, recentBulk, rec)

	store.cache["test"]["old"] = oldBulk
	rec, err = store.GetWorkableBulk(conf)
	require.Nil(t, err)
	require.Equal(t, oldBulk, rec)

	store.cache["test"]["completed"] = completedBulk
	rec, err = store.GetWorkableBulk(conf)
	require.Nil(t, err)
	require.Equal(t, oldBulk, rec)

	delete(store.cache["test"], "old")
	rec, err = store.GetWorkableBulk(conf)
	require.Nil(t, err)
	require.Equal(t, recentBulk, rec)

	delete(store.cache["test"], "recent")
	rec, err = store.GetWorkableBulk(conf)
	require.Nil(t, err)
	require.Nil(t, rec)
}
