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

use Chill\PersonBundle\Entity\SocialWork\SocialAction;
use Chill\PersonBundle\Templating\Entity\SocialActionRender;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class SocialActionNormalizer implements NormalizerAwareInterface, NormalizerInterface
{
    use NormalizerAwareTrait;

    public function __construct(private readonly SocialActionRender $render) {}

    public function normalize($socialAction, $format = null, array $context = [])
    {
        switch ($format) {
            case 'json':
                return [
                    'id' => $socialAction->getId(),
                    'type' => 'social_work_social_action',
                    'text' => $this->render->renderString($socialAction, []),
                    'parent' => $this->normalizer->normalize($socialAction->getParent(), $format, $context),
                    'desactivationDate' => $this->normalizer->normalize($socialAction->getDesactivationDate(), $format, $context),
                    'title' => $socialAction->getTitle(),
                    'issue' => $this->normalizer->normalize($socialAction->getIssue(), $format, $context),
                    'ordering' => $socialAction->getOrdering(),
                ];

            case 'docgen':
                if (null === $socialAction) {
                    return ['id' => 0, 'title' => '', 'text' => ''];
                }

                return [
                    'id' => $socialAction->getId(),
                    'type' => 'social_work_social_action',
                    'text' => $this->render->renderString($socialAction, []),
                    'title' => $socialAction->getTitle(),
                    'parent' => $this->normalizer->normalize($socialAction->getParent(), $format, [...$context, 'docgen:expects' => SocialAction::class]),
                    'issue' => $this->normalizer->normalize($socialAction->getIssue(), $format, $context),
                ];

            default:
                throw new \Symfony\Component\Serializer\Exception\RuntimeException('format not supported');
        }
    }

    public function supportsNormalization($data, $format = null, array $context = [])
    {
        if ($data instanceof SocialAction && 'json' === $format) {
            return true;
        }

        if ('docgen' === $format) {
            if ($data instanceof SocialAction) {
                return true;
            }

            if (null === $data && SocialAction::class === ($context['docgen:expects'] ?? null)) {
                return true;
            }
        }

        return false;
    }
}
