package benefactorvalidator

import (
	"context"
	"testing"

	"git.gocasts.ir/ebhomengo/niki/entity"
	benefactoreparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactor"
	errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
	"github.com/stretchr/testify/assert"
)

func TestValidator_ValidateSendOtpRequest(t *testing.T) {
	mockRepository := NewMockRepository(t)
	validator := New(mockRepository)

	validPhoneNumber := "09123456789"
	ctx := context.Background()

	t.Run("Valid request", func(t *testing.T) {
		req := benefactoreparam.SendOtpRequest{
			PhoneNumber: validPhoneNumber,
		}

		mockRepository.EXPECT().GetByPhoneNumber(ctx, req.PhoneNumber).Return(entity.Benefactor{
			Status: entity.BenefactorActiveStatus,
		}, nil).Once()

		fieldErrors, err := validator.ValidateSendOtpRequest(ctx, req)
		assert.NoError(t, err)
		assert.Nil(t, fieldErrors)
	})

	t.Run("Empty phone number", func(t *testing.T) {
		req := benefactoreparam.SendOtpRequest{
			PhoneNumber: "",
		}

		fieldErrors, err := validator.ValidateSendOtpRequest(ctx, req)
		assert.Error(t, err)
		assert.NotNil(t, fieldErrors)
		assert.Contains(t, fieldErrors, "phone_number")
	})

	t.Run("Invalid phone number format", func(t *testing.T) {
		req := benefactoreparam.SendOtpRequest{
			PhoneNumber: "12345",
		}

		fieldErrors, err := validator.ValidateSendOtpRequest(ctx, req)
		assert.Error(t, err)
		assert.NotNil(t, fieldErrors)
		assert.Equal(t, errmsg.ErrorMsgPhoneNumberIsNotValid, fieldErrors["phone_number"])
	})

	t.Run("Inactive user is not allowed", func(t *testing.T) {
		req := benefactoreparam.SendOtpRequest{
			PhoneNumber: validPhoneNumber,
		}

		mockRepository.EXPECT().GetByPhoneNumber(ctx, req.PhoneNumber).Return(entity.Benefactor{
			Status: entity.BenefactorInactiveStatus,
		}, nil).Once()

		fieldErrors, err := validator.ValidateSendOtpRequest(ctx, req)
		assert.Error(t, err)
		assert.NotNil(t, fieldErrors)
		assert.Equal(t, errmsg.ErrorMsgUserNotAllowed, fieldErrors["phone_number"])
	})

	t.Run("new users are allowed", func(t *testing.T) {
		req := benefactoreparam.SendOtpRequest{
			PhoneNumber: validPhoneNumber,
		}

		mockRepository.EXPECT().GetByPhoneNumber(ctx, req.PhoneNumber).Return(entity.Benefactor{}, richerror.New("test").
			WithKind(richerror.KindNotFound)).Once()

		fieldErrors, err := validator.ValidateSendOtpRequest(ctx, req)
		assert.NoError(t, err)
		assert.Nil(t, fieldErrors)
	})
}
