<?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\Notification;

use Chill\MainBundle\Entity\Notification;
use Chill\MainBundle\Notification\NotificationHandlerInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWork;
use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodWorkRepository;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Contracts\Translation\TranslatableInterface;

final readonly class AccompanyingPeriodWorkNotificationHandler implements NotificationHandlerInterface
{
    public function __construct(private AccompanyingPeriodWorkRepository $accompanyingPeriodWorkRepository, private TranslatableStringHelperInterface $translatableStringHelper) {}

    public function getTemplate(Notification $notification, array $options = []): string
    {
        return '@ChillPerson/AccompanyingCourseWork/showInNotification.html.twig';
    }

    public function getTemplateData(Notification $notification, array $options = []): array
    {
        return [
            'notification' => $notification,
            'work' => $this->accompanyingPeriodWorkRepository->find($notification->getRelatedEntityId()),
        ];
    }

    public function supports(Notification $notification, array $options = []): bool
    {
        return AccompanyingPeriodWork::class === $notification->getRelatedEntityClass();
    }

    public function getTitle(Notification $notification, array $options = []): TranslatableInterface
    {
        if (null === $work = $this->getRelatedEntity($notification)) {
            return new TranslatableMessage('accompanying_course_work.deleted');
        }

        return new TranslatableMessage('accompanying_period_work.title', [
            'id' => $work->getId(),
            'action_title' => $this->translatableStringHelper->localize($work->getSocialAction()->getTitle()),
        ]);
    }

    public function getAssociatedPersons(Notification $notification, array $options = []): array
    {
        if (null === $work = $this->getRelatedEntity($notification)) {
            return [];
        }

        return $work->getPersons()->getValues();
    }

    public function getRelatedEntity(Notification $notification): ?AccompanyingPeriodWork
    {
        return $this->accompanyingPeriodWorkRepository->find($notification->getRelatedEntityId());
    }
}
