package adminvalidator

import (
	"context"
	"errors"
	"regexp"

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

func (v Validator) ValidateLoginWithPhoneNumberRequest(ctx context.Context, req adminserviceparam.LoginWithPhoneNumberRequest) (map[string]string, error) {
	const op = "adminvalidator.ValidateLoginWithPhoneNumberRequest"

	if err := validation.ValidateStruct(&req,
		// TODO - add regex
		validation.Field(&req.Password, validation.Required, validation.NotNil,
			validation.Length(minLengthPassword, maxLengthPassword)),

		validation.Field(&req.PhoneNumber,
			validation.Required,
			validation.Match(regexp.MustCompile(phoneNumberRegex)).Error(errmsg.ErrorMsgPhoneNumberIsNotValid),
			validation.By(v.doesAdminExistByPhoneNumber(ctx)),
			validation.By(v.isAdminAllowed(ctx)),
		)); err != nil {
		fieldErrors := make(map[string]string)

		vErr := validation.Errors{}
		if errors.As(err, &vErr) {
			for key, value := range vErr {
				if value != nil {
					fieldErrors[key] = value.Error()
				}
			}
		}

		return fieldErrors, richerror.New(op).WithMessage(errmsg.ErrorMsgInvalidInput).
			WithKind(richerror.KindInvalid).
			WithMeta(map[string]interface{}{"req": req}).WithErr(err)
	}

	//nolint
	return nil, nil
}
