<?php

declare(strict_types=1);

namespace App\Message\Handler;

use App\Entity\Message\Email;
use App\Message\Command\MailerCommand;
use App\Repository\Access\AccessRepository;
use App\Service\Mailer\Mailer;
use App\Service\Notifier;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(priority: 1)]
class MailerHandler
{
    public function __construct(
        private Mailer           $mailer,
        private Notifier         $notifier,
        private AccessRepository $accessRepository
    )
    {
    }

    public function __invoke(MailerCommand $mailerCommand): void
    {
        $mailerModel = $mailerCommand->getMailerModel();
        $emails = $this->mailer->main($mailerModel);

        if ($mailerModel->getNotify()) {
            /** @var Email */
            $email = $emails->first()->getEmailEntity();

            $this->notifier->notifyMessage(
                $this->accessRepository->find($mailerCommand->getMailerModel()->getSenderId()),
                ['about' => $email->getAbout()]
            );
        }
    }
}
