<?php

namespace Tests\Feature;

use App\Models\ApiCall;
use App\Services\Meta\MetaException;
use App\Services\Platforms\Support\CallContext;
use App\Services\Platforms\Support\CallLogger;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/**
 * Trying again when it can help, and not when it cannot.
 *
 * This class was written to stop a throttled turn dying outright: Meta's
 * ads-management limit had blocked account enumeration for hours, and a throttle
 * is an explicit refusal, so repeating one cannot create a second campaign. The
 * reasoning was sound and the retry is safe. It just does not work.
 *
 * Production says so plainly. 108 throttles, and the number whose retry ever
 * succeeded within thirty seconds:
 *
 *   throttled_total  retry_succeeded_within_30s
 *   108              0
 *
 * Every chain reads 0 -> 0 -> 0, one to two seconds apart. Meta's ad limits reset
 * hourly and the backoff is half a second to sixteen, so the wait is three orders
 * of magnitude short. What the retry did instead was multiply the refusals: three
 * attempts per call, nine per account, 33 across 11 accounts inside one minute on
 * 7 Oct. Kaushal reported it as a rate-limiting problem, and the retry was making
 * it worse rather than riding it out.
 *
 * So the hourly limits fail once and report. Everything else keeps the original
 * behaviour, which was never in doubt: a 503 or a transport blip is still worth
 * another go, and a timeout is still a different thing entirely - the reply may
 * have been lost after the work was done, so a write that times out is never
 * repeated. Same reasoning as the double publish guard.
 */
class RateLimitRetryTest extends TestCase
{
    use RefreshDatabase;

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

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['act_777'],
            // No point sitting through the real backoff to prove the count.
            'platforms.guardrails.retry_backoff_ms' => 0,
        ]);
    }

    private function context(bool $mutating = false): CallContext
    {
        return new CallContext('graph', 'POST', 'act_777/campaigns', 'act_777', [], mutating: $mutating);
    }

    /** The exact error that blocked us, as Meta words it. */
    public function test_a_throttled_read_is_not_tried_again(): void
    {
        $calls = 0;

        try {
            app(CallLogger::class)->record($this->context(), function () use (&$calls): array {
                $calls++;

                throw new MetaException(
                    'There have been too many calls to this ad-account. Wait a bit and try again '
                    .'[OAuthException 80004/2446079] on me/adaccounts'
                );
            });

            $this->fail('the throttle should have been reported, not swallowed');
        } catch (MetaException $e) {
            $this->assertStringContainsString('too many calls', $e->getMessage());
        }

        $this->assertSame(1, $calls, 'the hourly limit was asked again, spending the quota for the same answer');
    }

    /**
     * Repeating a refusal is safe, which was never the question. It is useless.
     */
    public function test_a_throttled_write_is_not_tried_again(): void
    {
        $calls = 0;

        try {
            app(CallLogger::class)->record($this->context(mutating: true), function () use (&$calls): array {
                $calls++;

                throw new MetaException('User request limit reached [OAuthException 17] on act_777/campaigns');
            });

            $this->fail('the throttle should have been reported');
        } catch (MetaException) {
            // expected
        }

        $this->assertSame(1, $calls);
    }

    /** A 503 is still worth another go, which is the half that still works. */
    public function test_a_transient_failure_is_still_tried_again(): void
    {
        $calls = 0;

        $result = app(CallLogger::class)->record($this->context(), function () use (&$calls): array {
            $calls++;

            if ($calls < 3) {
                throw new MetaException('Service temporarily unavailable [503] on me/adaccounts');
            }

            return ['id' => 'act_777'];
        });

        $this->assertSame(['id' => 'act_777'], $result);
        $this->assertSame(3, $calls);
    }

    /**
     * The case that must never be repeated.
     *
     * A write that times out may already have created the campaign, and the
     * reply was simply lost. Repeating it is how one campaign becomes two.
     */
    public function test_a_write_that_times_out_is_never_repeated(): void
    {
        $calls = 0;

        try {
            app(CallLogger::class)->record($this->context(mutating: true), function () use (&$calls): array {
                $calls++;

                throw new MetaException('cURL error 28: Operation timed out after 120000 milliseconds');
            });
        } catch (MetaException) {
            // expected
        }

        $this->assertSame(1, $calls, 'A timed-out write must not be sent twice.');
    }

    /** A read that times out changed nothing, so it can go again. */
    public function test_a_read_that_times_out_is_tried_again(): void
    {
        $calls = 0;

        try {
            app(CallLogger::class)->record($this->context(), function () use (&$calls): array {
                $calls++;

                throw new MetaException('cURL error 28: Operation timed out after 120000 milliseconds');
            });
        } catch (MetaException) {
            // expected
        }

        $this->assertSame(3, $calls);
    }

    /** An ordinary rejection is not worth repeating; it will be rejected again. */
    public function test_a_real_error_is_not_retried(): void
    {
        $calls = 0;

        try {
            app(CallLogger::class)->record($this->context(mutating: true), function () use (&$calls): array {
                $calls++;

                throw new MetaException('Invalid image hash [OAuthException 100] on act_777/adcreatives');
            });
        } catch (MetaException) {
            // expected
        }

        $this->assertSame(1, $calls);
    }

    public function test_it_gives_up_rather_than_retrying_forever(): void
    {
        $calls = 0;

        try {
            app(CallLogger::class)->record($this->context(), function () use (&$calls): array {
                $calls++;

                // A 503, because an hourly limit is no longer retried at all.
                throw new MetaException('Service temporarily unavailable [503] on act_777/campaigns');
            });
        } catch (MetaException) {
            // expected
        }

        $this->assertSame(3, $calls);
    }

    /**
     * Every attempt is a real call against Meta's quota, so every attempt is
     * recorded. An audit log that showed one row for three calls would
     * understate what we did to the account.
     */
    public function test_every_attempt_is_audited(): void
    {
        try {
            app(CallLogger::class)->record($this->context(), function (): array {
                throw new MetaException('Service temporarily unavailable [503] on act_777/campaigns');
            });
        } catch (MetaException) {
            // expected
        }

        $this->assertSame(3, ApiCall::count());
        $this->assertSame(0, ApiCall::where('ok', true)->count());
    }
}
