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

use Chill\CalendarBundle\Repository\CalendarDocRepositoryInterface;
use Chill\CalendarBundle\Service\GenericDoc\Providers\AccompanyingPeriodCalendarGenericDocProvider;
use Chill\CalendarBundle\Service\GenericDoc\Renderers\AccompanyingPeriodCalendarGenericDocRenderer;
use Chill\DocStoreBundle\GenericDoc\GenericDocDTO;
use Chill\DocStoreBundle\GenericDoc\GenericDocNormalizerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;

final readonly class AccompanyingPeriodCalendarGenericDocNormalizer implements GenericDocNormalizerInterface
{
    public function __construct(
        private AccompanyingPeriodCalendarGenericDocRenderer $renderer,
        private CalendarDocRepositoryInterface $calendarDocRepository,
        private Environment $twig,
        private TranslatorInterface $translator,
    ) {}

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

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

        return [
            'isPresent' => true,
            'title' => $calendarDoc->getStoredObject()->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])
            ),
        ];
    }
}
