package benefactorvalidator

import (
	"context"
	"errors"
	"fmt"

	"git.gocasts.ir/ebhomengo/niki/entity"
	errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)

const (
	phoneNumberRegex = "^09\\d{9}$"
)

//go:generate mockery --name Repository
type Repository interface {
	GetByPhoneNumber(ctx context.Context, phoneNumber string) (entity.Benefactor, error)
}

type Validator struct {
	repo Repository
}

func New(repo Repository) Validator {
	return Validator{repo: repo}
}

func (v Validator) isBenefactorAllowed(ctx context.Context) func(interface{}) error {
	return func(value interface{}) error {
		phoneNumber, ok := value.(string)
		if !ok {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}
		bnf, err := v.repo.GetByPhoneNumber(ctx, phoneNumber)
		if err != nil {
			// new users are always allowed
			var richErr richerror.RichError
			if errors.As(err, &richErr) && richErr.Kind() == richerror.KindNotFound {
				return nil
			}

			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}
		if bnf.Status == entity.BenefactorInactiveStatus {
			return fmt.Errorf(errmsg.ErrorMsgUserNotAllowed)
		}

		return nil
	}
}
