package server

import (
	"context"
	"fmt"
	"testing"

	"github.com/twitchtv/twirp"

	"code.justin.tv/live/autohost/rpc/hosting"

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

	"code.justin.tv/live/autohost/lib"
)

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

	callerID := "11111111"
	userID := "222222222"
	expectedSettings := &lib.Settings{
		Strategy: lib.AutohostStrategyOrdered,
		Enabled:  false,
		TeamHost: true,
	}
	mockLogic.
		On("GetSettings", mock.Anything, callerID, userID).
		Return(expectedSettings, nil).Once()

	ctx := context.Background()
	resp, err := client.GetAutohostSettings(ctx, &hosting.GetAutohostSettingsRequest{
		CallerId: callerID,
		UserId:   userID,
	})
	require.NoError(t, err)

	expectedResponse := &hosting.GetAutohostSettingsResponse{
		Settings: &hosting.AutohostSettings{
			Enabled:  false,
			TeamHost: true,
			Strategy: hosting.AutohostStrategy_AUTOHOST_STRATEGY_ORDERED,
		},
	}
	require.Equal(t, expectedResponse, resp)
}

func TestGetAutohostSettings_CallerIDRequired(t *testing.T) {
	ctx, cancel := getContextWithTimeout()
	defer cancel()

	testEnv := newTestEnvWithMockLogic(t)
	client := testEnv.client

	callerID := ""
	userID := "11111111"

	resp, err := client.GetAutohostSettings(ctx, &hosting.GetAutohostSettingsRequest{
		CallerId: callerID,
		UserId:   userID,
	})
	requireTwirpError(t, twirp.InvalidArgument, err)
	require.Nil(t, resp)
}

func TestGetAutohostSettings_ServerError(t *testing.T) {
	ctx, cancel := getContextWithTimeout()
	defer cancel()

	testEnv := newTestEnvWithMockLogic(t)
	mockLogic := testEnv.mockLogic
	client := testEnv.client

	callerID := "11111111"
	userID := "222222222"
	err := fmt.Errorf("a test error")
	mockLogic.On("GetSettings", mock.Anything, callerID, userID).Return(
		nil, err).Once()

	resp, err := client.GetAutohostSettings(ctx, &hosting.GetAutohostSettingsRequest{
		CallerId: callerID,
		UserId:   userID,
	})
	requireTwirpError(t, twirp.Internal, err)
	require.Nil(t, resp)
}
