package servicecatalog

import (
	"context"
	"testing"

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

func TestGet(t *testing.T) {
	ctx := context.Background()
	t.Run("should retrieve items from the cache", func(t *testing.T) {
		s := New()
		s.cache.Set("1", &Response{
			Name: "name1",
		}, expiry)
		r, err := s.getNonLocal(ctx, "1")
		require.NoError(t, err)
		require.Equal(t, r.Name, "name1")
	})

	t.Run("should respect negative caches", func(t *testing.T) {
		s := New()
		s.cacheMissingService("1")
		r, err := s.getNonLocal(ctx, "1")
		require.Nil(t, r)
		require.Error(t, err)
		require.Equal(t, ErrDoesNotExist, err)
	})

	t.Run("should fall back to service catalog", func(t *testing.T) {
		s := New()
		mockServices := []Service{
			Service{
				ID:   "2",
				Name: "name2",
			},
		}
		s.fetcher = &mockFetcher{
			mockServices: mockServices,
		}
		r, err := s.getNonLocal(ctx, "2")
		require.NoError(t, err)
		require.Equal(t, r.Name, "name2")
	})

	t.Run("errors when item not found and caches missing service", func(t *testing.T) {
		s := New()
		s.fetcher = &mockFetcher{mockServices: []Service{}}
		r, err := s.getNonLocal(ctx, "3")
		require.Error(t, err)
		require.Equal(t, ErrDoesNotExist, err)
		require.Nil(t, r)

		item := s.cache.Get("3")
		require.Equal(t, item.Value(), &NonExistentService{})
	})
}
