<?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\Repository\AddressRepository;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

final readonly class AddressToIdDataTransformer implements DataTransformerInterface
{
    public function __construct(private AddressRepository $addressRepository) {}

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

        $address = $this->addressRepository->find($value);

        if (null === $address) {
            $failure = new TransformationFailedException(sprintf('Address with id %s does not exists', $value));
            $failure
                ->setInvalidMessage('The given {{ value }} is not a valid address id', ['{{ value }}' => $value]);

            throw $failure;
        }

        return $address;
    }

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

        return $value->getId();
    }
}
