<?php
declare(strict_types=1);

namespace Autogedal\Manufacturers\Model\Config\Backend;

use Autogedal\Manufacturers\Model\ManufacturerPage;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Value;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Indexer\CacheContextFactory;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;

class InactiveManufacturers extends Value
{
    public function __construct(
        Context $context,
        Registry $registry,
        ScopeConfigInterface $config,
        TypeListInterface $cacheTypeList,
        private readonly CacheContextFactory $cacheContextFactory,
        ?AbstractResource $resource = null,
        ?AbstractDb $resourceCollection = null,
        array $data = []
    ) {
        parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
    }

    public function beforeSave(): self
    {
        $statuses = $this->getValue();
        if (is_array($statuses)) {
            $inactiveIds = array_keys(array_filter($statuses, static fn ($isActive): bool => !$isActive));
            sort($inactiveIds);
            $this->setValue(implode(',', $inactiveIds));
        }

        return parent::beforeSave();
    }

    public function afterSave(): self
    {
        if ($this->isValueChanged()) {
            $oldIds = array_map('intval', explode(',', $this->getOldValue()));
            $newIds = array_map('intval', explode(',', (string)$this->getValue()));
            $changedIds = array_filter(array_merge(array_diff($oldIds, $newIds), array_diff($newIds, $oldIds)));

            $cacheContext = $this->cacheContextFactory->create();
            $cacheContext->registerTags([ManufacturerPage::CACHE_TAG]);
            $cacheContext->registerEntities(ManufacturerPage::MANUFACTURER_CACHE_TAG, $changedIds);
            $this->_eventManager->dispatch('clean_cache_by_tags', ['object' => $cacheContext]);
        }

        return parent::afterSave();
    }
}
