<?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\Quote\Api\CartRepositoryInterface;
use RuntimeException;

/**
 * Class QuoteLoader
 * @package FiloBlu\Esb\Model\Loader
 */
class QuoteLoader extends AbstractEndpoint implements ObjectTypeLoaderInterface
{
    /**
     * @var \Magento\Quote\Api\CartRepositoryInterface
     */
    private $cartRepository;

    /**
     * QuoteLoader constructor.
     * @param \Magento\Quote\Api\CartRepositoryInterface $cartRepository
     * @param ObjectTypeDescriptorInterface $objectTypeDescriptor
     */
    public function __construct(CartRepositoryInterface $cartRepository, ObjectTypeDescriptorInterface $objectTypeDescriptor)
    {
        parent::__construct($objectTypeDescriptor);
        $this->cartRepository = $cartRepository;
    }

    /**
     * @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->cartRepository->get($objectType->getId());
    }

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

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