<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Messaging;

use App\Administration\Domain\Event\PasswordResetTokenGenerated;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Mime\Email;
use Twig\Environment;

/**
 * Sends a password reset email when a reset token is generated.
 *
 * This handler listens for PasswordResetTokenGenerated events and sends
 * an email to the user with a link to reset their password.
 */
#[AsMessageHandler(bus: 'event.bus')]
final readonly class SendPasswordResetEmailHandler
{
    public function __construct(
        private MailerInterface $mailer,
        private Environment $twig,
        private string $appUrl,
        private string $fromEmail = 'noreply@classeo.fr',
    ) {
    }

    public function __invoke(PasswordResetTokenGenerated $event): void
    {
        $resetUrl = rtrim($this->appUrl, '/') . '/reset-password/' . $event->tokenValue;

        $html = $this->twig->render('emails/password_reset.html.twig', [
            'email' => $event->email,
            'resetUrl' => $resetUrl,
        ]);

        $email = (new Email())
            ->from($this->fromEmail)
            ->to($event->email)
            ->subject('Réinitialisation de votre mot de passe Classeo')
            ->html($html);

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