<?php

namespace KupShop\MessengerBundle\Util;

use KupShop\MessengerBundle\Exception\MessageFailureException;
use KupShop\MessengerBundle\Handler\FinalAsyncHandler;
use KupShop\MessengerBundle\Handler\FinalEmailHandler;
use KupShop\MessengerBundle\Message\AsyncMessage;
use KupShop\MessengerBundle\Message\EmailMessage;

class MessengerUtil
{
    public function __construct(
        private FinalEmailHandler $finalEmailHandler,
        private FinalAsyncHandler $finalAsyncHandler,
    ) {
    }

    public function handleMessage($message, bool $isLast): array
    {
        $handler = null;
        if ($message instanceof EmailMessage) {
            $handler = $this->finalEmailHandler;
        } elseif ($message instanceof AsyncMessage) {
            $handler = $this->finalAsyncHandler;
        }

        if (!$handler) {
            throw new MessageFailureException('There is no handler to handle message!');
        }

        $handler->setIsLast($isLast);

        return $handler($message);
    }
}
