<?php

namespace App\Tech\EventListener;

use App\Tech\Entity\EmailLog;
use App\Tech\Entity\User;
use App\Tech\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mime\Address;

#[AsEventListener(event: MessageEvent::class, method: 'onMessage')]
class EmailLoggerListener
{
    public function __construct(
        private EntityManagerInterface $entityManager,
        private UserRepository $userRepository
    ) {
    }

    public function onMessage(MessageEvent $event): void
    {
        $message = $event->getMessage();
        if (!$message instanceof TemplatedEmail) {
            return;
        }

        $recipients = $message->getTo();
        foreach ($recipients as $recipient) {
            if (!$recipient instanceof Address) {
                continue;
            }

            $user = $this->userRepository->findOneBy(['email' => $recipient->getAddress()]);
            if (!$user) {
                continue;
            }

            $emailLog = new EmailLog();
            $emailLog->setUser($user);
            $emailLog->setSentAt(new \DateTimeImmutable());

            // Try to get the template name, or use the subject as identifier
            $identifier = $message->getHtmlTemplate() ?: $message->getTextTemplate() ?: $message->getSubject();
            $emailLog->setEmailIdentifier($identifier);

            $this->entityManager->persist($emailLog);
        }

        $this->entityManager->flush();
    }
}
