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

use Chill\ActivityBundle\Service\GenericDoc\Providers\AccompanyingPeriodActivityGenericDocProvider;
use Chill\ActivityBundle\Service\GenericDoc\Renderers\AccompanyingPeriodActivityGenericDocRenderer;
use Chill\DocStoreBundle\GenericDoc\GenericDocDTO;
use Chill\DocStoreBundle\GenericDoc\GenericDocNormalizerInterface;
use Chill\DocStoreBundle\Repository\StoredObjectRepositoryInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;

final readonly class AccompanyingPeriodActivityGenericDocNormalizer implements GenericDocNormalizerInterface
{
    public function __construct(
        private StoredObjectRepositoryInterface $storedObjectRepository,
        private AccompanyingPeriodActivityGenericDocRenderer $renderer,
        private Environment $twig,
        private TranslatorInterface $translator,
    ) {}

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

    public function normalize(GenericDocDTO $genericDocDTO, string $format, array $context = []): array
    {
        $storedObject = $this->storedObjectRepository->find($genericDocDTO->identifiers['id']);

        if (null === $storedObject) {
            return ['title' => $this->translator->trans('generic_doc.document removed'), 'isPresent' => false];
        }

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