<?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\Exception\UnexpectedValueException;
use Chill\DocStoreBundle\GenericDoc\GenericDocDTO;
use Chill\DocStoreBundle\GenericDoc\GenericDocNormalizerInterface;
use Chill\DocStoreBundle\GenericDoc\Providers\AccompanyingCourseDocumentGenericDocProvider;
use Chill\DocStoreBundle\GenericDoc\Renderer\AccompanyingCourseDocumentGenericDocRenderer;
use Chill\DocStoreBundle\Repository\AccompanyingCourseDocumentRepository;
use Twig\Environment;

class AccompanyingCourseDocumentGenericDocNormalizer implements GenericDocNormalizerInterface
{
    public function __construct(
        private readonly AccompanyingCourseDocumentRepository $repository,
        private readonly Environment $twig,
        private readonly AccompanyingCourseDocumentGenericDocRenderer $renderer,
    ) {}

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

    public function normalize(GenericDocDTO $genericDocDTO, string $format, array $context = []): array
    {
        if (!array_key_exists('id', $genericDocDTO->identifiers)) {
            throw new UnexpectedValueException('key id not found in identifier');
        }

        $document = $this->repository->find($genericDocDTO->identifiers['id']);

        if (null === $document) {
            throw new UnexpectedValueException('document not found with id '.$genericDocDTO->identifiers['id']);
        }

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