<?php

declare(strict_types=1);

namespace FiloBlu\Esb\Model\Loader;

use FiloBlu\Esb\Api\Data\ObjectTypeDescriptorInterface;
use FiloBlu\Esb\Api\Data\ObjectTypeInterface;
use FiloBlu\Esb\Api\ObjectTypeLoaderInterface;
use FiloBlu\Esb\Framework\ObjectType\Endpoint\AbstractEndpoint;
use Magento\Catalog\Api\ProductRepositoryInterface;
use RuntimeException;

/**
 * Class ProductLoader
 * @package FiloBlu\Esb\Model\Loader
 */
class ProductLoader extends AbstractEndpoint implements ObjectTypeLoaderInterface
{
    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * ProductLoader constructor.
     * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
     * @param ObjectTypeDescriptorInterface $objectTypeDescriptor
     */
    public function __construct(ProductRepositoryInterface $productRepository, ObjectTypeDescriptorInterface $objectTypeDescriptor)
    {
        parent::__construct($objectTypeDescriptor);
        $this->productRepository = $productRepository;
    }

    /**
     * @inheritDoc
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function get(ObjectTypeInterface $objectType)
    {
        if (!$this->isSuitableFor($objectType)) {
            throw new RuntimeException("Incompatible loader for type {$objectType->getTypeCode()}");
        }

        return $this->productRepository->getById($objectType->getId());
    }

    /**
     * @inheritDoc
     */
    public function getName(): string
    {
        return 'Esb Product Loader';
    }

    /**
     * @inheritDoc
     */
    public function getUniqueName(): string
    {
        return 'FiloBlu_Esb::product_loader';
    }
}
