<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Importer;

use Newland\Toubiz\Api\ObjectAdapter\ExternalIdAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\ExternalId;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ExternalIdRepository;
use Neos\Flow\Annotations as Flow;

class ExternalIdImporter extends AbstractImporter
{

    /**
     * @var ExternalIdRepository
     * @Flow\Inject()
     */
    protected $externalIdRepository;

    /**
     * @param ExternalIdAdapterInterface $data
     * @return ExternalId
     */
    public function import($data)
    {
        $externalId = $this->externalIdRepository->findByTypeAndId($data->getType(), $data->getId());
        if ($externalId) {
            return $externalId;
        }

        $externalId = new ExternalId();
        $externalId->setType($data->getType());
        $externalId->setId($data->getId());
        $this->externalIdRepository->add($externalId);
        return $externalId;
    }
}
