<?php

namespace KupShop\KupShopBundle\EventListener;

use KupShop\KupShopBundle\Attribute\EnableCache;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
use Symfony\Component\HttpKernel\KernelEvents;

class CacheListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::CONTROLLER_ARGUMENTS => [
                ['processCachingAttribute', 110],
            ],
            KernelEvents::RESPONSE => [
                ['setNoAutoCacheControl', -100],
            ],
        ];
    }

    public function processCachingAttribute(ControllerArgumentsEvent $event): void
    {
        if (!\is_array($event->getAttributes()[EnableCache::class] ?? null)) {
            return;
        }

        $event->getRequest()->attributes->set('_enablecache', true);
    }

    public function setNoAutoCacheControl(ResponseEvent $event)
    {
        if ($event->getRequest()->attributes->has('_enablecache') && $event->getResponse()->isCacheable()) {
            $event->getResponse()->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, true);
        }
    }
}
