<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Service\Cache\Cloadflare;

use Newland\Toubiz\Sync\Neos\Service\Cache\CacheServiceInterface;
use Neos\Flow\Annotations as Flow;

class CacheService implements CacheServiceInterface
{
    /**
     * @var CloudflareClient
     * @Flow\Inject()
     */
    protected $client;

    public function flushGlobalCache(): void
    {
        $this->client->purgeEverything();
    }

    public function flushUri(string $uri): void
    {
        $response = $this->client->purgeFiles([ $uri ]);
        $content = json_decode($response->getBody()->getContents(), true);

        if ($response->getStatusCode() !== 200) {
            throw new \Exception(
                sprintf('Failed to flush uri: "%s". Server response: %s', $uri, $response->getBody()->getContents()),
                $response->getStatusCode()
            );
        }

        if ($content['success'] !== true) {
            throw new \Exception(
                sprintf('Failed to flush uri: "%s". Server response: %s', $uri, json_encode($content['errors']))
            );
        }
    }
}
