<?php

namespace FiloBlu\Esb\Model\Saver;

use FiloBlu\Esb\Api\Data\ObjectTypeDescriptorInterface;
use FiloBlu\Esb\Api\ObjectTypeSaverInterface;
use FiloBlu\Esb\Framework\ObjectType\Endpoint\AbstractEndpoint;
use Magento\Sales\Api\CreditmemoRepositoryInterface;
use RuntimeException;

/**
 * Class CreditmemoSaver
 * @package FiloBlu\Esb\Model\Saver
 */
class CreditmemoSaver extends AbstractEndpoint implements ObjectTypeSaverInterface
{
    /**
     * @var CreditmemoRepositoryInterface
     */
    private $creditmemoRepository;

    /**
     * CreditmemoLoader constructor.
     * @param CreditmemoRepositoryInterface $creditmemoRepository
     * @param ObjectTypeDescriptorInterface $objectTypeDescriptor
     */
    public function __construct(CreditmemoRepositoryInterface $creditmemoRepository, ObjectTypeDescriptorInterface $objectTypeDescriptor)
    {
        parent::__construct($objectTypeDescriptor);
        $this->creditmemoRepository = $creditmemoRepository;
    }


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

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

    /**
     * @inheritDoc
     */
    public function save(ObjectTypeDescriptorInterface $objectType, $objectToSave)
    {
        if (!$this->isSuitableFor($objectType)) {
            throw new RuntimeException("Incompatible loader for type {$objectType->getTypeCode()}");
        }

        $this->creditmemoRepository->save($objectToSave);
    }
}
