package adminkindboxvalidator

import (
	"context"
	"fmt"

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

type Repository interface {
	KindBoxExist(ctx context.Context, kindBoxID uint) (bool, error)
	GetKindBox(ctx context.Context, kindBoxID uint) (entity.KindBox, error)
}

type AdminSvc interface {
	AgentExistByID(ctx context.Context, agentID uint) (bool, error)
}

type Validator struct {
	repo     Repository
	adminSvc AdminSvc
}

func New(repo Repository, adminSvc AdminSvc) Validator {
	return Validator{repo: repo, adminSvc: adminSvc}
}

func (v Validator) doesKindBoxExist(value interface{}) error {
	kindBoxID, ok := value.(uint)
	if !ok {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	exists, err := v.repo.KindBoxExist(context.Background(), kindBoxID)
	if err != nil {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	if !exists {
		return fmt.Errorf(errmsg.ErrorMsgNotFound)
	}

	return nil
}

func (v Validator) checkKindBoxStatusForAssigningReceiverAgent(value interface{}) error {
	kindboxID, ok := value.(uint)
	if !ok {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	kindBox, err := v.repo.GetKindBox(context.Background(), kindboxID)
	if err != nil {
		return fmt.Errorf(errmsg.ErrorMsgSomethingWentWrong)
	}
	if kindBox.Status != entity.KindBoxReadyToReturnStatus {
		return fmt.Errorf(errmsg.ErrorMsgAssignReceiverAgentKindBoxStatus)
	}

	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
}
