<?php


namespace Shop\Application\Shopping\MergeProducts;


use Shop\Models\Product\Product;
use Shop\Repositories\Product\ProductCriteria;
use Shop\Repositories\Product\ProductRepository;

/**
 * Class MergeProductsHandler
 * @package Shop\Commands\Catalog\MergeProducts
 */
class MergeProductsHandler
{
    protected $productRepository;

    /**
     * MergeProductsHandler constructor.
     * @param ProductRepository $productRepository
     */
    public function __construct(ProductRepository $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    /**
     * @param MergeProductsCommand $command
     * @throws \Propel\Runtime\Exception\PropelException
     * @throws \Repo\Concrete\Exceptions\Collection
     */
    public function handle(MergeProductsCommand $command): void
    {

        $productIds = $command->getMergeProductsIds();

        if (count($productIds) < 1) {
            throw new MergeProductsException('count products must be more than 1');
        }

        $targetId = $command->getTargetProductId();

        $productPrepareIds = array_filter($productIds, function ($el) use ($targetId) {
            return (int)$el !== $targetId;
        });

        $products = $this->productRepository->findByCriteria(
            ProductCriteria::create()->setFilterByIds($productPrepareIds)
        );

        if (!$targetProduct = $this->productRepository->findById($targetId)) {
            throw new MergeProductsException('product not found by id ' . $targetId);
        }

        /**
         * @var Product $product
         */
        foreach($products as $product){
            foreach($product->getPositions() as $position){
                $position->setProduct($targetProduct);
            }
        }

        $this->productRepository->save($targetProduct);

    }

}