<?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\OrderRepositoryInterface;
use RuntimeException;

/**
 * Class OrderSaver
 * @package FiloBlu\Esb\Model\Saver
 */
class OrderSaver extends AbstractEndpoint implements ObjectTypeSaverInterface
{
    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

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


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

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

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

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