package users_test

import (
	"context"
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"

	"code.justin.tv/live/autohost/internal/worker/clients/users"
	"code.justin.tv/live/autohost/internal/worker/clients/users/mocks"
	userModels "code.justin.tv/web/users-service/models"
)

var (
	mockUsers *mocks.InternalUsersClient
)

func resetMocks() {
	mockUsers = &mocks.InternalUsersClient{}
}

func TestGetChannelIDs(t *testing.T) {
	resetMocks()

	usersService := &users.Service{
		Client: mockUsers,
	}

	logins := []string{"1", "2", "3"}

	t.Run("GetChannelIDs returns an error if GetUsers returns an error", func(t *testing.T) {
		usersErr := fmt.Errorf("users error")
		mockUsers.On("GetUsers", mock.Anything, &userModels.FilterParams{
			Logins:                     logins,
			InlineIdentifierValidation: true,
		}, mock.Anything).Return(nil, usersErr).Once()

		_, err := usersService.GetChannelIDs(context.Background(), logins)

		assert.NotNil(t, err)
	})

	t.Run("GetChannelIDs only returns IDs of channels with valid logins", func(t *testing.T) {
		IDs := []string{"1", "2", "3"}
		mockUsers.On("GetUsers", mock.Anything, &userModels.FilterParams{
			Logins:                     logins,
			InlineIdentifierValidation: true,
		}, mock.Anything).Return(&userModels.PropertiesResult{
			Results: []*userModels.Properties{
				{
					ID:    IDs[0],
					Login: &logins[0],
				},
				{
					ID: IDs[1],
				},
				{
					ID:    IDs[2],
					Login: &logins[2],
				},
			},
		}, nil).Once()

		channelIDs, err := usersService.GetChannelIDs(context.Background(), logins)

		assert.EqualValues(t, map[string]string{"1": "1", "3": "3"}, channelIDs)
		assert.Nil(t, err)
	})
}
