package benefactoraddressvalidator

import (
	"context"
	"fmt"

	param "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactor"
	errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
	validation "github.com/go-ozzo/ozzo-validation/v4"
)

//go:generate mockery --name BenefactorSvc
type BenefactorSvc interface {
	BenefactorExistByID(ctx context.Context, request param.BenefactorExistByIDRequest) (param.BenefactorExistByIDResponse, error)
}

//go:generate mockery --name Repository
type Repository interface {
	IsExistCityByID(ctx context.Context, id uint) (bool, error)
	IsExistAddressByID(ctx context.Context, addressID uint, benefactorID uint) (bool, error)
}
type Validator struct {
	benefactorSvc BenefactorSvc
	repository    Repository
}

func New(benefactorSvc BenefactorSvc, repository Repository) Validator {
	return Validator{benefactorSvc: benefactorSvc, repository: repository}
}

func (v Validator) doesBenefactorExist(ctx context.Context) validation.RuleFunc {
	return func(value interface{}) error {
		benefactorID, ok := value.(uint)
		if !ok {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}
		res, err := v.benefactorSvc.BenefactorExistByID(ctx, param.BenefactorExistByIDRequest{ID: benefactorID})
		if err != nil {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}

		if !res.Existed {
			return fmt.Errorf(errmsg.ErrorMsgBenefactorNotFound)
		}

		return nil
	}
}

func (v Validator) doesCityExist(ctx context.Context) validation.RuleFunc {
	return func(value interface{}) error {
		cityID, ok := value.(uint)
		if !ok {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}
		isExisted, err := v.repository.IsExistCityByID(ctx, cityID)
		if err != nil {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}
		if !isExisted {
			return fmt.Errorf(errmsg.ErrorMsgNotFound)
		}

		return nil
	}
}

func (v Validator) doesAddressExist(ctx context.Context, benefactorID uint) validation.RuleFunc {
	return func(value interface{}) error {
		addressID, ok := value.(uint)
		if !ok {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}
		isExisted, err := v.repository.IsExistAddressByID(ctx, addressID, benefactorID)
		if err != nil {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}
		if !isExisted {
			return fmt.Errorf(errmsg.ErrorMsgNotFound)
		}

		return nil
	}
}