package api

import (
	"fmt"
	"testing"

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

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

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

	testEnv := newTestEnv(t)
	hostingMockLogic := testEnv.hostingMockLogic
	client := testEnv.client

	callerID := "11111111"
	userID := callerID

	enabled := false
	teamHost := true
	strategy := lib.AutohostStrategyOrdered
	settingsInput := lib.UpdateSettingsInput{
		Enabled:  &enabled,
		TeamHost: &teamHost,
		Strategy: &strategy,
	}
	expectedSettings := &lib.Settings{
		Strategy: strategy,
		Enabled:  enabled,
		TeamHost: teamHost,
	}
	hostingMockLogic.On("UpdateSettings", mock.Anything, callerID, userID, &settingsInput).Return(
		expectedSettings, nil).Once()

	returnedSettings, err := client.UpdateSettings(ctx, callerID, userID, settingsInput, nil)
	require.NoError(t, err)
	require.Equal(t, expectedSettings, returnedSettings)
}

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

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

	callerID := ""
	userID := "11111111"

	enabled := false
	teamHost := true
	strategy := lib.AutohostStrategyOrdered
	settingsInput := lib.UpdateSettingsInput{
		Enabled:  &enabled,
		TeamHost: &teamHost,
		Strategy: &strategy,
	}

	_, err := client.UpdateSettings(ctx, callerID, userID, settingsInput, nil)
	require.Error(t, err)
}

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

	testEnv := newTestEnv(t)
	hostingMockLogic := testEnv.hostingMockLogic
	client := testEnv.client

	callerID := "11111111"
	userID := callerID

	enabled := false
	teamHost := true
	strategy := lib.AutohostStrategyOrdered
	settingsInput := lib.UpdateSettingsInput{
		Enabled:  &enabled,
		TeamHost: &teamHost,
		Strategy: &strategy,
	}
	err := fmt.Errorf("a test error")
	hostingMockLogic.On("UpdateSettings", mock.Anything, callerID, userID, &settingsInput).Return(
		nil, err).Once()

	_, err = client.UpdateSettings(ctx, callerID, userID, settingsInput, nil)
	require.Error(t, err)
}
