<?php

namespace App\Base\Service;

use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
use Symfony\Component\Notifier\Notification\Notification;
use Symfony\Component\Notifier\NotifierInterface;
use Twig\Environment;

readonly class Broadcaster
{
    public function __construct(
        #[Autowire(param: 'notification.transport')]
        private string $notificationTransport,
        #[Autowire(service: 'twig')]
        private Environment $renderer,
        private HubInterface $hub,
        private RequestStack $requestStack,
        private NotifierInterface $notifier,
        private LoggerInterface $logger,
    ) {}

    public function alert(string $title, string $message, string $type = "success", bool $sendPush = false, ?string $mercureAlertTopic = null): void
    {
        try {
            $userAlertTopic = $mercureAlertTopic ?? $this->requestStack->getCurrentRequest()->getSession()->get('mercure_alert_topic');
            $update = new Update(
                $userAlertTopic,
                $this->renderer->render('broadcast/Alert.stream.html.twig', [
                    'alert_id' => uniqid(),
                    'title' => $title,
                    'message' => $message,
                    'type' => $type,
                ])
            );
            $this->hub->publish($update);
        } catch (\Throwable $exception) {
            $this->logger->error('Unable to publish alert: ' . $exception->getMessage());
        }

        if (true === $sendPush && in_array($this->notificationTransport, ['ntfy'])) {
            try {
                $notification = new Notification($title, ['push'])->content($message);
                $this->notifier->send($notification);
            } catch (\Throwable $exception) {
                $this->logger->error('Unable to send push notification: ' . $exception->getMessage());
            }
        }
    }
}
