package validation

import (
	"context"
	"testing"

	"code.justin.tv/eventbus/controlplane/internal/clients/mocks"
	"code.justin.tv/eventbus/controlplane/internal/clients/servicecatalog"
	"code.justin.tv/eventbus/controlplane/internal/db"
	"github.com/pkg/errors"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

func TestServiceValidate(t *testing.T) {
	ctx := context.Background()

	t.Run("OK when found in catalog", func(t *testing.T) {
		scMock := &mocks.Client{}
		scMock.On("Get", mock.Anything, "123").Return(&servicecatalog.Response{}, nil)

		service := serviceValidator(scMock, "123")
		report, err := service.Validate(ctx)

		assert.NoError(t, err)
		assert.Equal(t, StatusOk, report.Status)
	})

	t.Run("WARN when missing from catalog", func(t *testing.T) {
		scMock := &mocks.Client{}
		scMock.On("Get", mock.Anything, "234").Return(nil, servicecatalog.ErrDoesNotExist)

		service := serviceValidator(scMock, "234")
		report, err := service.Validate(ctx)

		assert.NoError(t, err)
		assert.Equal(t, ErrServiceNotInCatalog, report.Message)
		assert.Equal(t, StatusWarn, report.Status)
	})

	t.Run("Errors on unexpected failures", func(t *testing.T) {
		scMock := &mocks.Client{}
		scMock.On("Get", mock.Anything, "345").Return(nil, errors.New("an unexpected error"))

		service := serviceValidator(scMock, "345")
		report, err := service.Validate(ctx)

		assert.Error(t, err)
		assert.Nil(t, report)
	})
}

func serviceValidator(client servicecatalog.Client, id string) *Service {
	return &Service{
		Service: &db.Service{
			ServiceCatalogID: id,
		},
		serviceCatalog: client,
	}
}
