<?php

declare(strict_types=1);

namespace KupShop\SynchronizationBundle\EventSubscriber;

use KupShop\SynchronizationBundle\Util\SynchronizationJobProvider;
use KupShop\SynchronizationBundle\Util\SynchronizationQueueUtil;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Scheduler\Event\FailureEvent;
use Symfony\Component\Scheduler\Event\PostRunEvent;
use Symfony\Component\Scheduler\Event\PreRunEvent;
use Symfony\Contracts\Service\Attribute\Required;

class SynchronizationEventSubscriber implements EventSubscriberInterface
{
    protected SynchronizationJobProvider $jobProvider;
    protected SynchronizationQueueUtil $queueUtil;

    public static function getSubscribedEvents(): array
    {
        return [
            PreRunEvent::class => [
                ['handleEvent', 200],
            ],
            PostRunEvent::class => [
                ['handleEvent', 200],
            ],
            FailureEvent::class => [
                ['handleEvent', 200],
            ],
        ];
    }

    public function handleEvent($event): void
    {
        $message = '';
        $status = SynchronizationQueueUtil::STATUS_RUNNING;

        if ($event instanceof PostRunEvent) {
            $status = SynchronizationQueueUtil::STATUS_SUCCESS;
        } elseif ($event instanceof FailureEvent) {
            // Do not log failed "System::eventWatchdog" - failed job triggered by watchdog will log itself
            if ($event->getMessage()->jobId === '3402e8083939bdc19b4ff83cc9402dd8') {
                return;
            }
            $status = SynchronizationQueueUtil::STATUS_FAILED;
            $message = $event->getError()->getMessage();
        }

        $this->queueUtil->setJobStatus($event->getMessage()->jobId, $status, $message);
    }

    #[Required]
    public function setJobProvider(SynchronizationJobProvider $jobProvider): void
    {
        $this->jobProvider = $jobProvider;
    }

    #[Required]
    public function setQueueUtil(SynchronizationQueueUtil $queueUtil): void
    {
        $this->queueUtil = $queueUtil;
    }
}
