<?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\Serializer\Normalizer;

use Chill\MainBundle\Entity\UserGroup;
use Chill\MainBundle\Repository\UserGroupRepositoryInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

class UserGroupDenormalizer implements DenormalizerInterface
{
    public function __construct(private readonly UserGroupRepositoryInterface $userGroupRepository) {}

    public function denormalize($data, string $type, ?string $format = null, array $context = []): ?UserGroup
    {
        return $this->userGroupRepository->find($data['id']);
    }

    public function supportsDenormalization($data, string $type, ?string $format = null): bool
    {
        return UserGroup::class === $type
            && 'json' === $format
            && is_array($data)
            && array_key_exists('id', $data)
            && 'user_group' === ($data['type'] ?? false)
            && 2 === count(array_keys($data))
        ;
    }
}
