<?php

namespace AutoAdmin\Bundle\Cache\EventListener;

use AutoAdmin\Bundle\Admin\Entity\Administrator;
use AutoAdmin\Bundle\Cache\Service\CacheService;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\Security\Core\Security;

class CachableEventListener
{
    private CacheService $service;
    private Security $security;

    private bool $isCachable = false;
    private bool $isCached = false;

    public function __construct(CacheService $service, Security $security)
    {
        $this->service = $service;
        $this->security = $security;
    }

    public function onKernelRequest(RequestEvent $event)
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $user = $this->security->getUser();
        if ($user instanceof Administrator) {
            return;
        }

        $request = $event->getRequest();

        $this->isCachable = $this->service->isCachable($request);
        $this->isCached = $this->service->isCached($request);

        if ($this->isCachable && $this->isCached) {
            $response = $this->service->getCached($request);
            $event->setResponse($response);
        }
    }

    public function onKernelResponse(ResponseEvent $event)
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $user = $this->security->getUser();
        if ($user instanceof Administrator) {
            return;
        }

        if ($this->isCachable && !$this->isCached) {
            $response = $event->getResponse();
            $request = $event->getRequest();
            $this->service->setCached($request, $response);
        }
    }
}
