// +build integration

package logic

import (
	"context"
	"testing"

	"code.justin.tv/live/autohost/internal/hosting/auth"
	"github.com/stretchr/testify/require"
)

func TestSetList_Success(t *testing.T) {
	testEnv := newTestEnv(t, &Params{
		Auth: auth.NewAllowAllStub(),
	})
	l := testEnv.logic

	channelID := NewRandomUserID()
	user1 := NewRandomUserID()
	user2 := NewRandomUserID()
	list := []string{user1, user2, channelID}
	expectedList := []string{user1, user2}

	updatedList, err := l.SetList(context.Background(), channelID, channelID, list)
	require.NoError(t, err)
	require.Equal(t, expectedList, updatedList)

	// You should not be able to add yourself to your list.
	require.NotContains(t, updatedList, channelID)
}

func TestSetList_Cached(t *testing.T) {
	testEnv := newTestEnv(t, &Params{
		Auth: auth.NewAllowAllStub(),
	})
	l := testEnv.logic
	cache := testEnv.memcachedCache

	channelID := NewRandomUserID()
	user1 := NewRandomUserID()
	user2 := NewRandomUserID()
	list := []string{user1, user2}

	updatedList, err := l.SetList(context.Background(), channelID, channelID, list)
	require.NoError(t, err)
	require.Contains(t, updatedList, user1)
	require.Contains(t, updatedList, user2)

	// Verify that list is set in cache.
	resultList, inCache, err := cache.GetList(context.Background(), channelID)
	require.NoError(t, err)
	require.True(t, inCache)
	require.Equal(t, resultList, list)
}

func TestSetList_Unauthorized(t *testing.T) {
	testEnv := newTestEnv(t, &Params{
		Auth: auth.NewDenyAllStub(),
	})
	l := testEnv.logic

	channelID := NewRandomUserID()
	user1 := NewRandomUserID()
	user2 := NewRandomUserID()
	list := []string{user1, user2, channelID}

	updatedList, err := l.SetList(context.Background(), channelID, channelID, list)
	require.Error(t, err)
	require.Nil(t, updatedList)
}
