<?php declare(strict_types=1);

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

use Exception;
use GuzzleHttp\Client;
use Neos\Flow\Annotations as Flow;
use Psr\Http\Message\ResponseInterface;

class CloudflareClient
{
    /**
     * @var array
     * @Flow\InjectConfiguration(path="cache.cloudflare")
     */
    protected $configuration;

    public function purgeEverything(): ResponseInterface
    {
        return $this->purge([ 'purge_everything' => true ]);
    }

    public function purgeFiles(array $files): ResponseInterface
    {
        return $this->purge([ 'files' => $files ]);
    }

    public function purgePrefixes(array $prefixes): ResponseInterface
    {
        return $this->purge([ 'prefix' => $prefixes ]);
    }

    private function purge(array $options = []): ResponseInterface
    {
        return $this->getClient()
            ->post('purge_cache', [
                'json' => $options,
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $this->getRequiredConfigurationValue('apiToken'),
                ],
            ]);
    }

    private function getClient(): Client
    {
        return new Client([
            'base_uri' => sprintf(
                'https://api.cloudflare.com/client/v4/zones/%s/',
                $this->getRequiredConfigurationValue('zoneId')
            ),
        ]);
    }

    private function getRequiredConfigurationValue(string $key): string
    {
        $value = $this->configuration[$key] ?? null;

        if ($value === null) {
            throw new Exception(sprintf('"%s" is not set in configuration.', $key));
        }

        return $value;
    }
}
