<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\CoreBundle\Notification\Notifier;

use Serenity\CoreBundle\Notification\Enum\PushChannel;
use Serenity\CoreBundle\Notification\Enum\PushLevel;
use Serenity\CoreBundle\Notification\Enum\PushTarget;
use Serenity\CoreBundle\Notification\Enum\PushTransport;
use Serenity\CoreBundle\Notification\Enum\PushType;
use Serenity\CoreBundle\Notification\MercureNotification;
use Serenity\CoreBundle\Notification\Notifier\NotifierInterface as CoreNotifierInterface;
use Serenity\CoreBundle\Shared\Mercure\ChannelGenerator;
use Symfony\Component\Notifier\NotifierInterface;
use Twig\Environment;

final readonly class MercureNotifier implements CoreNotifierInterface
{
    public function __construct(
        private NotifierInterface $notifier,
        private Environment $twig,
    ) {
    }

    public function push(string $message, PushChannel $channel, PushTarget $target, PushLevel $level, PushTransport $transport, PushType $type, ?string $template = null): void
    {
        $topic = [];
        if (PushTarget::USER === $target) {
            $topic = ChannelGenerator::privateUserIdTopic($channel->value);
        }
        if (PushTarget::WINDOW === $target) {
            $topic = ChannelGenerator::privateWindowIdTopic($channel->value);
        }
        if (PushTarget::SESSION === $target) {
            $topic = ChannelGenerator::privateSessionTopic($channel->value);
        }

        $content = $message;

        if ($template) {
            $content = $this->twig->render(
                $template,
                ['level' => $level->value, 'message' => $message]
            );
        }

        $this->notifier->send(
            (new MercureNotification($topic))->content($content)
        );
    }

    public static function supports(): PushTransport
    {
        return PushTransport::MERCURE;
    }
}
