<?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\Notification\Command;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Messenger\Messaging\CommandHandlerInterface;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Notification\Enum\PushType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Notification\Notifier\NotifierInterface;
use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
final readonly class NotificationCommandHandler implements CommandHandlerInterface
{
    /**
     * @param iterable<NotifierInterface> $notifiers
     */
    public function __construct(
        #[AutowireIterator('viticore.push_notifier')]
        private iterable $notifiers,
    ) {
    }

    public function __invoke(NotificationCommand $command): void
    {
        $template = $command->template ?? $this->defaultTemplate($command->type);
        foreach ($this->notifiers as $notifier) {
            $supports = $notifier::supports();
            if (null === $supports || $supports !== $command->transport) {
                continue;
            }

            $notifier->push(
                message: $command->message,
                channel: $command->channel,
                target: $command->target,
                level: $command->level,
                transport: $command->transport,
                type: $command->type,
                template: $template,
            );

            return;
        }

        throw new \InvalidArgumentException(\sprintf('No notifier supports push transport "%s".', $command->transport->value));
    }

    private function defaultTemplate(PushType $type): string
    {
        return \sprintf('@stream/notifier/alert/%s.stream.html.twig', $type->value);
    }
}
