// +build integration

package logic

import (
	"context"
	"fmt"
	"testing"

	"code.justin.tv/live/autohost/internal/hosting/redis"

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

func TestUnhost(t *testing.T) {
	t.Run("unhost succeeds", func(t *testing.T) {
		callerID := NewRandomUserID()
		channelID := NewRandomUserID()

		mockClue := &clue.MockClient{}
		mockClue.On("Unhost", context.Background(), channelID).Return(nil)

		testEnv := newTestEnv(t, &Params{
			ClueClient: mockClue,
			Auth:       auth.NewAllowAllStub(),
		})
		l := testEnv.logic

		err := l.Unhost(context.Background(), callerID, channelID)
		require.NoError(t, err)
	})

	t.Run("unhost fails", func(t *testing.T) {
		callerID := NewRandomUserID()
		channelID := NewRandomUserID()

		mockClue := &clue.MockClient{}
		resErr := fmt.Errorf("mocked hostmode.Host error")
		mockClue.On("Unhost", context.Background(), channelID).Return(resErr)

		testEnv := newTestEnv(t, &Params{
			ClueClient: mockClue,
			Auth:       auth.NewAllowAllStub(),
		})
		l := testEnv.logic

		err := l.Unhost(context.Background(), callerID, channelID)
		require.Error(t, err)
	})

	t.Run("user is not authorized", func(t *testing.T) {
		callerID := NewRandomUserID()
		channelID := NewRandomUserID()

		mockClue := &clue.MockClient{}
		mockClue.On("Unhost", context.Background(), channelID).Return(nil)

		testEnv := newTestEnv(t, &Params{
			ClueClient: mockClue,
			Auth:       auth.NewDenyAllStub(),
		})
		l := testEnv.logic

		err := l.Unhost(context.Background(), callerID, channelID)
		require.Error(t, err)
	})

	t.Run("user is rate limited", func(t *testing.T) {
		callerID := NewRandomUserID()
		channelID := callerID

		mockClue := &clue.MockClient{}
		mockClue.On("Unhost", context.Background(), channelID).Return(nil)

		testEnv := newTestEnv(t, &Params{
			ClueClient:  mockClue,
			Auth:        auth.NewDenyAllStub(),
			RateLimiter: redis.NewRateLimiterStub(false),
		})
		l := testEnv.logic

		err := l.Unhost(context.Background(), callerID, channelID)
		require.Error(t, err)
		require.Equal(t, "TooManyRequests", err.Error())
	})
}
