<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Messaging;

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

/**
 * Envoie un email d'alerte quand un compte est bloqué temporairement.
 *
 * @see Story 1.4 - T4: Email alerte lockout
 */
#[AsMessageHandler(bus: 'event.bus')]
final readonly class SendLockoutAlertHandler
{
    public function __construct(
        private MailerInterface $mailer,
        private Environment $twig,
        private string $fromEmail = 'noreply@classeo.fr',
    ) {
    }

    public function __invoke(CompteBloqueTemporairement $event): void
    {
        $blockedForMinutes = (int) ceil($event->blockedForSeconds / 60);

        $htmlContent = $this->twig->render('email/lockout_alert.html.twig', [
            'email' => $event->email,
            'ipAddress' => $event->ipAddress,
            'failedAttempts' => $event->failedAttempts,
            'blockedForMinutes' => $blockedForMinutes,
            'occurredOn' => $event->occurredOn,
        ]);

        $textContent = $this->twig->render('email/lockout_alert.txt.twig', [
            'email' => $event->email,
            'ipAddress' => $event->ipAddress,
            'failedAttempts' => $event->failedAttempts,
            'blockedForMinutes' => $blockedForMinutes,
            'occurredOn' => $event->occurredOn,
        ]);

        $email = (new Email())
            ->from($this->fromEmail)
            ->to($event->email)
            ->subject('🔒 Alerte de sécurité - Tentatives de connexion suspectes')
            ->html($htmlContent)
            ->text($textContent)
            ->priority(Email::PRIORITY_HIGH);

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