<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Observer;

use FiloBlu\Refilo\Helper\Catalog\CategoryHelper;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Indexer\IndexerRegistry;

use function in_array;

/**
 *
 */
class UpdateRefiloSearchObserver implements ObserverInterface
{
    /**
     * @var IndexerRegistry
     */
    private $indexerRegistry;

    /**
     * @param IndexerRegistry $indexerRegistry
     */
    public function __construct(IndexerRegistry $indexerRegistry)
    {
        $this->indexerRegistry = $indexerRegistry;
    }

    /**
     * @param Observer $observer
     */
    public function execute(Observer $observer)
    {
        $changedPaths = $observer->getData('changed_paths') ?? [];

        if (!$this->mustInvalidateIndex($changedPaths)) {
            return;
        }

        $indexer = $this->indexerRegistry->get('beehive_category');

        if ($indexer->isScheduled()) {
            $indexer->invalidate();
        }
    }

    /**
     * @param string[] $changedPaths
     * @return bool
     */
    public function mustInvalidateIndex(array $changedPaths): bool
    {
        foreach (
            [
                CategoryHelper::XML_REFILO_SEARCH_GENERAL_CATEGORY_FULL_PATH_SEPARATOR,
                CategoryHelper::XML_REFILO_SEARCH_GENERAL_USE_CATEGORY_FULL_PATH
            ] as $path
        ) {
            if (in_array($path, $changedPaths, true)) {
                return true;
            }
        }

        return false;
    }
}
