<?php

namespace App\User\Framework\EventListener;

use App\Base\ConfigResolver;
use App\Base\Service\Broadcaster;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent;

final class LoginSuccessListener
{
    public function __construct(
        private readonly RequestStack $requestStack,
        private readonly ConfigResolver $configResolver,
        private readonly Broadcaster $broadcaster,
    ) {}

    #[AsEventListener(event: 'security.authentication.success', priority: 20)]
    public function setMercureTopics(AuthenticationSuccessEvent $event): void
    {
        // Set the unique Mercure topic name for the User's alerts
        $this->requestStack->getSession()->set('mercure_alert_topic', 'alerts_' . uniqid());
    }

    #[AsEventListener(event: 'security.authentication.success', priority: 10)]
    public function validateConfig(AuthenticationSuccessEvent $event): void
    {
        // Set the unique Mercure topic name for the User's alerts
        $valid = $this->configResolver->validate();
        if (false === $valid) {
            foreach ($this->configResolver->getMessages() as $message) {
                $this->requestStack->getSession()->getFlashBag()->add('warning', $message);
            }
        }
    }
}
