<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Serializer\SerializerInterface;

final class JsonModelTransformer implements DataTransformerInterface
{
    public function __construct(
        private readonly SerializerInterface $serializer,
        private readonly string $className,
    ) {
    }

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

        // Si c'est déjà le bon objet
        if (\is_object($value) && $value instanceof $this->className) {
            return $value;
        }

        // Si c'est un array (ex: json déserialisé), on hydrate l'objet
        if (\is_array($value)) {
            return $this->serializer->denormalize($value, $this->className);
        }

        return $value;
    }

    public function reverseTransform(mixed $value): mixed
    {
        if (null === $value) {
            return null;
        }

        // On stocke en array normalisé
        if (\is_object($value) && $value instanceof $this->className) {
            return $this->serializer->normalize($value);
        }

        return $value;
    }
}
