<?php

namespace Tests\Feature;

use App\Models\ApiCall;
use App\Models\User;
use App\Services\Meta\GraphApi;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use App\Services\Platforms\Support\CallContext;
use App\Services\Platforms\Support\CallLogger;
use App\Services\Platforms\Support\Guardrails;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Sleep;
use PHPUnit\Framework\Attributes\TestWith;
use Tests\TestCase;

/**
 * The hourly call budget, which exists so other systems on the same token keep
 * their share.
 *
 * Two holes in it. It was asserted once before the retry loop, though every
 * retry is a real call that writes its own row, so a throttled burst could take
 * the budget past its limit while the check that prevents exactly that had
 * already passed. And it returned early for any call that named no ad account,
 * which is the two edges that sweep everything the token can see.
 */
class GuardrailBudgetTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        config([
            'cache.default' => 'array',
            'platforms.guardrails.allowed_ad_accounts' => ['act_777'],
            'platforms.guardrails.max_calls_per_hour' => 3,
            'platforms.guardrails.retry_backoff_ms' => 0,
            'platforms.meta.mcp.enabled' => false,
            'platforms.meta.token' => 'test-token',
        ]);

        $this->actingAs(User::factory()->create());
        Cache::flush();
    }

    private function api(string $token = 'test-token', string $version = 'v23.0'): GraphApi
    {
        return new GraphApi($token, $version, new CallLogger(app(Guardrails::class)));
    }

    public function test_campaign_reads_preserve_spend_caps_special_categories_and_fresh_readback(): void
    {
        Http::preventStrayRequests();
        Http::fake(['graph.facebook.com/*/990*' => Http::sequence()
            ->push(['id' => '990', 'spend_cap' => '10000', 'special_ad_categories' => ['HOUSING']])
            ->push(['id' => '990', 'spend_cap' => '20000', 'special_ad_categories' => ['HOUSING']])]);

        $api = $this->api();
        $this->assertSame('10000', $api->campaign('990', 'act_777')['spend_cap']);
        $fresh = $api->campaign('990', 'act_777', fresh: true);
        $this->assertSame('20000', $fresh['spend_cap']);
        $this->assertSame(['HOUSING'], $fresh['special_ad_categories']);
        Http::assertSentCount(2);
        Http::assertSent(fn (Request $request): bool => str_contains($request['fields'], 'spend_cap')
            && str_contains($request['fields'], 'special_ad_categories'));
    }

    #[TestWith([false])]
    #[TestWith([true])]
    public function test_pixels_follow_account_and_business_pagination_and_cache_every_page(bool $fresh): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        Http::preventStrayRequests();
        Http::fake([
            'graph.facebook.com/*/act_777/adspixels*' => Http::sequence()
                ->push(['data' => [['id' => '1']], 'paging' => ['cursors' => ['after' => 'account-next'], 'next' => 'next-page']])
                ->push(['data' => [['id' => '2']], 'paging' => ['cursors' => ['after' => 'account-end']]]),
            'graph.facebook.com/*/888/owned_pixels*' => Http::sequence()
                ->push(['data' => [['id' => '2']], 'paging' => ['cursors' => ['after' => 'business-next'], 'next' => 'next-page']])
                ->push(['data' => [['id' => '3']]]),
            'graph.facebook.com/*/act_777?*' => Http::response(['id' => 'act_777', 'business' => ['id' => '888']]),
        ]);

        $pixels = $this->api()->pixels('act_777', fresh: $fresh);

        $this->assertSame(['1', '2', '3'], array_column($pixels, 'id'));
        $this->assertSame(['ad account', 'ad account', 'business'], array_column($pixels, 'owned_by'));
        Http::assertSentCount(5);
        Http::assertSent(fn (Request $request): bool => ($request['after'] ?? null) === 'account-next');
        Http::assertSent(fn (Request $request): bool => ($request['after'] ?? null) === 'business-next');

        if (! $fresh) {
            $this->assertSame($pixels, $this->api()->pixels('act_777'));
            Http::assertSentCount(6);
        }
    }

    public function test_pixel_pagination_refuses_a_repeated_cursor_instead_of_returning_a_partial_list(): void
    {
        Http::preventStrayRequests();
        Http::fake(['graph.facebook.com/*/act_777/adspixels*' => Http::response([
            'data' => [['id' => '1']],
            'paging' => ['cursors' => ['after' => 'repeated'], 'next' => 'next-page'],
        ])]);

        $this->expectException(MetaException::class);
        $this->expectExceptionMessage('pagination repeated a cursor');

        $this->api()->pixels('act_777', fresh: true);
    }

    #[TestWith([false])]
    #[TestWith([true])]
    public function test_incomplete_pixel_pagination_is_reported_explicitly(bool $missingCursor): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        Http::preventStrayRequests();
        $page = 0;
        Http::fake(['graph.facebook.com/*/act_777/adspixels*' => function () use (&$page, $missingCursor) {
            $page++;

            return Http::response([
                'data' => [['id' => (string) $page]],
                'paging' => [
                    'next' => 'next-page',
                    'cursors' => $missingCursor ? [] : ['after' => 'page-'.$page],
                ],
            ]);
        }]);

        try {
            $this->api()->pixels('act_777', fresh: true);
            $this->fail('Incomplete pixel discovery must not return success.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString($missingCursor ? 'missing its next cursor' : 'exceeded its page limit', $exception->getMessage());
        }
        Http::assertSentCount($missingCursor ? 1 : 20);
    }

    private function fakeResourceDiscovery(): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        Http::preventStrayRequests();
        Http::fake([
            'graph.facebook.com/*/act_*/adspixels*' => Http::response(['data' => [['id' => '900', 'name' => 'Pixel']]]),
            'graph.facebook.com/*/act_*/customaudiences*' => Http::response(['data' => [['id' => '700', 'name' => 'Visitors']]]),
            'graph.facebook.com/*/act_*' => Http::response(['id' => 'act_777']),
        ]);
    }

    /** @return array{CallContext, string} */
    private function discoveryLockFixture(string $store): array
    {
        config([
            'cache.default' => $store,
            'cache.stores.database.connection' => 'sqlite',
            'cache.stores.database.lock_connection' => 'sqlite',
            'cache.stores.database.lock_table' => 'cache_locks',
        ]);
        $context = new CallContext(
            transport: 'graph', method: 'GET', endpoint: 'me/accounts',
            credentialScope: 'test-scope', cacheSeconds: 300,
        );
        $memo = 'meta|graph|GET|me/accounts||test-scope|'.md5('[]');

        return [$context, 'platform-discovery:'.hash('sha256', $memo).':lock'];
    }

    #[TestWith(['array'])]
    #[TestWith(['database'])]
    public function test_a_waiting_discovery_miss_rechecks_the_cache_instead_of_sending_a_duplicate(string $store): void
    {
        [$context, $key] = $this->discoveryLockFixture($store);
        $inFlight = Cache::lock($key, 240);
        $this->assertTrue($inFlight->get());
        $result = ['data' => [['id' => '123', 'name' => 'Page']]];
        Sleep::fake(syncWithCarbon: true);
        Sleep::whenFakingSleep(function () use ($context, $inFlight, $result): void {
            config(['platforms.meta.discovery_coalescing' => false]);

            try {
                $this->assertSame($result, (new CallLogger(app(Guardrails::class)))->record($context, fn (): array => $result));
            } finally {
                config(['platforms.meta.discovery_coalescing' => true]);
                $inFlight->release();
            }
        });

        try {
            $actual = (new CallLogger(app(Guardrails::class)))->record($context, function (): array {
                $this->fail('A waiting cache miss must not send a duplicate provider call.');
            });

            $this->assertSame($result, $actual);
            $this->assertSame(1, ApiCall::count());
            Sleep::assertSleptTimes(1);
            $this->assertFalse(Cache::lock($key, 240)->isLocked());
        } finally {
            Sleep::fake(false);
            $inFlight->release();
        }
    }

    #[TestWith(['array'])]
    #[TestWith(['database'])]
    public function test_discovery_lock_wait_is_bounded_and_sends_no_request_on_timeout(string $store): void
    {
        [$context, $key] = $this->discoveryLockFixture($store);
        $inFlight = Cache::lock($key, 240);
        $this->assertTrue($inFlight->get());
        Sleep::fake(syncWithCarbon: true);
        $started = now();

        try {
            (new CallLogger(app(Guardrails::class)))->record($context, function (): array {
                $this->fail('A lock timeout must not send a provider call.');
            });
            $this->fail('Expected an explicit discovery-busy error.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString('No duplicate request was sent', $exception->getMessage());
            $this->assertSame(0, ApiCall::count());
            $this->assertLessThanOrEqual(5, $started->diffInSeconds(now()));
            $this->assertTrue($inFlight->isOwnedByCurrentProcess());
        } finally {
            Sleep::fake(false);
            $inFlight->release();
        }
    }

    #[TestWith(['array'])]
    #[TestWith(['database'])]
    public function test_a_failed_discovery_releases_its_lock_and_is_not_cached(string $store): void
    {
        [$context, $key] = $this->discoveryLockFixture($store);
        $logger = new CallLogger(app(Guardrails::class));

        try {
            $logger->record($context, fn (): array => throw new MetaException('Permission denied', 200));
            $this->fail('Expected the provider permission failure.');
        } catch (MetaException $exception) {
            $this->assertSame('Permission denied', $exception->getMessage());
        }

        $this->assertFalse(Cache::lock($key, 240)->isLocked());
        $result = ['data' => []];
        $this->assertSame($result, $logger->record($context, fn (): array => $result));
        $this->assertSame(2, ApiCall::count());
    }

    #[TestWith(['array'])]
    #[TestWith(['database'])]
    public function test_discovery_coalescing_can_be_disabled_without_disabling_caching(string $store): void
    {
        [$context, $key] = $this->discoveryLockFixture($store);
        config(['platforms.meta.discovery_coalescing' => false]);
        $inFlight = Cache::lock($key, 240);
        $this->assertTrue($inFlight->get());
        $result = ['data' => []];

        try {
            $this->assertSame($result, (new CallLogger(app(Guardrails::class)))->record($context, fn (): array => $result));
            $this->assertSame($result, (new CallLogger(app(Guardrails::class)))->record($context, function (): array {
                $this->fail('Disabling coalescing must not disable the discovery cache.');
            }));
            $this->assertSame(1, ApiCall::count());
        } finally {
            $inFlight->release();
        }
    }

    public function test_usage_headers_are_logged_as_numeric_telemetry_without_changing_the_response(): void
    {
        Log::spy();
        Http::preventStrayRequests();
        Http::fake(['*/me/accounts*' => Http::response(['data' => [['id' => '123']]], 200, [
            'X-App-Usage' => '{"call_count":80,"total_time":20,"access_token":"do-not-log"}',
            'X-Ad-Account-Usage' => '{"acc_id_util_pct":95,"reset_time_duration":60}',
            'X-Business-Use-Case-Usage' => '{"777":[{"type":"ads_management","call_count":90,"estimated_time_to_regain_access":5,"token":"private"}]}',
            'Retry-After' => '120',
        ])]);

        $this->assertSame([['id' => '123']], $this->api()->pages());
        $this->api()->pages();
        Http::assertSentCount(1);
        Log::shouldHaveReceived('info')->once()->with('Meta Graph quota usage', \Mockery::on(
            fn (array $context): bool => $context['usage']['x-app-usage']['call_count'] === 80.0
                && $context['usage']['x-ad-account-usage']['acc_id_util_pct'] === 95.0
                && $context['usage']['x-business-use-case-usage'][777][0]['estimated_time_to_regain_access'] === 5.0
                && $context['usage']['retry_after_seconds'] === 120
                && ! str_contains(json_encode($context), 'do-not-log')
                && ! str_contains(json_encode($context), 'private')
                && ! str_contains(json_encode($context), 'test-token'),
        ));
    }

    public function test_quota_failure_retains_usage_and_recovery_hints_in_its_audit_diagnostics(): void
    {
        $this->freezeTime();
        Log::spy();
        Http::preventStrayRequests();
        Http::fake(['*/act_777*' => Http::response(['error' => ['code' => 80004, 'message' => 'Too many calls']], 400, [
            'X-Ad-Account-Usage' => '{"acc_id_util_pct":100}',
            'Retry-After' => now()->addMinutes(2)->toRfc7231String(),
        ])]);

        try {
            $this->api()->adAccount('act_777');
            $this->fail('Expected quota refusal.');
        } catch (MetaException $exception) {
            $this->assertSame(120, $exception->diagnostics()['meta_usage']['retry_after_seconds']);
        }

        $call = ApiCall::firstOrFail();
        $this->assertSame(400, $call->status);
        $this->assertEquals(100, data_get($call->response, '_error_diagnostics.meta_usage.x-ad-account-usage.acc_id_util_pct'));
        Http::assertSentCount(1);
    }

    public function test_malformed_usage_headers_do_not_break_a_successful_response_or_log_raw_contents(): void
    {
        Log::spy();
        Http::preventStrayRequests();
        Http::fake(['*/me/accounts*' => Http::response(['data' => []], 200, [
            'X-App-Usage' => 'invalid-secret',
            'Retry-After' => 'invalid-secret',
        ])]);

        $this->assertSame([], $this->api()->pages());
        Log::shouldHaveReceived('warning')->with('Meta usage header is invalid', [
            'header' => 'X-App-Usage', 'endpoint' => 'me/accounts',
        ])->once();
        Log::shouldHaveReceived('warning')->with('Meta recovery header is invalid', ['endpoint' => 'me/accounts'])->once();
        Log::shouldNotHaveReceived('info');
    }

    #[TestWith(['pixels'])]
    #[TestWith(['customAudiences'])]
    public function test_resource_discovery_is_shared_but_fresh_reads_bypass_both_caches(string $method): void
    {
        $this->fakeResourceDiscovery();
        $api = $this->api();
        $first = $api->{$method}('act_777');
        $this->assertSame($first, $this->api()->{$method}('act_777'));
        Http::assertSentCount($method === 'pixels' ? 3 : 1);

        $this->assertSame($first, $api->{$method}('act_777', fresh: true));
        Http::assertSentCount($method === 'pixels' ? 5 : 2);
        $this->assertSame($method === 'pixels' ? 5 : 2, ApiCall::count());
    }

    #[TestWith(['pixels'])]
    #[TestWith(['customAudiences'])]
    public function test_resource_discovery_expires_and_can_be_disabled(string $method): void
    {
        $this->fakeResourceDiscovery();
        config(['platforms.meta.discovery_cache.pixels_and_audiences' => 60]);
        $this->api()->{$method}('act_777');
        $this->travel(61)->seconds();
        $this->api()->{$method}('act_777');
        Http::assertSentCount($method === 'pixels' ? 4 : 2);

        config(['platforms.meta.discovery_cache.pixels_and_audiences' => 0]);
        $this->api()->{$method}('act_777');
        Http::assertSentCount($method === 'pixels' ? 6 : 3);
    }

    #[TestWith(['pixels'])]
    #[TestWith(['customAudiences'])]
    public function test_resource_discovery_is_isolated_by_credentials_version_and_account(string $method): void
    {
        $this->fakeResourceDiscovery();
        config(['platforms.guardrails.allowed_ad_accounts' => ['act_777', 'act_888']]);
        $this->api()->{$method}('act_777');
        $this->api('other-token')->{$method}('act_777');
        $this->api(version: 'v24.0')->{$method}('act_777');
        $this->api()->{$method}('act_888');
        Http::assertSentCount($method === 'pixels' ? 8 : 4);

        config(['platforms.guardrails.allowed_ad_accounts' => ['act_888']]);
        $this->expectException(MetaException::class);
        $this->api()->{$method}('act_777');
    }

    #[TestWith(['pixels', 'adspixels'])]
    #[TestWith(['customAudiences', 'customaudiences'])]
    public function test_resource_creation_invalidates_cached_lists_including_request_memory(string $method, string $edge): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        $items = [];
        Http::preventStrayRequests();
        Http::fake([
            'graph.facebook.com/*/act_777/'.$edge.'*' => function (Request $request) use (&$items) {
                if ($request->method() === 'POST') {
                    $items = [['id' => '901', 'name' => 'New item']];

                    return Http::response(['id' => '901']);
                }

                return Http::response(['data' => $items]);
            },
            'graph.facebook.com/*/act_777*' => Http::response(['id' => 'act_777']),
        ]);
        $api = $this->api();
        $this->assertSame([], $api->{$method}('act_777'));
        $this->assertSame([], $this->api()->{$method}('act_777'));

        if ($method === 'pixels') {
            $this->api()->createPixel('act_777', 'New item');
        } else {
            $this->api()->createWebsiteAudience('act_777', 'New item', '900', 'Purchase', 30);
        }

        $this->assertSame('901', $api->{$method}('act_777')[0]['id']);
        $this->assertSame('901', $this->api()->{$method}('act_777')[0]['id']);
    }

    #[TestWith(['update'])]
    #[TestWith(['delete'])]
    public function test_object_mutations_invalidate_pixel_and_audience_discovery(string $mutation): void
    {
        $this->fakeResourceDiscovery();
        Http::fake(['graph.facebook.com/*/901' => Http::response(['success' => true])]);
        $api = $this->api();
        $api->pixels('act_777');
        $api->customAudiences('act_777');

        if ($mutation === 'update') {
            $this->api()->updateEntity('901', ['name' => 'Renamed'], 'act_777');
        } else {
            $this->api()->delete('901');
        }

        $api->pixels('act_777');
        $api->customAudiences('act_777');
        Http::assertSentCount(6);
    }

    public function test_business_pixel_cache_is_still_checked_against_the_current_account_permission(): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        Http::preventStrayRequests();
        Http::fake([
            '*/adspixels*' => Http::response(['data' => [['id' => '900']]]),
            '*/owned_pixels*' => Http::response(['data' => [['id' => '901']]]),
            '*/act_777*' => Http::response(['id' => 'act_777', 'business' => ['id' => '999']]),
        ]);
        $first = $this->api()->pixels('act_777');
        $this->assertCount(2, $first);
        $this->assertSame($first, $this->api()->pixels('act_777'));
        Http::assertSentCount(4);

        config(['platforms.guardrails.allowed_ad_accounts' => ['act_888']]);
        $this->expectException(MetaException::class);
        $this->api()->pixels('act_777');
    }

    public function test_audience_pagination_is_cached_and_every_page_is_invalidated_after_creation(): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        Http::preventStrayRequests();
        Http::fake(['*/act_777/customaudiences*' => Http::sequence()
            ->push(['data' => [['id' => '700']], 'paging' => ['cursors' => ['after' => 'next']]])
            ->push(['data' => [['id' => '701']]])
            ->push(['id' => '702'])
            ->push(['data' => [['id' => '700']], 'paging' => ['cursors' => ['after' => 'next']]])
            ->push(['data' => [['id' => '701'], ['id' => '702']]])]);
        $api = $this->api();
        $this->assertCount(2, $api->customAudiences('act_777'));
        $this->assertCount(2, $this->api()->customAudiences('act_777'));
        Http::assertSentCount(2);

        $api->createWebsiteAudience('act_777', 'New audience', '900', 'Purchase', 30);
        $this->assertCount(3, $api->customAudiences('act_777'));
        $this->assertCount(3, $this->api()->customAudiences('act_777'));
        Http::assertSentCount(5);
    }

    #[TestWith(['pixels', 'adspixels'])]
    #[TestWith(['customAudiences', 'customaudiences'])]
    public function test_failed_resource_reads_are_not_cached_as_empty_lists(string $method, string $edge): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        Http::preventStrayRequests();
        Http::fake([
            '*/act_777/'.$edge.'*' => Http::sequence()
                ->push(['error' => ['message' => 'Permission denied', 'code' => 200]], 403)
                ->push(['data' => [['id' => '900']]]),
            '*/act_777*' => Http::response(['id' => 'act_777']),
        ]);
        try {
            $this->api()->{$method}('act_777');
            $this->fail('A refused read must remain an error.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString('Permission denied', $exception->getMessage());
        }

        $this->assertSame('900', $this->api()->{$method}('act_777')[0]['id']);
        Http::assertSentCount($method === 'pixels' ? 3 : 2);
    }

    public function test_an_in_flight_discovery_read_cannot_repopulate_the_namespace_invalidated_by_a_write(): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        $changed = false;
        Http::preventStrayRequests();
        Http::fake([
            '*/act_777/customaudiences*' => function (Request $request) use (&$changed) {
                if ($request->method() === 'POST') {
                    $changed = true;

                    return Http::response(['id' => '701']);
                }

                if (! $changed) {
                    $this->api()->createWebsiteAudience('act_777', 'New audience', '900', 'Purchase', 30);

                    return Http::response(['data' => [['id' => '700']]]);
                }

                return Http::response(['data' => [['id' => '700'], ['id' => '701']]]);
            },
        ]);
        $api = $this->api();
        $this->assertCount(1, $api->customAudiences('act_777'));
        $this->assertCount(2, $api->customAudiences('act_777'));
        $this->assertCount(2, $this->api()->customAudiences('act_777'));
        Http::assertSentCount(3);
    }

    #[TestWith(['pixels', 'adspixels'])]
    #[TestWith(['customAudiences', 'customaudiences'])]
    public function test_successful_empty_resource_lists_are_cached(string $method, string $edge): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        Http::preventStrayRequests();
        Http::fake([
            '*/act_777/'.$edge.'*' => Http::response(['data' => []]),
            '*/act_777*' => Http::response(['id' => 'act_777']),
        ]);
        $this->assertSame([], $this->api()->{$method}('act_777'));
        $this->assertSame([], $this->api()->{$method}('act_777'));
        Http::assertSentCount($method === 'pixels' ? 3 : 1);
    }

    public function test_a_write_with_a_lost_response_still_invalidates_audience_discovery(): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        $items = [];
        Http::preventStrayRequests();
        Http::fake(['*/act_777/customaudiences*' => function (Request $request) use (&$items) {
            if ($request->method() === 'POST') {
                $items = [['id' => '701']];

                throw new ConnectionException('Response lost');
            }

            return Http::response(['data' => $items]);
        }]);
        $api = $this->api();
        $this->assertSame([], $api->customAudiences('act_777'));
        try {
            $api->createWebsiteAudience('act_777', 'Visitors', '900', 'Purchase', 30);
            $this->fail('An uncertain write must remain an error.');
        } catch (ConnectionException) {
        }

        $this->assertSame([['id' => '701']], $api->customAudiences('act_777'));
        Http::assertSentCount(2);
        $this->assertSame(3, ApiCall::count());
    }

    #[TestWith(['pages'])]
    #[TestWith(['adAccounts'])]
    public function test_discovery_reads_are_shared_between_api_instances(string $method): void
    {
        Http::fake(['*' => Http::response(['data' => [['id' => '123', 'name' => 'Example']]])]);

        $first = $this->api()->{$method}();
        $this->assertSame($first, $this->api()->{$method}());

        Http::assertSentCount(1);
        $this->assertSame(1, ApiCall::count());
    }

    #[TestWith(['pages'])]
    #[TestWith(['adAccounts'])]
    public function test_empty_account_and_page_lists_keep_their_discovery_cache(string $method): void
    {
        Http::preventStrayRequests();
        Http::fake(['graph.facebook.com/v23.0/me/*' => Http::response(['data' => []])]);

        $this->assertSame([], $this->api()->{$method}());
        $this->assertSame([], $this->api()->{$method}());

        Http::assertSentCount(1);
    }

    public function test_paginated_discovery_reuses_each_page_without_truncating_results(): void
    {
        Http::fake(['*' => Http::sequence()
            ->push(['data' => [['id' => '123']], 'paging' => ['cursors' => ['after' => 'next-page']]])
            ->push(['data' => [['id' => '456']]])]);

        $expected = [['id' => '123'], ['id' => '456']];
        $this->assertSame($expected, $this->api()->pages());
        $this->assertSame($expected, $this->api()->pages());

        Http::assertSentCount(2);
    }

    public function test_cached_discovery_does_not_spend_or_require_another_call_budget(): void
    {
        Http::fake(['*' => Http::response(['data' => [['id' => '123']]])]);
        $this->api()->pages();
        $this->spend(2, null);

        $this->assertSame([['id' => '123']], $this->api()->pages());
        $this->assertSame(3, ApiCall::count());
        Http::assertSentCount(1);
    }

    public function test_interest_search_is_cached_for_seven_days_by_default(): void
    {
        Http::fake(['*' => Http::response(['data' => [['id' => '123', 'name' => 'Doctors']]])]);

        $first = $this->api()->targetingInterests('act_777', 'doctors');
        $this->travel(6)->days();
        $this->assertSame($first, $this->api()->targetingInterests('act_777', 'doctors'));
        Http::assertSentCount(1);

        $this->travel(2)->days();
        $this->api()->targetingInterests('act_777', 'doctors');
        Http::assertSentCount(2);
    }

    public function test_interest_search_normalization_and_expiry(): void
    {
        config(['platforms.meta.discovery_cache.interests' => 60]);
        Http::fake(['*' => Http::response(['data' => [['id' => '123', 'name' => 'Medical Students']]])]);

        $first = $this->api()->targetingInterests('act_777', ' Medical   Students ');
        $this->assertSame($first, $this->api()->targetingInterests('act_777', 'medical students'));
        Http::assertSentCount(1);

        $this->travel(61)->seconds();
        $this->api()->targetingInterests('act_777', 'medical students');
        Http::assertSentCount(2);
    }

    #[TestWith([[]])]
    #[TestWith([['data' => []]])]
    #[TestWith([['data' => [], 'paging' => ['cursors' => ['after' => 'cursor']]]])]
    public function test_empty_interest_results_are_retried_in_a_later_request(array $emptyResponse): void
    {
        $interests = [['id' => '123', 'name' => 'Doctors']];
        Http::preventStrayRequests();
        Http::fake(['graph.facebook.com/v23.0/act_777/targetingsearch*' => Http::sequence()
            ->push($emptyResponse)
            ->push(['data' => $interests])]);
        $api = $this->api();

        $this->assertSame([], $api->targetingInterests('act_777', 'doctors'));
        $this->assertSame([], $api->targetingInterests('act_777', 'doctors'));
        Http::assertSentCount(1);

        $this->assertSame($interests, $this->api()->targetingInterests('act_777', 'doctors'));
        $this->assertSame($interests, $this->api()->targetingInterests('act_777', 'doctors'));
        Http::assertSentCount(2);
        $this->assertDatabaseCount('api_calls', 2);
    }

    public function test_previously_cached_empty_interest_results_are_ignored(): void
    {
        $interests = [['id' => '123', 'name' => 'Doctors']];
        Http::preventStrayRequests();
        Http::fake(['graph.facebook.com/v23.0/act_777/targetingsearch*' => Http::response(['data' => $interests])]);
        $this->api()->targetingInterests('act_777', 'doctors');
        $entries = Cache::getStore()->all();
        $this->assertCount(1, $entries);
        Cache::put(array_key_first($entries), ['data' => []], 604800);

        $this->assertSame($interests, $this->api()->targetingInterests('act_777', 'doctors'));
        $this->assertSame($interests, $this->api()->targetingInterests('act_777', 'doctors'));

        Http::assertSentCount(2);
    }

    public function test_discovery_cache_isolated_by_credentials_version_and_account(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['act_777', 'act_888']]);
        Http::fake(['*' => Http::response(['data' => [['id' => '123', 'name' => 'Doctors']]])]);

        $this->api()->targetingInterests('act_777', 'doctors');
        $this->api('rotated-token')->targetingInterests('act_777', 'doctors');
        $this->api(version: 'v24.0')->targetingInterests('act_777', 'doctors');
        $this->api()->targetingInterests('act_888', 'doctors');

        Http::assertSentCount(4);
    }

    public function test_cached_interest_search_still_checks_account_permission(): void
    {
        Http::fake(['*' => Http::response(['data' => [['id' => '123', 'name' => 'Doctors']]])]);
        $this->api()->targetingInterests('act_777', 'doctors');
        config(['platforms.guardrails.allowed_ad_accounts' => ['act_888']]);

        try {
            $this->api()->targetingInterests('act_777', 'doctors');
            $this->fail('Revoked account permission must block cached discovery.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString('not on the allowed list', $exception->getMessage());
        }

        Http::assertSentCount(1);
    }

    public function test_validation_reads_are_not_persistently_cached(): void
    {
        Http::fake(['*' => Http::response(['data' => [['id' => '123', 'valid' => true]]])]);

        $this->api()->validateTargetingInterests('act_777', ['123']);
        $this->api()->validateTargetingInterests('act_777', ['123']);

        Http::assertSentCount(2);
    }

    public function test_discovery_cache_can_be_disabled(): void
    {
        config(['platforms.meta.discovery_cache.accounts_and_pages' => 0]);
        Http::fake(['*' => Http::response(['data' => []])]);

        $this->api()->pages();
        $this->api()->pages();

        Http::assertSentCount(2);
    }

    public function test_failed_discovery_does_not_populate_cache(): void
    {
        Http::fake(['*' => Http::sequence()
            ->push(['error' => ['message' => 'Invalid token', 'code' => 190]], 400)
            ->push(['data' => [['id' => '123']]])]);

        try {
            $this->api()->pages();
            $this->fail('Invalid credentials must be reported.');
        } catch (MetaException) {
        }

        $this->assertSame([['id' => '123']], $this->api()->pages());
        Http::assertSentCount(2);
    }

    #[TestWith([80004, 0, false])]
    #[TestWith([17, 2446079, false])]
    #[TestWith([4, 0, true])]
    #[TestWith([613, 0, true])]
    public function test_meta_quota_cooldown_scope_and_expiry(int $code, int $subcode, bool $tokenWide): void
    {
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['act_777', 'act_888'],
            'platforms.meta.cooldown_seconds' => 60,
        ]);
        Http::fake(['*' => Http::sequence()
            ->push(['error' => ['message' => 'Too many calls', 'code' => $code, 'error_subcode' => $subcode]], 400)
            ->push(['id' => 'act_888'])
            ->push(['id' => 'act_777'])]);

        try {
            $this->api()->adAccount('act_777');
            $this->fail('Expected the original Meta quota refusal.');
        } catch (MetaException $exception) {
            $this->assertSame($code, $exception->getCode());
        }

        try {
            $this->api()->adAccount('act_777');
            $this->fail('Expected the shared cooldown to prevent a second request.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString('No new request was sent', $exception->getMessage());
        }
        Http::assertSentCount(1);
        $this->assertSame(1, ApiCall::count());

        if ($tokenWide) {
            try {
                $this->api()->adAccount('act_888');
                $this->fail('Token-wide limits must cover other accounts.');
            } catch (MetaException $exception) {
                $this->assertStringContainsString('cooldown', $exception->getMessage());
            }
        } else {
            $this->assertSame('act_888', $this->api()->adAccount('act_888')['id']);
        }

        $this->travel(61)->seconds();
        $this->api()->adAccount('act_777');
        Http::assertSentCount($tokenWide ? 2 : 3);
    }

    public function test_cached_discovery_is_available_during_cooldown_and_rollback_is_not_blocked(): void
    {
        Http::fake(['*' => Http::sequence()
            ->push(['data' => [['id' => '123']]])
            ->push(['error' => ['message' => 'Too many calls', 'code' => 4]], 400)
            ->push(['success' => true])]);
        $this->api()->pages();

        try {
            $this->api()->adAccount('act_777');
            $this->fail('Expected a quota refusal.');
        } catch (MetaException) {
        }

        $this->assertSame([['id' => '123']], $this->api()->pages());
        $this->assertTrue($this->api()->delete('123'));
        Http::assertSentCount(3);
        $this->assertSame(3, ApiCall::count());
    }

    public function test_cooldown_blocks_writes_but_isolated_credentials_can_still_read(): void
    {
        Http::fake(['*' => Http::sequence()
            ->push(['error' => ['message' => 'Too many calls', 'code' => 4]], 400)
            ->push(['id' => 'act_777'])]);

        try {
            $this->api()->adAccount('act_777');
            $this->fail('Expected a quota refusal.');
        } catch (MetaException) {
        }

        try {
            $this->api(version: 'v24.0')->createPixel('act_777', 'New pixel');
            $this->fail('Writes must not bypass the Graph cooldown.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString('cooldown', $exception->getMessage());
        }

        $this->assertSame('act_777', $this->api('another-token')->adAccount('act_777')['id']);
        Http::assertSentCount(2);
    }

    #[TestWith([4, 0, true])]
    #[TestWith([17, 0, true])]
    #[TestWith([32, 0, true])]
    #[TestWith([613, 0, true])]
    #[TestWith([613, 1996, true])]
    #[TestWith([80004, 2446079, false])]
    #[TestWith([17, 2446079, false])]
    public function test_quota_policy_blocks_cross_account_writes_only_for_shared_cooldowns(int $code, int $subcode, bool $shared): void
    {
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['act_777', 'act_888'],
            'platforms.meta.cooldown_seconds' => 60,
        ]);
        Http::preventStrayRequests();
        Http::fake([
            'graph.facebook.com/v23.0/act_777*' => Http::response([
                'error' => ['code' => $code, 'error_subcode' => $subcode, 'message' => 'Too many calls'],
            ], 400),
            'graph.facebook.com/v23.0/990' => Http::response(['success' => true]),
        ]);

        try {
            $this->api()->adAccount('act_777');
            $this->fail('Expected the original quota refusal.');
        } catch (MetaException $exception) {
            $this->assertSame($code, $exception->getCode());
        }

        if ($shared) {
            try {
                $this->api()->updateEntity('990', ['daily_budget' => 2000], 'act_888');
                $this->fail('Shared quota cooldowns must also protect writes on other accounts.');
            } catch (MetaException $exception) {
                $this->assertStringContainsString('No new request was sent', $exception->getMessage());
            }
        } else {
            $this->assertSame(['success' => true], $this->api()->updateEntity('990', ['daily_budget' => 2000], 'act_888'));
        }

        Http::assertSentCount($shared ? 1 : 2);
        $this->assertDatabaseCount('api_calls', $shared ? 1 : 2);
    }

    #[TestWith([4])]
    #[TestWith([80004])]
    public function test_entity_updates_respect_cooldown_and_resume_after_expiry(int $code): void
    {
        $this->freezeTime();
        config(['platforms.meta.cooldown_seconds' => 60]);
        Http::preventStrayRequests();
        Http::fake([
            'graph.facebook.com/v23.0/act_777*' => Http::response(['error' => ['message' => 'Too many calls', 'code' => $code]], 400),
            'graph.facebook.com/v24.0/990' => Http::response(['success' => true]),
        ]);

        try {
            $this->api()->adAccount('act_777');
            $this->fail('Expected the original Meta quota refusal.');
        } catch (MetaException $exception) {
            $this->assertSame($code, $exception->getCode());
        }

        try {
            $this->api(version: 'v24.0')->updateEntity('990', ['daily_budget' => 2000], 'act_777');
            $this->fail('Entity updates must respect the cooldown across API versions.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString('No new request was sent', $exception->getMessage());
        }
        Http::assertSentCount(1);
        $this->assertDatabaseCount('api_calls', 1);

        $this->assertSame(['success' => true], $this->api('another-token', 'v24.0')->updateEntity('990', ['daily_budget' => 2000], 'act_777'));

        $this->travel(61)->seconds();
        $this->assertSame(['success' => true], $this->api(version: 'v24.0')->updateEntity('990', ['daily_budget' => 2000], 'act_777'));
        Http::assertSentCount(3);
        $this->assertDatabaseCount('api_calls', 3);
    }

    public function test_entity_update_quota_refusal_starts_an_account_cooldown(): void
    {
        $this->freezeTime();
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['act_777', 'act_888'],
            'platforms.meta.cooldown_seconds' => 60,
        ]);
        Http::preventStrayRequests();
        Http::fake([
            'graph.facebook.com/v23.0/990' => Http::response(['error' => ['message' => 'Too many calls', 'code' => 80004]], 400),
            'graph.facebook.com/v23.0/act_777*' => Http::response(['id' => 'act_777']),
            'graph.facebook.com/v23.0/act_888*' => Http::response(['id' => 'act_888']),
        ]);

        try {
            $this->api()->updateEntity('990', ['status' => 'ACTIVE'], 'act_777');
            $this->fail('Expected the original Meta quota refusal.');
        } catch (MetaException $exception) {
            $this->assertSame(80004, $exception->getCode());
        }

        try {
            $this->api()->adAccount('act_777');
            $this->fail('A quota refusal from an entity update must block subsequent account requests.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString('No new request was sent', $exception->getMessage());
        }
        Http::assertSentCount(1);
        $this->assertDatabaseCount('api_calls', 1);

        $this->assertSame('act_888', $this->api()->adAccount('act_888')['id']);
        Http::assertSentCount(2);
    }

    public function test_cooldown_can_be_disabled(): void
    {
        config(['platforms.meta.cooldown_seconds' => 0]);
        Http::fake(['*' => Http::sequence()
            ->push(['error' => ['message' => 'Too many calls', 'code' => 80004]], 400)
            ->push(['id' => 'act_777'])]);

        try {
            $this->api()->adAccount('act_777');
            $this->fail('Expected a quota refusal.');
        } catch (MetaException) {
        }

        $this->assertSame('act_777', $this->api()->adAccount('act_777')['id']);
        Http::assertSentCount(2);
    }

    public function test_a_rate_limit_is_retried_once_with_the_fallback_token(): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        Http::preventStrayRequests();
        Http::fake([
            '*' => Http::sequence()
                ->push(['error' => ['message' => 'Application request limit reached', 'code' => 4]], 400)
                ->push(['data' => [['id' => 'ig-1', 'username' => 'wintersale']]]),
        ]);

        $accounts = (new GraphApi('primary-token', 'v23.0', new CallLogger(app(Guardrails::class)), 'fallback-token'))
            ->instagramAccounts('act_777');

        $this->assertSame('ig-1', $accounts[0]['id']);
        Http::assertSentCount(2);

        $tokens = [];
        Http::assertSent(function (Request $request) use (&$tokens): bool {
            $tokens[] = (string) $request->data()['access_token'];

            return true;
        });

        $this->assertSame(['primary-token', 'fallback-token'], $tokens);
    }

    public function test_a_non_rate_limit_error_does_not_use_the_fallback_token(): void
    {
        config(['platforms.guardrails.max_calls_per_hour' => 100]);
        Http::preventStrayRequests();
        Http::fake([
            '*' => Http::response(['error' => ['message' => 'Invalid parameter', 'code' => 100]], 400),
        ]);

        try {
            (new GraphApi('primary-token', 'v23.0', new CallLogger(app(Guardrails::class)), 'fallback-token'))
                ->instagramAccounts('act_777');
            $this->fail('A non-rate-limit error must still fail.');
        } catch (MetaException $exception) {
            $this->assertSame(100, $exception->getCode());
        }

        Http::assertSentCount(1);
    }

    private function spend(int $calls, ?string $account): void
    {
        for ($i = 0; $i < $calls; $i++) {
            ApiCall::create([
                'transport' => 'graph',
                'method' => 'GET',
                'endpoint' => 'probe',
                'ad_account_id' => $account,
                'mutating' => false,
                'request' => [],
                'ok' => true,
            ]);
        }
    }

    public function test_an_account_over_its_budget_is_refused(): void
    {
        $this->spend(3, 'act_777');

        Http::fake(['*' => Http::response(['id' => 'act_777'])]);

        $this->expectException(MetaException::class);
        $this->expectExceptionMessage('hourly call budget');

        app(Meta::class)->adAccount('act_777');
    }

    /**
     * Calls that name no account are budgeted too.
     *
     * Listing Pages and listing ad accounts are both account-less, and they are
     * the two that sweep everything the token can see, so they were the two
     * nothing bounded.
     */
    public function test_calls_naming_no_account_are_budgeted(): void
    {
        $this->spend(3, null);

        Http::fake(['*' => Http::response(['data' => []])]);

        $this->expectException(MetaException::class);
        $this->expectExceptionMessage('calls that name no ad account');

        app(Meta::class)->pages();
    }

    /** The two buckets are separate, so one cannot starve the other. */
    public function test_an_account_budget_is_not_spent_by_account_less_calls(): void
    {
        $this->spend(3, null);

        Http::fake(['*' => Http::response(['id' => 'act_777', 'name' => 'Fine'])]);

        $this->assertSame('act_777', app(Meta::class)->adAccount('act_777')['id']);
    }

    /**
     * Retries count against the budget as they happen.
     *
     * Each attempt is a real call and writes its own row. Checked once up
     * front, a burst of throttles could overshoot the limit by the retry count.
     */
    public function test_a_retry_is_refused_once_the_budget_runs_out_mid_call(): void
    {
        $this->spend(2, 'act_777');

        // A 503, so the logger retries; the second attempt takes the count to the
        // limit and the third must not happen. This used a throttle, which is no
        // longer retried at all: Meta's hourly limits never cleared on the
        // sub-second backoff - 108 of them on production, none whose retry ever
        // succeeded - so repeating one only spent the quota again.
        Http::fake(['*' => Http::response(['error' => ['message' => 'Service temporarily unavailable', 'code' => 503]], 503)]);

        try {
            app(Meta::class)->adAccount('act_777');
        } catch (MetaException $e) {
            $this->assertStringContainsString('hourly call budget', $e->getMessage());

            $this->assertSame(
                3,
                ApiCall::where('ad_account_id', 'act_777')->count(),
                'the budget should stop the run at the limit, not past it',
            );

            return;
        }

        $this->fail('a throttled call over budget should have been refused');
    }
}
