<?php

namespace Tests\Tenant\Services;

use App\Services\CloudflareService;
use Illuminate\Support\Facades\Http;
use Mtc\MercuryDataModels\Tenant;
use Tests\TenantTestCase;

class CloudflareServiceTest extends TenantTestCase
{
    public function testClearCacheSendsCorrectRequest()
    {
        $tenant = new Tenant();
        $tenant->cloudflare_data = [
            'zone_id' => 'example-zone-id',
        ];

        Http::fake([
            'https://api.cloudflare.com/client/v4/zones/example-zone-id/purge_cache' => Http::response(['success' => true], 200),
        ]);

        $service = new CloudflareService();

        $response = $service->clear($tenant);

        $this->assertTrue($response->successful());

        Http::assertSent(fn ($request) => $request->url() === 'https://api.cloudflare.com/client/v4/zones/example-zone-id/purge_cache' &&
                $request->method() === 'POST' &&
                $request->hasHeader('Content-Type', 'application/json') &&
                $request->hasHeader('X-Auth-Email', config('services.cloudflare.email')) &&
                $request->hasHeader('X-Auth-Key', config('services.cloudflare.api_key')) &&
                $request['purge_everything'] === true);
    }

    public function testCacheEndpointReturnsCorrectUrl()
    {
        $service = new CloudflareService();

        $zoneId = 'example-zone-id';
        $expectedUrl = "https://api.cloudflare.com/client/v4/zones/$zoneId/purge_cache";

        $this->assertEquals($expectedUrl, $this->invokeMethod($service, 'cacheEndpoint', [$zoneId]));
    }

    protected function invokeMethod(object $object, string $methodName, array $parameters = [])
    {
        $reflection = new \ReflectionClass($object);
        $method = $reflection->getMethod($methodName);

        return $method->invokeArgs($object, $parameters);
    }
}
