// +build integration

package logic

import (
	"context"
	"testing"

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

func TestAddList(t *testing.T) {
	t.Run("Adds to list", func(t *testing.T) {
		channelID := NewRandomUserID()
		callerID := NewRandomUserID()
		auth_ := auth.NewAuthStub().WithCanEditChannel(callerID, channelID)

		testEnv := newTestEnv(t, &Params{
			Auth: auth_,
		})
		l := testEnv.logic

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

		list, err := l.AddList(context.Background(), callerID, channelID, usersToAdd)
		require.NoError(t, err)
		require.Equal(t, usersToAdd, list)

		user3 := NewRandomUserID()
		user4 := NewRandomUserID()
		usersToAdd = []string{user3, user4}

		list, err = l.AddList(context.Background(), callerID, channelID, usersToAdd)
		require.NoError(t, err)
		expectedList := []string{user1, user2, user3, user4}
		require.Equal(t, expectedList, list)
	})

	t.Run("Excludes self from the list", func(t *testing.T) {
		channelID := NewRandomUserID()
		callerID := channelID
		auth_ := auth.NewAuthStub().WithCanEditChannel(callerID, callerID)

		testEnv := newTestEnv(t, &Params{
			Auth: auth_,
		})
		l := testEnv.logic

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

		list, err := l.AddList(context.Background(), callerID, channelID, usersToAdd)
		require.NoError(t, err)
		require.Contains(t, list, user1)
		require.NotContains(t, list, channelID)
	})

	t.Run("Excludes duplicates from the list", func(t *testing.T) {
		channelID := NewRandomUserID()
		callerID := channelID
		auth_ := auth.NewAuthStub().WithCanEditChannel(callerID, callerID)

		testEnv := newTestEnv(t, &Params{
			Auth: auth_,
		})
		l := testEnv.logic

		user1 := NewRandomUserID()
		usersToAdd := []string{user1, user1}

		list, err := l.AddList(context.Background(), callerID, channelID, usersToAdd)
		require.NoError(t, err)
		require.Len(t, list, 1)
		require.Contains(t, list, user1)
	})

	t.Run("Failed auth", func(t *testing.T) {
		channelID := NewRandomUserID()
		callerID := NewRandomUserID()
		auth_ := auth.NewDenyAllStub()

		testEnv := newTestEnv(t, &Params{
			Auth: auth_,
		})
		l := testEnv.logic

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

		_, err := l.AddList(context.Background(), callerID, channelID, usersToAdd)
		require.Equal(t, err, autohosterrors.Forbidden)
	})
}
