package server

import (
	"context"
	"fmt"
	"testing"

	"code.justin.tv/live/autohost/rpc/hosting"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
	"github.com/twitchtv/twirp"
)

func TestSetAutohostList_Success(t *testing.T) {
	testEnv := newTestEnvWithMockLogic(t)
	mockLogic := testEnv.mockLogic
	client := testEnv.client

	callerID := "11111111"
	userID := "222222222"
	targetIDs := []string{"33333333", "44444444"}
	mockLogic.
		On("SetList", mock.Anything, callerID, userID, targetIDs).
		Return(targetIDs, nil).Once()

	ctx := context.Background()
	resp, err := client.SetAutohostList(ctx, &hosting.SetAutohostListRequest{
		CallerId:  callerID,
		SourceId:  userID,
		TargetIds: targetIDs,
	})
	require.NoError(t, err)
	require.NotNil(t, resp)

	expectedResponse := &hosting.SetAutohostListResponse{
		TargetIds: targetIDs,
	}
	require.Equal(t, expectedResponse, resp)
}

func TestSetAutohostList_SuccessEmptyList(t *testing.T) {
	testEnv := newTestEnvWithMockLogic(t)
	mockLogic := testEnv.mockLogic
	client := testEnv.client

	callerID := "11111111"
	userID := "222222222"
	targetIDs := make([]string, 0)
	mockLogic.
		On("SetList", mock.Anything, callerID, userID, targetIDs).
		Return(targetIDs, nil).Once()

	ctx := context.Background()
	resp, err := client.SetAutohostList(ctx, &hosting.SetAutohostListRequest{
		CallerId:  callerID,
		SourceId:  userID,
		TargetIds: nil,
	})
	require.NoError(t, err)
	require.NotNil(t, resp)

	expectedResponse := &hosting.SetAutohostListResponse{}
	require.Equal(t, expectedResponse, resp)
}

func TestSetAutohostList_ServerError(t *testing.T) {
	testEnv := newTestEnvWithMockLogic(t)
	mockLogic := testEnv.mockLogic
	client := testEnv.client

	callerID := "11111111"
	userID := "222222222"
	targetIDs := []string{"33333333", "44444444"}
	err := fmt.Errorf("a test error")
	mockLogic.
		On("SetList", mock.Anything, callerID, userID, targetIDs).
		Return(nil, err).Once()

	ctx := context.Background()
	resp, err := client.SetAutohostList(ctx, &hosting.SetAutohostListRequest{
		CallerId:  callerID,
		SourceId:  userID,
		TargetIds: targetIDs,
	})
	requireTwirpError(t, twirp.Internal, err)
	require.Nil(t, resp)
}
