<?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\MainBundle\Workflow\Messenger;

use Chill\MainBundle\Entity\Workflow\EntityWorkflowSend;
use Chill\MainBundle\Repository\Workflow\EntityWorkflowRepository;
use Chill\MainBundle\Workflow\EntityWorkflowManager;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

#[\Symfony\Component\Messenger\Attribute\AsMessageHandler]
final readonly class PostSendExternalMessageHandler
{
    public function __construct(
        private EntityWorkflowRepository $entityWorkflowRepository,
        private MailerInterface $mailer,
        private EntityWorkflowManager $workflowManager,
    ) {}
    public function __invoke(PostSendExternalMessage $message): void
    {
        $entityWorkflow = $this->entityWorkflowRepository->find($message->entityWorkflowId);

        if (null === $entityWorkflow) {
            throw new UnrecoverableMessageHandlingException(sprintf('Entity workflow with id %d not found', $message->entityWorkflowId));
        }

        foreach ($entityWorkflow->getCurrentStep()->getSends() as $send) {
            $this->sendEmailToDestinee($send, $message);
        }
    }
    private function sendEmailToDestinee(EntityWorkflowSend $send, PostSendExternalMessage $message): void
    {
        $entityWorkflow = $send->getEntityWorkflowStep()->getEntityWorkflow();
        $title = $this->workflowManager->getHandler($entityWorkflow)->getEntityTitle($entityWorkflow);
        $email = new TemplatedEmail();
        $email
            ->to($send->getDestineeThirdParty()?->getEmail() ?? $send->getDestineeEmail())
            ->subject($title)
            ->htmlTemplate('@ChillMain/Workflow/workflow_send_external_email_to_destinee.html.twig')
            ->context([
                'send' => $send,
                'lang' => $message->lang,
            ]);

        $this->mailer->send($email);
    }
}
