<?php

namespace App\EventSubscriber;

use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\Order;
use App\Helper\Hiltes;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class ExportHiltesSubscriber implements EventSubscriberInterface
{
    public function __construct(private Hiltes $hiltes)
    {
    }

    /**
     * @param ViewEvent $event
     * @return void
     */
    public function onPatchOrder(ViewEvent $event): void
    {
        $method = $event->getRequest()->getMethod();
        $order = $event->getControllerResult();

        if (!$order instanceof Order || Request::METHOD_PATCH !== $method) {
            return;
        }

        if ($order->getStatus() == 2) {
            $this->hiltes->createRequest($order);
        }
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => ['onPatchOrder', EventPriorities::POST_WRITE]
        ];
    }
}