<?php

declare(strict_types=1);

use App\Services\Cdn\ArtworkCdnPurgeService;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

uses(TestCase::class);

it('purges canonical artwork urls through the Cloudflare api', function (): void {
    Http::fake([
        'https://api.cloudflare.com/client/v4/zones/test-zone/purge_cache' => Http::response(['success' => true], 200),
    ]);

    config()->set('cdn.files_url', 'https://cdn.skinbase.org');
    config()->set('cdn.cloudflare.zone_id', 'test-zone');
    config()->set('cdn.cloudflare.api_token', 'test-token');

    $result = app(ArtworkCdnPurgeService::class)->purgeArtworkObjectPaths([
        'artworks/sq/61/83/6183c98975512ee6bff4657043067953a33769c7.webp',
    ], ['reason' => 'test']);

    expect($result)->toBeTrue();

    Http::assertSent(function ($request): bool {
        return $request->url() === 'https://api.cloudflare.com/client/v4/zones/test-zone/purge_cache'
            && $request->hasHeader('Authorization', 'Bearer test-token')
            && $request['files'] === [
                'https://cdn.skinbase.org/artworks/sq/61/83/6183c98975512ee6bff4657043067953a33769c7.webp',
            ];
    });
});

it('falls back to the legacy purge webhook when Cloudflare credentials are absent', function (): void {
    Http::fake([
        'https://purge.internal.example/purge' => Http::response(['ok' => true], 200),
    ]);

    config()->set('cdn.files_url', 'https://cdn.skinbase.org');
    config()->set('cdn.cloudflare.zone_id', null);
    config()->set('cdn.cloudflare.api_token', null);
    config()->set('cdn.purge_url', 'https://purge.internal.example/purge');

    $result = app(ArtworkCdnPurgeService::class)->purgeArtworkObjectPaths([
        'artworks/sq/61/83/6183c98975512ee6bff4657043067953a33769c7.webp',
    ], ['reason' => 'test']);

    expect($result)->toBeTrue();

    Http::assertSent(function ($request): bool {
        return $request->url() === 'https://purge.internal.example/purge'
            && $request['paths'] === [
                '/artworks/sq/61/83/6183c98975512ee6bff4657043067953a33769c7.webp',
            ];
    });
});