<?php

namespace KupShop\MessengerBundle\Handler;

use KupShop\KupShopBundle\Util\Logging\SentryLogger;
use KupShop\MessengerBundle\Message\AsyncMessage;
use Psr\Log\LoggerInterface;

class FinalAsyncHandler
{
    /** @var SentryLogger */
    private $sentryLogger;

    /** @var LoggerInterface */
    private $logger;

    private $isLast = false;

    public function __invoke(AsyncMessage $message)
    {
        $result = [];

        $res = false;
        try {
            $res = $message->handle();
        } catch (\Throwable $e) {
            $this->sentryLogger->captureException($e);
            $result['error'] = $e->getMessage();
        }
        $result['status'] = $res;

        if (!$res) { // handle failed
            // pokud je to posledni pokus odeslani
            if ($this->isLast) {
                // capture to sentry
                $this->sentryLogger->captureMessage('Failure in AsyncMessage processing!', [], ['extra' => $result]);
            } else {
                // log to kibana
                $this->logger->notice('Failure in AsyncMessage processing!', ['data' => $result]);
            }
        }

        return $result;
    }

    public function setIsLast($isLast)
    {
        $this->isLast = $isLast;
    }

    /**
     * @required
     */
    public function setSentryLogger(SentryLogger $sentryLogger)
    {
        $this->sentryLogger = $sentryLogger;
    }

    /**
     * @required
     */
    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
}
