<?php

namespace FiloBlu\Rma\Plugin\Rma\Model\Service;

use Magento\Customer\Model\AttributeMetadataDataProvider;
use Magento\Eav\Model\Config;
use Magento\Eav\Model\Entity\Attribute\AbstractAttribute;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Rma\Api\RmaAttributesManagementInterface;
use Magento\Rma\Model\Service\RmaAttributesManagement as MagentoRmaAttributesManagement;

class RmaAttributesManagement
{
    /**
     * @var Config
     */
    protected $eavConfig;
    /**
     * @var AttributeMetadataDataProvider
     */
    protected $metadataDataProvider;
    /**
     * @var ProductMetadataInterface
     */
    protected $productMetadata;

    /**
     * @param Config $eavConfig
     * @param AttributeMetadataDataProvider $metadataDataProvider
     * @param ProductMetadataInterface $productMetadata
     */
    public function __construct(
        Config $eavConfig,
        AttributeMetadataDataProvider $metadataDataProvider,
        ProductMetadataInterface $productMetadata
    )
    {
        $this->eavConfig = $eavConfig;
        $this->metadataDataProvider = $metadataDataProvider;
        $this->productMetadata = $productMetadata;
    }

    /**
     * @param MagentoRmaAttributesManagement $subject
     * @param $result
     * @return array
     * @throws LocalizedException
     */
    public function afterGetAllAttributesMetadata(MagentoRmaAttributesManagement $subject, $result)
    {
        if (version_compare($this->productMetadata->getVersion(), '2.4.2', '>')) {
            return $result;
        }

        $rmaItemEntityAttributeSetId = $this->eavConfig->getEntityType(RmaAttributesManagementInterface::ENTITY_TYPE)->getDefaultAttributeSetId();

        /** @var AbstractAttribute[] $attribute */
        $attributeCodes = $this->metadataDataProvider->getAllAttributeCodes(
            RmaAttributesManagementInterface::ENTITY_TYPE,
            $rmaItemEntityAttributeSetId
        );

        $attributesMetadata = [];
        foreach ($attributeCodes as $attributeCode) {
            try {
                $attributesMetadata[] = $subject->getAttributeMetadata($attributeCode);
            } catch (NoSuchEntityException $e) {
                continue;
            }
        }

        return $attributesMetadata;
    }
}
