<?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\CustomFieldsBundle\Form\DataTransformer;

use Chill\CustomFieldsBundle\Entity\CustomFieldsGroup;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class CustomFieldsGroupToIdTransformer implements DataTransformerInterface
{
    public function __construct(private readonly ObjectManager $om) {}

    /**
     * Transforms a string (id) to an object (CustomFieldsGroup).
     *
     * @param string $id
     *
     * @throws TransformationFailedException if object (report) is not found
     */
    public function reverseTransform($id): ?CustomFieldsGroup
    {
        if (!$id) {
            return null;
        }

        if ($id instanceof CustomFieldsGroup) {
            throw new TransformationFailedException('The transformation failed: the expected argument on reverseTransform is an object of type int,Chill\CustomFieldsBundle\Entity\CustomFieldsGroup, given');
        }

        $customFieldsGroup = $this->om
            ->getRepository(CustomFieldsGroup::class)->find($id);

        if (null === $customFieldsGroup) {
            throw new TransformationFailedException(sprintf('Le group avec le numéro "%s" ne peut pas être trouvé!', $id));
        }

        return $customFieldsGroup;
    }

    /**
     * Transforms an custom_field_group to a string (id).
     *
     * @param CustomFieldsGroup|null $customFieldsGroup
     *
     * @return string
     */
    public function transform($customFieldsGroup)
    {
        if (null === $customFieldsGroup) {
            return '';
        }

        if (!$customFieldsGroup instanceof CustomFieldsGroup) {
            throw new TransformationFailedException(sprintf('Transformation failed: the expected type of the transforme function is an object of type Chill\CustomFieldsBundle\Entity\CustomFieldsGroup, %s given (value : %s)', \gettype($customFieldsGroup), $customFieldsGroup));
        }

        return $customFieldsGroup->getId();
    }
}
