<?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\Center;
use Chill\MainBundle\Repository\CenterRepository;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class CenterNormalizer implements DenormalizerInterface, NormalizerInterface
{
    public function __construct(private readonly CenterRepository $repository) {}

    public function denormalize($data, $type, $format = null, array $context = [])
    {
        if (null === $data) {
            return null;
        }

        if (false === \array_key_exists('type', $data)) {
            throw new InvalidArgumentException('missing "type" key in data');
        }

        if ('center' !== $data['type']) {
            throw new InvalidArgumentException('type should be equal to "center"');
        }

        if (false === \array_key_exists('id', $data)) {
            throw new InvalidArgumentException('missing "id" key in data');
        }

        $center = $this->repository->find($data['id']);

        if (null === $center) {
            throw new UnexpectedValueException("The type with id {$data['id']} does not exists");
        }

        return $center;
    }

    public function normalize($center, $format = null, array $context = [])
    {
        /* @var Center $center */
        return [
            'id' => $center->getId(),
            'type' => 'center',
            'name' => $center->getName(),
            'isActive' => $center->getIsActive(),
        ];
    }

    public function supportsDenormalization($data, $type, $format = null)
    {
        return Center::class === $type;
    }

    public function supportsNormalization($data, $format = null): bool
    {
        return $data instanceof Center && 'json' === $format;
    }
}
