<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Messaging;

use App\Administration\Domain\Event\CompteActive;
use App\Administration\Domain\Model\User\Role;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Mime\Email;
use Twig\Environment;

/**
 * Sends a confirmation email when an account is activated.
 *
 * This handler listens for CompteActive events and sends an email
 * to the user confirming their account activation.
 */
#[AsMessageHandler(bus: 'event.bus')]
final readonly class SendActivationConfirmationHandler
{
    public function __construct(
        private MailerInterface $mailer,
        private Environment $twig,
        private string $appUrl,
        private string $fromEmail = 'noreply@classeo.fr',
    ) {
    }

    public function __invoke(CompteActive $event): void
    {
        $roleEnum = Role::tryFrom($event->role);
        $roleLabel = $roleEnum?->label() ?? $event->role;

        $html = $this->twig->render('emails/activation_confirmation.html.twig', [
            'email' => $event->email,
            'role' => $roleLabel,
            'loginUrl' => rtrim($this->appUrl, '/') . '/login',
        ]);

        $email = (new Email())
            ->from($this->fromEmail)
            ->to($event->email)
            ->subject('Votre compte Classeo est activé')
            ->html($html);

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