<?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\Customer\Api\AddressRepositoryInterface;
use RuntimeException;

/**
 * Class CustomerAddressSaver
 * @package FiloBlu\Esb\Model\Saver
 */
class CustomerAddressSaver extends AbstractEndpoint implements ObjectTypeSaverInterface
{
    /**
     * @var AddressRepositoryInterface
     */
    private $customerAddressRepository;

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

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

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

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

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