<?php
namespace Newland\Toubiz\Sync\Neos\Importer;

/*
 * This file is part of the "toubiz-sync-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Newland\Toubiz\Api\Service\WithUuidPredictionService;
use Newland\Toubiz\Sync\Neos\Domain\Model\ZipCode;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ZipCodeRepository;
use Neos\Flow\Annotations as Flow;

class ZipCodeImporter
{
    use WithUuidPredictionService;

    /**
     * @var ZipCodeRepository
     * @Flow\Inject()
     */
    protected $zipCodeRepository;

    public function import(string $zipCodeValue, string $country = null): ?ZipCode
    {
        $identifier = $this->uuidPredictionService->predictForType(
            'zipCode',
            [
                'zipCode' => $zipCodeValue,
                'country' => $country,
            ]
        );

        $zipCode = $this->zipCodeRepository->findByIdentifier($identifier);
        $persisted = (bool) $zipCode;

        if (!$zipCode) {
            $zipCode = new ZipCode();
        }

        $zipCode->setZipCode($zipCodeValue);
        $zipCode->setCountry($country);

        if ($persisted) {
            $this->zipCodeRepository->update($zipCode);
        } else {
            $this->zipCodeRepository->add($zipCode);
        }

        return $zipCode;
    }
}
