<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Observer;

use Exception;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Eav\Api\AttributeRepositoryInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\EntityManager\MetadataPool;

/**
 *
 */
class CategorySaveAfterObserver implements ObserverInterface
{

    /** @var AttributeRepositoryInterface */
    protected $attributeRepository;

    /** @var ResourceConnection */
    protected $resourceConnection;

    /** @var \Magento\Framework\EntityManager\MetadataPool */
    private $metadataPool;

    /**
     * @param \Magento\Eav\Api\AttributeRepositoryInterface $attributeRepository
     * @param \Magento\Framework\App\ResourceConnection $resourceConnection
     * @param \Magento\Framework\EntityManager\MetadataPool $metadataPool
     */
    public function __construct(
        AttributeRepositoryInterface $attributeRepository,
        ResourceConnection $resourceConnection,
        MetadataPool $metadataPool


    ) {
        $this->attributeRepository = $attributeRepository;
        $this->resourceConnection = $resourceConnection;
        $this->metadataPool = $metadataPool;
    }

    /**
     * @param Observer $observer
     * @throws Exception
     */
    public function execute(Observer $observer)
    {
        /** @var CategoryInterface|Category $category */
        $category = $observer->getData('category');
        $childrenCategories = $category->getChildrenCategories();
        try {
            $attributeId = $this->attributeRepository->get(
                Category::ENTITY,
                'refilo_exclude_from_search'
            )->getAttributeId();
        } catch (NoSuchEntityException $noSuchEntityException) {
            return;
        }

        if (!$attributeId || !$childrenCategories->getAllIds()) {
            return;
        }

        $value = (int)$category->getData('refilo_exclude_from_search');
        $storeId = $category->getStoreId();
        $childrenIds = implode(',', $category->getChildrenCategories()->getAllIds());
        $linkField = $this->metadataPool->getMetadata(CategoryInterface::class)->getLinkField();
        $connection = $this->resourceConnection->getConnection();
        $connection->update(
            'catalog_category_entity_int',
            ['value' => $value],
            "attribute_id = $attributeId AND $linkField in ($childrenIds) AND store_id = $storeId"
        );
    }
}
