<?php

namespace Tests\Feature;

use App\Models\User;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaApiError;
use App\Services\Meta\MetaException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;

/**
 * An authentication failure is not reported as something waiting will fix.
 *
 * Meta answers an expired token, a missing Advertiser role and an exhausted rate
 * limit with the same shape of message, and nothing in the platform layer told
 * them apart - grep for OAuthException or code 2500 under app/Services/Platforms
 * and app/Agent returned nothing before this. CallLogger::THROTTLED named what is
 * worth retrying; the permanent half was only its absence.
 *
 * Two of those three clear by waiting and one never does. A user token lasts
 * sixty days, so the one that never clears is a date on the calendar, and the
 * answer the buyer needs then is "the token has to be replaced", not "try again
 * shortly".
 *
 * On the provenance, since the docblock should not lie about it: this came out of
 * a dev session where the chat reported an account-call limit and I concluded it
 * had made that up, having counted calls that named an ad account while the
 * refusal came from the separate bucket for calls that name none - which really
 * was at 60 of 60. The chat was right and I was not. The OAuthException 2500 and
 * 104 rows I pointed at were older and unrelated. What survived is the gap itself,
 * which is real and was worth closing on its own.
 */
class AFailureWaitingCannotFixSaysSoTest extends TestCase
{
    use RefreshDatabase;

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

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['act_111'],
            'platforms.guardrails.paused' => false,
        ]);

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

    // ------------------------------------------------------- classification

    /** @return array<string, list<int>> */
    public static function authCodes(): array
    {
        return [
            'expired or revoked token' => [190],
            'invalid session' => [102],
            'no active access token' => [2500],
            'access token required' => [104],
        ];
    }

    #[DataProvider('authCodes')]
    public function test_an_authentication_failure_is_named_as_one(int $code): void
    {
        $reason = MetaApiError::permanentReason($code);

        $this->assertNotNull($reason, "code {$code} was treated as something waiting might fix");
        $this->assertStringContainsString('not authenticated', $reason);
        $this->assertStringContainsString('will not clear by waiting', $reason);
    }

    /** @return array<string, list<int>> */
    public static function permissionCodes(): array
    {
        return ['advertiser role missing' => [200]];
    }

    #[DataProvider('permissionCodes')]
    public function test_a_permission_failure_is_named_as_one(int $code): void
    {
        $reason = MetaApiError::permanentReason($code);

        $this->assertNotNull($reason);
        $this->assertStringContainsString('not permitted', $reason);
        $this->assertStringContainsString('Business Manager', $reason, 'the buyer needs to know where to go');
    }

    /**
     * Code 10 is the application being refused, not the person, and says so.
     *
     * This used to sit alongside 200 and borrow its sentence, so a buyer was
     * told the login lacked an Advertiser role and sent to Business Manager.
     * Nobody is short a role: in this product 10 is almost always Graph being
     * pointed at an object Meta's MCP created and has not finished publishing,
     * which NOT_PERMITTED's own docblock has said since it was written.
     *
     * It is not only confusing wording. MetaPublisher::isLive() reads the
     * campaign through Graph, gets this on an MCP-created campaign, and returns
     * null - so the product cannot tell the buyer their campaign is live, and
     * the operator is sent to a screen where there is nothing to fix.
     */
    public function test_an_application_refusal_does_not_send_anyone_to_business_manager(): void
    {
        $reason = (string) MetaApiError::permanentReason(10);

        $this->assertNotSame('', $reason, 'retrying this cannot help, so it must still be permanent');
        $this->assertTrue(MetaApiError::isPermanent(10));

        $this->assertStringContainsString('application rather than to the person', $reason);
        $this->assertStringContainsString('MCP', $reason, 'the real cause has to be named');
        $this->assertStringContainsString('wrong place to look', $reason, 'it must not send anyone to fix a role');
        $this->assertStringNotContainsString('lacks an Advertiser role', $reason);
    }

    /**
     * And it still cannot be mistaken for a throttle.
     *
     * permanentReason's docblock warns that CallLogger reads the finished
     * message as a string, so a retry signature smuggled into this wording
     * would have the retry loop treat a permanent refusal as a burst.
     */
    public function test_the_application_refusal_carries_no_throttle_signature(): void
    {
        $reason = strtolower((string) MetaApiError::permanentReason(10));

        foreach (['too many calls', 'rate limit', 'request limit reached', 'reduce the amount of data',
            '80004', '613', ' 17/', ' 4/', '429', '503', 'resource_exhausted', 'rate_exceeded', '2446079'] as $signature) {
            $this->assertStringNotContainsString($signature, $reason, "the wording reads as a throttle: {$signature}");
        }
    }

    /** @return array<string, list<int|null>> */
    public static function waitableCodes(): array
    {
        return [
            'user request limit' => [4],
            'application request limit' => [17],
            'too many calls on the account' => [613],
            'a plain validation failure' => [100],
            'nothing at all' => [null],
        ];
    }

    #[DataProvider('waitableCodes')]
    public function test_everything_else_is_left_alone(?int $code): void
    {
        $this->assertNull(
            MetaApiError::permanentReason($code),
            'a throttle or a validation error must not be relabelled as permanent',
        );
    }

    // ------------------------------------- and the retry loop still agrees

    /**
     * The message must not read as throttled to CallLogger.
     *
     * worthRetrying() matches THROTTLED against the finished message as a plain
     * string, so a single careless word here turns a dead token into three more
     * doomed requests. The first version of this fix said "do not describe this as
     * a rate limit", which contains "rate limit", which is on that list. Caught by
     * this assertion and not by reading it.
     */
    public function test_the_wording_does_not_look_like_a_throttle(): void
    {
        $signatures = ['too many calls', 'rate limit', 'request limit reached', 'reduce the amount of data',
            '80004', '613', ' 17/', ' 4/', '429', '503', 'resource_exhausted', 'rate_exceeded', 'quota'];

        foreach ([190, 102, 2500, 104, 10, 200] as $code) {
            $reason = strtolower((string) MetaApiError::permanentReason($code));

            foreach ($signatures as $signature) {
                $this->assertStringNotContainsString(
                    $signature,
                    $reason,
                    "code {$code} would be retried as a throttle because of \"{$signature}\"",
                );
            }
        }
    }

    // ------------------------------------------------- through the real call

    /** Meta's own sentence survives, because that is what gets quoted to Meta. */
    public function test_graph_keeps_metas_wording_and_adds_the_verdict(): void
    {
        Http::fake(['*' => Http::response([
            'error' => [
                'message' => 'An active access token must be used to query information about the current user.',
                'type' => 'OAuthException',
                'code' => 2500,
            ],
        ], 400)]);

        try {
            app(Meta::class)->on(null, 'tester')->adAccount('act_111');
            $this->fail('the call should have thrown');
        } catch (MetaException $e) {
            $this->assertStringContainsString('not authenticated', $e->getMessage(), 'the verdict is missing');
            $this->assertStringContainsString('active access token must be used', $e->getMessage(), 'Meta\'s own wording was dropped');
            $this->assertStringContainsString('[OAuthException 2500]', $e->getMessage(), 'the code is needed to escalate');
        }
    }

    /** An ordinary validation error is passed through untouched. */
    public function test_an_ordinary_error_is_not_editorialised(): void
    {
        Http::fake(['*' => Http::response([
            'error' => [
                'message' => 'custom_event_type "PAGE_VIEW" is not valid.',
                'type' => 'OAuthException',
                'code' => 100,
            ],
        ], 400)]);

        try {
            app(Meta::class)->on(null, 'tester')->adAccount('act_111');
            $this->fail('the call should have thrown');
        } catch (MetaException $e) {
            $this->assertStringNotContainsString('not authenticated', $e->getMessage());
            $this->assertStringNotContainsString('will not clear by waiting', $e->getMessage());
            $this->assertStringContainsString('PAGE_VIEW', $e->getMessage());
        }
    }
}
