<?php

namespace KupShop\ResponseCacheBundle\Util\Cache;

use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\HttpFoundation\Response;

class ResponseCache
{
    /** @var AdapterInterface */
    private $cache;

    public function __construct(AdapterInterface $cache)
    {
        $this->cache = $cache;
    }

    public function wrap(callable $responseCallback, string $key, int $ttl = 300, ?array $tags = null, bool &$isHit = false): Response
    {
        $cacheResponse = $this->cache->getItem($key);

        if ($cacheResponse->isHit()) {
            /** @var $response Response */
            $response = new Response($cacheResponse->get());
            $response->headers->addCacheControlDirective('must-revalidate', true);
            $response->headers->addCacheControlDirective('no-store', true);
            $response->headers->set('X-Cache', $key.': hit');
            $isHit = true;
        } else {
            /** @var $response Response */
            $response = $responseCallback();
            if ($response->getStatusCode() == 200) {
                $cacheResponse->expiresAfter($ttl);
                if (isset($tags)) {
                    $cacheResponse->tag($tags);
                }
                $cacheResponse->set($response->getContent());
                $this->cache->save($cacheResponse);
                $response->headers->set('X-Cache', $key.': store');
            }
        }

        return $response;
    }
}
