<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Form\Type\DataTransformer;

use Chill\MainBundle\Entity\PostalCode;
use Chill\MainBundle\Repository\PostalCodeRepositoryInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class PostalCodeToIdTransformer implements DataTransformerInterface
{
    public function __construct(private readonly PostalCodeRepositoryInterface $postalCodeRepository) {}

    public function reverseTransform($value)
    {
        if (null === $value || trim('') === $value) {
            return null;
        }

        if (!\is_int((int) $value)) {
            throw new TransformationFailedException('Cannot transform '.\gettype($value));
        }

        return $this->postalCodeRepository->find((int) $value);
    }

    public function transform($value)
    {
        if (null === $value) {
            return null;
        }

        if ($value instanceof PostalCode) {
            return $value->getId();
        }

        throw new TransformationFailedException('Could not reverseTransform '.\gettype($value));
    }
}
