<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Messaging;

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

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

    public function __invoke(MotDePasseChange $event): void
    {
        $html = $this->twig->render('emails/password_reset_confirmation.html.twig', [
            'email' => $event->email,
            'changedAt' => $event->occurredOn()->format('d/m/Y à H:i'),
            'loginUrl' => rtrim($this->appUrl, '/') . '/login',
        ]);

        $email = (new Email())
            ->from($this->fromEmail)
            ->to($event->email)
            ->subject('Votre mot de passe Classeo a été modifié')
            ->html($html);

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