<?php
declare(strict_types=1);

namespace Autogedal\Labels\Model\Attribute;

use Autogedal\Labels\Model\ResourceModel\Label\CollectionFactory;
use Magento\Store\Model\StoreManagerInterface;

class ActiveAttributeCodesProvider
{
    private CollectionFactory $collectionFactory;
    private StoreManagerInterface $storeManager;

    public function __construct(
        CollectionFactory $collectionFactory,
        StoreManagerInterface $storeManager
    ) {
        $this->collectionFactory = $collectionFactory;
        $this->storeManager = $storeManager;
    }

    /**
     * Return attribute codes used by active labels that can affect frontend
     * product matching.
     *
     * @return string[]
     */
    public function getAttributeCodes(): array
    {
        $storeId = (int)$this->storeManager->getStore()->getId();
        $codes = [];

        $collection = $this->collectionFactory->create();
        $collection->addFieldToFilter('is_active', 1);

        foreach ($collection as $label) {
            $stores = (string)$label->getData('stores');
            if ($stores !== '' && strpos($stores, ',0,') === false && strpos($stores, ',' . $storeId . ',') === false) {
                continue;
            }

            $attrCode = trim((string)$label->getData('attr_code'));
            if ($attrCode === '') {
                continue;
            }

            $codes[$attrCode] = true;
        }

        return array_keys($codes);
    }
}
