<?php
declare(strict_types=1);

namespace Autogedal\Extend\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Autogedal\Extend\Model\Product\SpecsDescriptionManager;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;

class UpdateProductDescriptionOnSave implements ObserverInterface
{

    public function __construct(
        private readonly SpecsDescriptionManager $specsManager,
        private readonly CategoryCollectionFactory $categoryCollectionFactory
    ) {}


    public function execute(Observer $observer): void
    {
        $product = $observer->getEvent()->getProduct();
        if (!$product) {
            return;
        }

        $categoryIds = $product->getCategoryIds();
        if (empty($categoryIds)) {
            return;
        }

        if ($this->isProductInCategory($categoryIds, '59')) {
            $this->specsManager->updateDescription($product);
        }
    }


    private function isProductInCategory(array $categoryIds, string $targetCategoryId): bool
    {
        $collection = $this->categoryCollectionFactory->create()
            ->addAttributeToSelect('path')
            ->addFieldToFilter('entity_id', ['in' => $categoryIds]);

        foreach ($collection as $category) {
            $pathIds = explode('/', (string)$category->getPath());
            if (in_array($targetCategoryId, $pathIds, true)) {
                return true;
            }
        }

        return false;
    }
}
