package adminkindboxreqvalidator

import (
	"context"
	"errors"
	"fmt"
	"slices"

	"git.gocasts.ir/ebhomengo/niki/entity"
	params "git.gocasts.ir/ebhomengo/niki/param"
	param "git.gocasts.ir/ebhomengo/niki/param/admin/admin"
	refertimeparam "git.gocasts.ir/ebhomengo/niki/param/admin/refer_time"
	addressparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/address"
	errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
	benefactorsvc "git.gocasts.ir/ebhomengo/niki/service/admin/benefactor"
	validation "github.com/go-ozzo/ozzo-validation/v4"
)

const (
	MinKindBoxReq = 1
	MaxKindBoxReq = 100
)

type Repository interface {
	KindBoxRequestExist(id uint) (bool, error)
	GetByID(ctx context.Context, id uint) (entity.KindBoxReq, error)
}

type AdminSvc interface {
	AdminExistByID(ctx context.Context, req param.AdminExistByIDRequest) (param.AdminExistByIDResponse, error)
	AgentExistByID(ctx context.Context, agentID uint) (bool, error)
}

type ReferTimeSvc interface {
	GetReferTimeByID(ctx context.Context, req refertimeparam.GetReferTimeRequest) (refertimeparam.GetReferTimeResponse, error)
}

type AddressSvc interface {
	AddressExistByID(ctx context.Context, request addressparam.GetAddressByIDRequest) (addressparam.GetAddressByIDResponse, error)
}

type Validator struct {
	repo          Repository
	adminSvc      AdminSvc
	benefactorSvc benefactorsvc.Service
	referTimeSvc  ReferTimeSvc
	addressSvc    AddressSvc
}

func New(repo Repository, adminSvc AdminSvc, benefactorSvc benefactorsvc.Service, referTimeSvc ReferTimeSvc, addressSvc AddressSvc) Validator {
	return Validator{repo: repo, adminSvc: adminSvc, benefactorSvc: benefactorSvc, referTimeSvc: referTimeSvc, addressSvc: addressSvc}
}

func (v Validator) doesKindBoxRequestExist(value interface{}) error {
	kindboxreqID, ok := value.(uint)
	if !ok {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	if isExist, err := v.repo.KindBoxRequestExist(kindboxreqID); !isExist || err != nil {
		if err != nil {
			return err
		}
		if !isExist {
			return errors.New("kind box request is not exist")
		}
	}

	return nil
}

func (v Validator) CheckKindBoxReqStatusForAccepting(value interface{}) error {
	kindboxreqID, ok := value.(uint)
	if !ok {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	kindBox, err := v.repo.GetByID(context.Background(), kindboxreqID)
	if err != nil {
		return err
	}
	if kindBox.Status != entity.KindBoxReqPendingStatus {
		return fmt.Errorf(errmsg.ErrorMsgAcceptKindBoxReqStatus)
	}

	return nil
}

func (v Validator) CheckKindBoxReqStatusForRejecting(value interface{}) error {
	kindboxreqID, ok := value.(uint)
	if !ok {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	kindBox, err := v.repo.GetByID(context.Background(), kindboxreqID)
	if err != nil {
		return err
	}
	if kindBox.Status != entity.KindBoxReqPendingStatus {
		return fmt.Errorf(errmsg.ErrorMsgRejectKindBoxReqStatus)
	}

	return nil
}

func (v Validator) checkKindBoxReqStatusForDelivering(value interface{}) error {
	kindboxreqID, ok := value.(uint)
	if !ok {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	kindBoxReq, err := v.repo.GetByID(context.Background(), kindboxreqID)
	if err != nil {
		return err
	}
	if kindBoxReq.Status != entity.KindBoxReqAssignedSenderAgentStatus {
		return fmt.Errorf(errmsg.ErrorMsgDeliverKindBoxReqStatus)
	}

	return nil
}

func (v Validator) checkKindBoxReqStatusForAssigningSenderAgent(value interface{}) error {
	kindboxreqID, ok := value.(uint)
	if !ok {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	kindBoxReq, err := v.repo.GetByID(context.Background(), kindboxreqID)
	if err != nil {
		return err
	}
	if kindBoxReq.Status != entity.KindBoxReqAcceptedStatus {
		return fmt.Errorf(errmsg.ErrorMsgAssignSenderAgentKindBoxReqStatus)
	}

	return nil
}

func (v Validator) checkCountAcceptedMustBeLessThanCountRequested(kindboxreqID uint) validation.RuleFunc {
	return func(value interface{}) error {
		countAccepted, ok := value.(uint)
		if !ok {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}
		kindBoxReq, err := v.repo.GetByID(context.Background(), kindboxreqID)
		if err != nil {
			return err
		}
		if kindBoxReq.CountRequested < countAccepted {
			return fmt.Errorf(errmsg.ErrorMsgCountAcceptedOverflow)
		}
		return nil
	}
}

func (v Validator) doesAgentAdminExist(value interface{}) error {
	adminID, ok := value.(uint)
	if !ok {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	resp, err := v.adminSvc.AdminExistByID(context.Background(), param.AdminExistByIDRequest{
		AdminID: adminID,
	})
	if err != nil {
		return err
	}
	if resp.Admin.Role != entity.AdminAgentRole {
		return fmt.Errorf(errmsg.ErrorMsgAdminIsNotAgent)
	}

	return nil
}

func (v Validator) areFilterFieldsValid(validFilters []string) validation.RuleFunc {
	return func(value interface{}) error {
		filters, ok := value.(params.FilterRequest)
		if !ok {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}
		for filter := range filters {
			if !slices.Contains(validFilters, filter) {
				return fmt.Errorf(errmsg.ErrorMsgFiltersAreNotValid)
			}
		}
		return nil
	}
}

func (v Validator) areSortFieldsValid(validSortFields []string) validation.RuleFunc {
	return func(value interface{}) error {
		sort, ok := value.(params.SortRequest)
		if !ok {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}
		if sort.Field == "" && sort.Direction != "" {
			return fmt.Errorf(errmsg.ErrorMsgSortFieldIsRequired)
		}
		if sort.Direction != "" && sort.Direction != params.AscSortDirection && sort.Direction != params.DescSortDirection {
			return fmt.Errorf(errmsg.ErrorMsgSortDirectionShouldBeAscOrDesc)
		}
		if sort.Field != "" && !slices.Contains(validSortFields, sort.Field) {
			return fmt.Errorf(errmsg.ErrorMsgSortFieldIsNotValid)
		}
		return nil
	}
}

func (v Validator) isReferTimeIDValid(value interface{}) error {
	referTimeID, ok := value.(uint)
	if !ok {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	resp, gErr := v.referTimeSvc.GetReferTimeByID(context.Background(), refertimeparam.GetReferTimeRequest{
		ReferTimeID: referTimeID,
	})
	if gErr != nil {
		return fmt.Errorf(errmsg.ErrorMsgReferTimeNotFound)
	}
	if resp.ReferTime.Status != entity.ReferTimeActiveStatus {
		return fmt.Errorf(errmsg.ErrorMsgReferTimeIsNotActive)
	}
	return nil
}

func (v Validator) doesAgentExist(value interface{}) error {
	agentID, ok := value.(uint)
	if !ok {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	exists, err := v.adminSvc.AgentExistByID(context.Background(), agentID)
	if err != nil {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	if !exists {
		return fmt.Errorf(errmsg.ErrorMsgNotFound)
	}

	return nil
}

func (v Validator) doesBenefactorAddressExist(kindBoxReqID uint) validation.RuleFunc {
	return func(value interface{}) error {
		addressID, ok := value.(uint)
		if !ok {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}

		kindBoxReq, err := v.repo.GetByID(context.Background(), kindBoxReqID)
		if err != nil {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}

		address, aErr := v.addressSvc.AddressExistByID(context.Background(), addressparam.GetAddressByIDRequest{ID: addressID})
		if aErr != nil {
			return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
		}
		if address.Address == nil {
			return fmt.Errorf(errmsg.ErrorMsgNotFound)
		}
		if address.Address.BenefactorID != kindBoxReq.BenefactorID {
			return fmt.Errorf(errmsg.ErrorMsgNotFound)
		}

		return nil
	}
}
