<?php

namespace KupShop\KupShopBundle\EventListener;

use KupShop\AdminBundle\Controller\AdminController;
use KupShop\CatalogBundle\Controller\ImageController;
use KupShop\FeedsBundle\Controller\FeedController;
use KupShop\KupShopBundle\Util\RequestUtil;
use KupShop\MetricsBundle\Controller\PrometheusController;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Contracts\Service\Attribute\Required;

class BlackfireRequestSubscriber implements EventSubscriberInterface
{
    public const DISABLED_CONTROLLERS = [
        ImageController::class,
        FeedController::class,
        AdminController::class,
        PrometheusController::class,
    ];

    #[Required]
    public RequestUtil $requestUtil;

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::CONTROLLER => [
                ['requestController', -10000],
            ],
        ];
    }

    public function requestController(ControllerEvent $event): void
    {
        $controller = $this->requestUtil->getControllerFromEvent($event);

        $this->requestUtil->addTransactionInfo($event->getRequest(), [
            'controller' => str_replace('\\', '/', $controller[0]),
            'action' => $controller[1],
        ]);

        if (!class_exists(\BlackfireProbe::class)) {
            return;
        }

        $userAgent = $event->getRequest()->headers->get('User-Agent');
        if (str_starts_with($userAgent, 'kube-probe')) {
            //            \BlackfireProbe::ignoreTransaction();

            return;
        }

        if (in_array($controller[0], self::DISABLED_CONTROLLERS)) {
            //            \BlackfireProbe::ignoreTransaction();
        }
    }
}
