<?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)
    {
        $this->initializeLogger($data, [
            'externalId' => [
                'type' => $data->getType(),
                'id' => $data->getId(),
            ]
        ]);

        return $this->findExistingExternalId($data->getType(), $data->getId())
            ?? $this->createNewExternalId($data->getType(), $data->getId());
    }

    private function findExistingExternalId(string $type, string $id): ?ExternalId
    {
        return $this->externalIdRepository->findByTypeAndId($type, $id);
    }

    private function createNewExternalId(string $type, string $id): ExternalId
    {
        $externalId = new ExternalId();
        $externalId->setType($type);
        $externalId->setId($id);
        $this->externalIdRepository->add($externalId);

        return $externalId;
    }
}
