<?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\RequestInterface;
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 CategorySaveAfterObserverEmotionalProducts
 * @package FiloBlu\Refilo\Observer
 */
class CategorySaveAfterObserverEmotionalProducts implements ObserverInterface
{

    /** @var string */
    const EMOTIONAL_PRODUCTS_KEY = 'emotional_products';

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

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

    /** @var MetadataPool */
    private $metadataPool;

    /** @var RequestInterface */
    private $request;

    /**
     * @param AttributeRepositoryInterface $attributeRepository
     * @param ResourceConnection $resourceConnection
     * @param MetadataPool $metadataPool
     * @param RequestInterface $request
     */
    public function __construct(
        AttributeRepositoryInterface $attributeRepository,
        ResourceConnection           $resourceConnection,
        MetadataPool                 $metadataPool,
        RequestInterface             $request
    ) {
        $this->attributeRepository = $attributeRepository;
        $this->resourceConnection = $resourceConnection;
        $this->metadataPool = $metadataPool;
        $this->request = $request;
    }

    /**
     * @param Observer $observer
     * @return void|null
     * @throws Exception
     */
    public function execute(Observer $observer)
    {
        $post = $this->request->getPost();
        if ($post['emotional_products'] !== null) {
            return;
        }

        $category = $observer->getData('category');
        $originalEmotionalProducts = $category->getOrigdata(self::EMOTIONAL_PRODUCTS_KEY);
        if ($post['emotional_products'] === $originalEmotionalProducts) {
            return null;
        }

        $connection = $this->resourceConnection->getConnection();

        try {
            $attributeId = $this->attributeRepository->get(
                Category::ENTITY,
                self::EMOTIONAL_PRODUCTS_KEY
            )->getAttributeId();
        } catch (NoSuchEntityException $noSuchEntityException) {
            return;
        }

        if (!$attributeId) {
            return;
        }

        $linkField = $this->metadataPool->getMetadata(CategoryInterface::class)->getLinkField();
        $linkFieldId = $post[$linkField] ?? '';
        $storeId = $post['store_id'] ?? '';

        if (!isset($linkField, $linkFieldId, $storeId)) {
            return;
        }

        try {
            $connection->delete('catalog_category_entity_text',
                [
                    "$linkField = ?" => $linkFieldId,
                    'attribute_id = ?' => $attributeId,
                    'store_id = ?' => $storeId
                ]
            );
        } catch (Exception $exception) {
            return;
        }
    }
}
