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

use Chill\DocStoreBundle\GenericDoc\GenericDocDTO;
use Chill\DocStoreBundle\GenericDoc\GenericDocNormalizerInterface;
use Chill\DocStoreBundle\GenericDoc\Providers\PersonDocumentGenericDocProvider;
use Chill\DocStoreBundle\GenericDoc\Renderer\AccompanyingCourseDocumentGenericDocRenderer;
use Chill\DocStoreBundle\Repository\PersonDocumentRepository;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;

final readonly class PersonDocumentGenericDocNormalizer implements GenericDocNormalizerInterface
{
    public function __construct(
        private PersonDocumentRepository $personDocumentRepository,
        private AccompanyingCourseDocumentGenericDocRenderer $renderer,
        private Environment $twig,
        private TranslatorInterface $translator,
    ) {}

    public function supportsNormalization(GenericDocDTO $genericDocDTO, string $format, array $context = []): bool
    {
        return PersonDocumentGenericDocProvider::KEY === $genericDocDTO->key && 'json' === $format;
    }

    public function normalize(GenericDocDTO $genericDocDTO, string $format, array $context = []): array
    {
        if (null === $personDocument = $this->personDocumentRepository->find($genericDocDTO->identifiers['id'])) {
            return ['title' => $this->translator->trans('generic_doc.document removed'), 'isPresent' => false];
        }

        return [
            'isPresent' => true,
            'title' => $personDocument->getTitle(),
            'html' => $this->twig->render(
                $this->renderer->getTemplate($genericDocDTO, ['show-actions' => false, 'row-only' => true]),
                $this->renderer->getTemplateData($genericDocDTO, ['show-actions' => false, 'row-only' => true])
            ),
        ];
    }
}
