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"
	"github.com/go-ozzo/ozzo-validation/is"
	validation "github.com/go-ozzo/ozzo-validation/v4"
)

func (v Validator) ValidateRegisterRequest(ctx context.Context, req adminserviceparam.RegisterRequest) (map[string]string, error) {
	const op = "adminvalidator.ValidateRegisterRequest"
	if err := validation.ValidateStruct(&req,
		// TODO - add length of code config from benefactor config
		validation.Field(&req.FirstName,
			validation.Length(minLengthFirstName, maxLengthFirstName)),
		validation.Field(&req.LastName,
			validation.Length(minLengthLastName, maxLengthLastName)),

		// TODO - add regex
		validation.Field(&req.Password, validation.Required, validation.NotNil,
			validation.Length(minLengthPassword, maxLengthPassword)),
		validation.Field(&req.Gender, validation.By(v.IsGenderValid)),
		validation.Field(&req.Role, validation.By(v.IsRoleValid), validation.Required),
		validation.Field(&req.Status, validation.By(v.IsStatusValid), validation.Required),
		validation.Field(&req.Email, validation.Required, is.Email,
			validation.By(v.doesAdminExistByEmail(ctx))),

		validation.Field(&req.PhoneNumber,
			validation.Required,
			validation.Match(regexp.MustCompile(phoneNumberRegex)).Error(errmsg.ErrorMsgPhoneNumberIsNotValid),
			validation.By(v.IsPhoneNumberUnique(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
}
