package cartsService

import (
	"git.ma-al.com/goc_daniel/b2b/app/model"
	"git.ma-al.com/goc_daniel/b2b/app/repos/cartsRepo"
	constdata "git.ma-al.com/goc_daniel/b2b/app/utils/const_data"
	"git.ma-al.com/goc_daniel/b2b/app/utils/responseErrors"
)

type CartsService struct {
	repo cartsRepo.UICartsRepo
}

func New() *CartsService {
	return &CartsService{
		repo: cartsRepo.New(),
	}
}

func (s *CartsService) CreateNewCart(user_id uint) (model.CustomerCart, error) {
	var cart model.CustomerCart

	customers_carts_amount, err := s.repo.CartsAmount(user_id)
	if err != nil {
		return cart, err
	}
	if customers_carts_amount >= constdata.MAX_AMOUNT_OF_CARTS_PER_USER {
		return cart, responseErrors.ErrMaxAmtOfCartsReached
	}

	// create new cart for customer
	cart, err = s.repo.CreateNewCart(user_id)

	return cart, nil
}

func (s *CartsService) UpdateCartName(user_id uint, cart_id uint, new_name string) error {
	amt, err := s.repo.UserHasCart(user_id, cart_id)
	if err != nil {
		return err
	}
	if amt != 1 {
		return responseErrors.ErrUserHasNoSuchCart
	}

	return s.repo.UpdateCartName(user_id, cart_id, new_name)
}

func (s *CartsService) RetrieveCartsInfo(user_id uint) ([]model.CustomerCart, error) {
	return s.repo.RetrieveCartsInfo(user_id)
}

func (s *CartsService) RetrieveCart(user_id uint, cart_id uint) (*model.CustomerCart, error) {
	amt, err := s.repo.UserHasCart(user_id, cart_id)
	if err != nil {
		return nil, err
	}
	if amt != 1 {
		return nil, responseErrors.ErrUserHasNoSuchCart
	}

	return s.repo.RetrieveCart(user_id, cart_id)
}

func (s *CartsService) AddProduct(user_id uint, cart_id uint, product_id uint, product_attribute_id *uint, amount uint) error {
	amt, err := s.repo.UserHasCart(user_id, cart_id)
	if err != nil {
		return err
	}
	if amt != 1 {
		return responseErrors.ErrUserHasNoSuchCart
	}

	amt, err = s.repo.CheckProductExists(product_id, product_attribute_id)
	if err != nil {
		return err
	}
	if amt != 1 {
		return responseErrors.ErrProductOrItsVariationDoesNotExist
	}

	return s.repo.AddProduct(user_id, cart_id, product_id, product_attribute_id, amount)
}
