<?php

namespace App\Services;

use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Mtc\MercuryDataModels\Tenant;

class CloudflareService
{
    public function clear(Tenant $site): Response
    {
        return Http::withHeaders([
            'Content-Type' => 'application/json',
            'X-Auth-Email' => !empty($site->cloudflare_data['email'])
                ? $site->cloudflare_data['email']
                : config('services.cloudflare.email'),
            'X-Auth-Key' =>  !empty($site->cloudflare_data['key'])
                ? $site->cloudflare_data['key']
                : config('services.cloudflare.api_key'),
        ])
            ->post(
                $this->cacheEndpoint($site->cloudflare_data['zone_id']),
                [ 'purge_everything' => true ],
            );
    }

    private function cacheEndpoint(?string $zone_id): string
    {
        return "https://api.cloudflare.com/client/v4/zones/$zone_id/purge_cache";
    }
}
