<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 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 CpCreation\VitiCore\Bridge\Symfony\Bundle\Messenger;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Notification\Command\NotificationCommand;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;
use Symfony\Component\Messenger\Stamp\HandledStamp;

final readonly class DeduplicateNotificationMiddleware implements MiddlewareInterface
{
    private const REQUEST_ATTRIBUTE = '_viti_core_dispatched_notifications';

    public function __construct(private RequestStack $requestStack)
    {
    }

    public function handle(Envelope $envelope, StackInterface $stack): Envelope
    {
        $message = $envelope->getMessage();

        if (!$message instanceof NotificationCommand) {
            return $stack->next()->handle($envelope, $stack);
        }

        $request = $this->requestStack->getMainRequest() ?? $this->requestStack->getCurrentRequest();
        if (null === $request) {
            return $stack->next()->handle($envelope, $stack);
        }

        $key = implode("\0", [
            $message->message,
            $message->channel->value,
            $message->target->value,
            $message->level->value,
            $message->transport->value,
            $message->type->value,
            $message->template ?? '',
        ]);

        $dispatchedNotifications = $request->attributes->get(self::REQUEST_ATTRIBUTE, []);
        if (!\is_array($dispatchedNotifications)) {
            $dispatchedNotifications = [];
        }

        if (isset($dispatchedNotifications[$key])) {
            return $envelope->with(new HandledStamp(null, self::class));
        }

        $dispatchedNotifications[$key] = true;
        $request->attributes->set(self::REQUEST_ATTRIBUTE, $dispatchedNotifications);

        return $stack->next()->handle($envelope, $stack);
    }
}
