<?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\SocialIssue;
use Chill\PersonBundle\Templating\Entity\SocialIssueRender;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;

class SocialIssueNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
{
    use NormalizerAwareTrait;

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

    public function normalize($socialIssue, $format = null, array $context = [])
    {
        /* @var SocialIssue $socialIssue */
        switch ($format) {
            case 'json':
                return [
                    'type' => 'social_issue',
                    'id' => $socialIssue->getId(),
                    'parent_id' => $socialIssue->hasParent() ? $socialIssue->getParent()->getId() : null,
                    'children_ids' => $socialIssue->getChildren()->map(static fn (SocialIssue $si) => $si->getId()),
                    'title' => $socialIssue->getTitle(),
                    'text' => $this->render->renderString($socialIssue, []),
                    'ordering' => $socialIssue->getOrdering(),
                ];

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

                return [
                    'id' => $socialIssue->getId(),
                    'title' => $socialIssue->getTitle(),
                    'text' => $this->render->renderString($socialIssue, []),
                ];
        }
    }

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

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

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

        return false;
    }
}
