<?php


namespace Shop\Application\Shopping\MergeProducts;


use Propel\Runtime\Propel;
use Shop\Infrastructure\Models\Product\Product;
use Shop\Infrastructure\Repositories\Product\ProductCriteria;
use Shop\Infrastructure\Repositories\Product\ProductRepository;

/**
 * Class MergeProductsHandler
 * @package Shop\Presentation\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);

        foreach($products as $product){

            //@todo вынести в событие и команду
            if(class_exists('\PartScanner\Infrastructure\Models\SyncDraft\SyncDraftQuery')){
                $draft =  \PartScanner\Infrastructure\Models\SyncDraft\SyncDraftQuery::create()
                    ->findOneByLocalProductId($product->getId());
                if($draft !== null){
                    $draft->setLocalProductId($targetProduct->getId());
                    $draft->save();
                }
            }

            $this->productRepository->delete($product);
        }

    }

}