<?php

namespace App\Services\Meta;

/**
 * Which Meta failures waiting cannot fix.
 *
 * Nothing tells them apart. An expired token, a missing role and a throttle all
 * arrive as one sentence from Graph, and whatever reads that sentence has to
 * guess which of the three it is holding. Two of them clear on their own and one
 * never does, so the guess decides whether the right advice is "try again shortly"
 * or "somebody has to replace the token".
 *
 * Grep for OAuthException, or for codes 190 or 2500, under app/Services/Platforms
 * and app/Agent before this existed: nothing. The retry loop had
 * CallLogger::THROTTLED naming what is worth repeating, and the permanent cases
 * were only ever the absence of that - which is a weak way to express the half
 * where being wrong strands somebody.
 *
 * Meta's user tokens last sixty days, so the authentication case is not a
 * hypothetical. It is a calendar event, and the first time it lands in the middle
 * of someone's campaign the question will be whether the chat said "the token has
 * expired" or "try again in a little while".
 *
 * Written in response to a dev-server session that looked like exactly this and
 * turned out not to be: the chat reported an account-call limit, I checked the
 * wrong bucket of api_calls, concluded it had invented the limit, and was wrong -
 * the limit was real and genuinely exhausted. The 2500 and 104 responses in that
 * database were older rows from another context. So this class is not the fix for
 * that incident; it is the gap that incident made me look at.
 */
class MetaApiError
{
    /**
     * The token itself is no longer usable.
     *
     * 190 is the documented family for expired, invalid and revoked tokens, with
     * subcodes for why. 102 is an invalid session. 2500 and 104 are what Graph
     * answers when there is effectively no token at all, which is the pair the
     * dev server produced.
     */
    private const NOT_AUTHENTICATED = [190, 102, 2500, 104];

    /**
     * The token is valid and the person behind it is not allowed to do this.
     *
     * 200 is the permission family - 200/2490585 is the "contact an admin to get
     * permission with an Advertiser role or higher" that stopped Kaushal's
     * creative upload on production.
     *
     * 10 used to be in here and is not the same thing; see APPLICATION_REFUSED.
     */
    private const NOT_PERMITTED = [200];

    /**
     * Meta refused the application, not the person.
     *
     * In this product that is almost always Graph being pointed at an object the
     * MCP created: a draft, or an object still being published, which Graph will
     * not read or delete whatever roles the login holds. The docblock on
     * NOT_PERMITTED has said so since it was written - "10 is the same answer
     * for an application rather than a user, which is what refuses a delete on
     * an MCP draft" - and the wording still sent people to Business Manager.
     *
     * The cost of getting this wrong is not only a confusing sentence.
     * MetaPublisher::isLive() reads the campaign through Graph; on an
     * MCP-created campaign it gets this, logs "Could not read campaign status
     * from Meta" and returns null. Nobody is short a role. Graph simply cannot
     * answer for that object, and telling an operator to go and grant one sends
     * them somewhere there is nothing to fix.
     */
    private const APPLICATION_REFUSED = [10];

    /**
     * One sentence to put in front of Meta's own, or null when waiting may help.
     *
     * Deliberately worded to contain none of CallLogger::THROTTLED's signatures,
     * because that check reads the finished message as a string: a retry hint
     * smuggled in here would have the retry loop treat a dead token as a burst.
     */
    public static function permanentReason(int|string|null $code, int|string|null $subcode = null): ?string
    {
        $code = is_numeric($code) ? (int) $code : null;

        if ($code === null) {
            return null;
        }

        if (in_array($code, self::NOT_AUTHENTICATED, true)) {
            return 'The Meta connection is not authenticated: its access token has expired, been revoked, '
                .'or was never valid. This will not clear by waiting and retrying cannot help. Nothing can '
                .'reach Meta until the token is replaced, so say that plainly, say that no campaign has '
                .'changed, and stop. Do not call it throttling or a temporary problem, and do not offer '
                .'to try again.';
        }

        if (in_array($code, self::NOT_PERMITTED, true)) {
            return 'The Meta connection is authenticated but is not permitted to do this, which usually '
                .'means the login lacks an Advertiser role on the ad account or the token lacks a scope. '
                .'This will not clear by waiting and retrying cannot help. Say what was refused, say that '
                .'access has to be granted in Business Manager first, and stop. Do not offer to try again.';
        }

        if (in_array($code, self::APPLICATION_REFUSED, true)) {
            return 'Meta refused this to the application rather than to the person, which on this product '
                .'is almost always the Graph API being asked about an object that Meta\'s MCP created and '
                .'has not finished publishing. Nobody is missing a role, so Business Manager is the wrong '
                .'place to look and granting access there changes nothing. Asking the same way again will '
                .'get the same answer. Say which object could not be read or changed, say it is because '
                .'that object was made through Meta\'s MCP, and do not describe it as a permissions '
                .'problem or as the campaign having failed.';
        }

        return null;
    }

    /** Whether this failure is one of the two above. */
    public static function isPermanent(int|string|null $code, int|string|null $subcode = null): bool
    {
        return self::permanentReason($code, $subcode) !== null;
    }
}
