package benefactorkindboxreqvalidator

import (
	"context"
	"errors"
	"testing"

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

func TestValidator_ValidateDeleteRequest(t *testing.T) {
	mockRepository := NewMockRepository(t)
	mockAddressSvc := NewMockAddressSvc(t)
	mockReferTimeSvc := NewMockReferTimeSvc(t)
	validator := New(mockAddressSvc, mockReferTimeSvc, mockRepository)
	ctx := context.Background()

	t.Run("Successful validation", func(t *testing.T) {
		req := kindboxreqparam.KindBoxReqDeleteRequest{
			BenefactorID: 1,
			KindBoxReqID: 1,
		}

		mockRepository.EXPECT().GetKindBoxReqByID(ctx, uint(1)).Return(
			entity.KindBoxReq{BenefactorID: 1, Status: entity.KindBoxReqPendingStatus},
			nil,
		).Twice()

		fieldErrors, err := validator.ValidateDeleteRequest(ctx, req)

		assert.NoError(t, err)
		assert.Nil(t, fieldErrors)
	})

	t.Run("Empty KindBoxReq id", func(t *testing.T) {
		req := kindboxreqparam.KindBoxReqDeleteRequest{
			BenefactorID: 1,
			KindBoxReqID: 0,
		}

		fieldErrors, err := validator.ValidateDeleteRequest(ctx, req)

		assert.Error(t, err)
		assert.NotNil(t, fieldErrors)
		assert.Contains(t, fieldErrors, "KindBoxReqID")
	})

	t.Run("Invalid KindBoxReq status", func(t *testing.T) {
		req := kindboxreqparam.KindBoxReqDeleteRequest{
			BenefactorID: 1,
			KindBoxReqID: 2,
		}

		mockRepository.EXPECT().GetKindBoxReqByID(ctx, uint(2)).Return(
			entity.KindBoxReq{BenefactorID: 1, Status: entity.KindBoxReqDeliveredStatus},
			nil,
		).Once()

		fieldErrors, err := validator.ValidateDeleteRequest(ctx, req)

		assert.Error(t, err)
		assert.NotNil(t, fieldErrors)
		assert.Contains(t, fieldErrors, "KindBoxReqID")
	})

	t.Run("KindBoxReq does not belong to benefactor", func(t *testing.T) {
		req := kindboxreqparam.KindBoxReqDeleteRequest{
			BenefactorID: 1,
			KindBoxReqID: 3,
		}

		mockRepository.EXPECT().GetKindBoxReqByID(ctx, uint(3)).Return(
			entity.KindBoxReq{BenefactorID: 4, Status: entity.KindBoxReqPendingStatus},
			nil,
		).Twice()

		fieldErrors, err := validator.ValidateDeleteRequest(ctx, req)

		assert.Error(t, err)
		assert.NotNil(t, fieldErrors)
		assert.Contains(t, fieldErrors, "KindBoxReqID")
	})

	t.Run("KindBoxReq service error", func(t *testing.T) {
		req := kindboxreqparam.KindBoxReqDeleteRequest{
			BenefactorID: 1,
			KindBoxReqID: 1,
		}

		mockRepository.EXPECT().GetKindBoxReqByID(ctx, uint(1)).Return(
			entity.KindBoxReq{BenefactorID: 1, Status: entity.KindBoxReqPendingStatus},
			errors.New("service error"),
		).Once()

		fieldErrors, err := validator.ValidateDeleteRequest(ctx, req)

		assert.Error(t, err)
		assert.NotNil(t, fieldErrors)
		assert.Equal(t, errmsg.ErrorMsgNotFound, fieldErrors["KindBoxReqID"])
	})
}
