<?php

namespace App\Campaigns;

/**
 * The pairings Meta enforces between an objective, what it optimises toward,
 * and the pixel event it counts.
 *
 * Kept in one place because getting a pair wrong is not a validation error you
 * can reason about from the message: sending PURCHASE under a leads objective
 * comes back as "conversion event unavailable", subcode 2446814.
 */
class Objectives
{
    /**
     * Five of Meta's six ODAX objectives.
     *
     * OUTCOME_APP_PROMOTION is deliberately absent. It needs a promoted app
     * object naming a store listing, there is no field for one anywhere in this
     * product, and an objective that cannot reach a publishable ad set is worse
     * as a button than as an absence.
     */
    public const SUPPORTED = [
        'OUTCOME_SALES', 'OUTCOME_LEADS', 'OUTCOME_TRAFFIC',
        'OUTCOME_ENGAGEMENT', 'OUTCOME_AWARENESS',
    ];

    private const OPTIMIZATION_GOAL = [
        'OUTCOME_SALES' => 'OFFSITE_CONVERSIONS',
        'OUTCOME_LEADS' => 'OFFSITE_CONVERSIONS',
        'OUTCOME_TRAFFIC' => 'LINK_CLICKS',
        'OUTCOME_ENGAGEMENT' => 'POST_ENGAGEMENT',
        'OUTCOME_AWARENESS' => 'REACH',
    ];

    private const CONVERSION_EVENT = [
        'OUTCOME_SALES' => 'PURCHASE',
        'OUTCOME_LEADS' => 'LEAD',
        'OUTCOME_TRAFFIC' => null,
        'OUTCOME_ENGAGEMENT' => null,
        'OUTCOME_AWARENESS' => null,
    ];

    /**
     * Pixel event names as Meta reports them, against the enum an ad set takes.
     *
     * Two different vocabularies for one thing: a pixel fires "CompleteRegistration"
     * and promoted_object.custom_event_type wants COMPLETE_REGISTRATION. Only the
     * standard events are here, because a custom event has no enum member and is
     * published as OTHER.
     */
    private const EVENT_TYPE = [
        'Purchase' => 'PURCHASE',
        'Lead' => 'LEAD',
        'CompleteRegistration' => 'COMPLETE_REGISTRATION',
        'AddToCart' => 'ADD_TO_CART',
        'AddToWishlist' => 'ADD_TO_WISHLIST',
        'InitiateCheckout' => 'INITIATED_CHECKOUT',
        'AddPaymentInfo' => 'ADD_PAYMENT_INFO',
        'ViewContent' => 'CONTENT_VIEW',
        'PageView' => 'PAGE_VIEW',
        'Search' => 'SEARCH',
        'Subscribe' => 'SUBSCRIBE',
        'StartTrial' => 'START_TRIAL',
        'Donate' => 'DONATE',
        'Contact' => 'CONTACT',
        'CustomizeProduct' => 'CUSTOMIZE_PRODUCT',
        'FindLocation' => 'FIND_LOCATION',
        'Schedule' => 'SCHEDULE',
        'SubmitApplication' => 'SUBMIT_APPLICATION',
    ];

    /**
     * The custom_event_type values an objective's ad set will actually take.
     *
     * Translating a pixel event into Meta's enum is not the same as the ad set
     * accepting it. EVENT_TYPE above maps every standard pixel event, correctly,
     * and a sales ad set still refuses most of them: a pixel fires PageView, that
     * is PAGE_VIEW, and ads_create_ad_set answers "custom_event_type
     * \"PAGE_VIEW\" is not valid. Did you mean \"PDP_VIEW\"?".
     *
     * Found on production on 5 Oct. The chat read the pixel's history, offered
     * PageView because that is what the pixel had fired, the buyer picked it, the
     * gate passed it, and Meta refused it only after the campaign object already
     * existed - leaving a campaign on the account that the rollback could not
     * delete.
     *
     * Only OUTCOME_SALES is listed, because its list is the one Meta has actually
     * told us, verbatim, in that error. The others are absent rather than guessed:
     * an invented list would refuse events that are in fact fine, which is the
     * same class of mistake in the opposite direction and harder to notice.
     * acceptedEventTypes() returns null for those, and callers do not filter.
     *
     * @var array<string, list<string>>
     */
    private const ACCEPTED_EVENT_TYPES = [
        'OUTCOME_SALES' => [
            'PURCHASE', 'INITIATED_CHECKOUT', 'ADD_TO_CART', 'CONTENT_VIEW',
            'ADD_TO_WISHLIST', 'ADD_PAYMENT_INFO', 'SEARCH', 'LEAD',
        ],
    ];

    /**
     * Values EVENT_TYPE produces that no ad set takes, whatever it optimises for.
     *
     * Separate from ACCEPTED_EVENT_TYPES because this is not a question of which
     * objective. Meta's custom_event_type enum has no PAGE_VIEW member at all,
     * so the refusal is the enum's rather than the objective's:
     * "custom_event_type \"PAGE_VIEW\" is not valid. Did you mean \"PDP_VIEW\"?".
     *
     * Which means the unknown-list rule below cannot be trusted to cover it. An
     * unknown list is not evidence against an event, and that reasoning is right,
     * but it let PAGE_VIEW through on every objective except SALES - the one
     * objective whose list we happen to hold.
     *
     * Found twice on production. OUTCOME_TRAFFIC on 5 Oct, OUTCOME_LEADS on
     * 7 Oct, two ad accounts, the same refusal both times, and both times it
     * arrived from ads_create_ad_set after ads_create_campaign had already
     * succeeded - so there was a campaign on the account and nothing to attach
     * to it. The second one reached a buyer whose pixel fires nothing else, so
     * the chat offered PageView, it was the only option, and it could not work.
     *
     * The pixel vocabulary keeps its PageView entry: the pixel really does fire
     * it and saying otherwise would be a different lie. It is optimising toward
     * it that Meta has no enum for.
     *
     * @var list<string>
     */
    private const NEVER_ACCEPTED = ['PAGE_VIEW'];

    /**
     * What this objective's ad set accepts, or null when nobody has told us.
     *
     * Null means "unknown", not "nothing". A caller must read it as a reason to
     * leave the choice alone rather than as a reason to refuse every event.
     *
     * @return list<string>|null
     */
    public static function acceptedEventTypes(?string $objective): ?array
    {
        return self::ACCEPTED_EVENT_TYPES[$objective] ?? null;
    }

    /**
     * Whether this objective's ad set will take this event.
     *
     * True when the objective's list is unknown, for the reason above: an
     * unknown list is not evidence against anything.
     */
    public static function acceptsEventType(?string $objective, ?string $eventType): bool
    {
        // Before the unknown-list rule, not after it, because this refusal does
        // not depend on the objective and that rule would return true first.
        if ($eventType !== null && in_array($eventType, self::NEVER_ACCEPTED, true)) {
            return false;
        }

        $accepted = self::acceptedEventTypes($objective);

        if ($accepted === null || $eventType === null) {
            return true;
        }

        // OTHER is Meta's own value for an event outside its list, and whether a
        // given objective takes it is not something the error told us. Left
        // alone rather than refused on a guess.
        return $eventType === 'OTHER' || in_array($eventType, $accepted, true);
    }

    /**
     * Every standard event a buyer may choose for this objective.
     *
     * In pixel vocabulary, because that is what Events Manager shows them and
     * what they will be looking for on screen.
     *
     * Note what this does not consult: whether the pixel has fired any of them.
     * The chooser used to offer only fired events and refuse the rest, and that
     * conflated two different things. Meta will happily optimise toward an event
     * with no history - it simply has nothing to learn from yet, which is a
     * delivery warning and not a reason to refuse. What actually broke
     * production was PAGE_VIEW, an enum member Meta does not have, and that is
     * caught by acceptsEventType() regardless of history. Treating the pixel's
     * past as a permission system is what left a leads campaign on a PageView-only
     * pixel with nothing selectable at all.
     *
     * @return list<string>
     */
    public static function selectableEventNames(?string $objective): array
    {
        return array_values(array_filter(
            array_keys(self::EVENT_TYPE),
            fn (string $name): bool => self::acceptsEventType($objective, self::EVENT_TYPE[$name]),
        ));
    }

    /**
     * The enum value for an event a pixel reported firing.
     *
     * A custom event is a real choice and becomes OTHER, which is what Meta
     * takes for anything outside its own list.
     */
    public static function eventType(string $pixelEventName): string
    {
        return self::EVENT_TYPE[$pixelEventName] ?? 'OTHER';
    }

    /** Pixel spelling of a standard event, matched without case, or null for a custom name. */
    public static function canonicalEventName(string $name): ?string
    {
        foreach (array_keys(self::EVENT_TYPE) as $standard) {
            if (strcasecmp($standard, $name) === 0) {
                return $standard;
            }
        }

        return null;
    }

    /** The pixel event name an enum value came from, for saying it back. */
    public static function eventName(?string $eventType): ?string
    {
        if ($eventType === null) {
            return null;
        }

        return array_search($eventType, self::EVENT_TYPE, true) ?: null;
    }

    /**
     * Whether the ad set names what it is promoting.
     *
     * A pixel objective names the pixel and the event; the rest name the Page.
     * REACH names neither: Meta rejects a promoted object against it, because
     * there is no object being optimised toward, only people being counted.
     *
     * @var array<string, bool>
     */
    private const NEEDS_PROMOTED_OBJECT = [
        'OFFSITE_CONVERSIONS' => true,
        'LINK_CLICKS' => true,
        'POST_ENGAGEMENT' => true,
        'REACH' => false,
    ];

    public const CALLS_TO_ACTION = [
        'SHOP_NOW', 'LEARN_MORE', 'SIGN_UP', 'GET_OFFER', 'SUBSCRIBE', 'CONTACT_US', 'BOOK_TRAVEL',
    ];

    /**
     * LOWEST_COST_WITHOUT_CAP spends the budget freely. COST_CAP holds an
     * average cost per result, which is how a target CPL or CPA is expressed.
     */
    public const BID_STRATEGIES = ['LOWEST_COST_WITHOUT_CAP', 'COST_CAP', 'LOWEST_COST_WITH_BID_CAP'];

    public const DEVICES = ['mobile', 'desktop'];

    public const PLACEMENTS = ['facebook', 'instagram', 'messenger', 'audience_network', 'threads'];

    /**
     * What a person calls it.
     *
     * A button reading OUTCOME_LEADS asks the reader to know Meta's vocabulary,
     * which is the thing offering choices is meant to remove. Falls back to the
     * raw value so a new objective is still usable before anyone names it.
     */
    public static function label(string $objective): string
    {
        return match ($objective) {
            'OUTCOME_SALES' => 'Sales',
            'OUTCOME_LEADS' => 'Leads',
            'OUTCOME_TRAFFIC' => 'Website Traffic',
            'OUTCOME_ENGAGEMENT' => 'Engagement',
            'OUTCOME_AWARENESS' => 'Brand Awareness',
            'OUTCOME_APP_PROMOTION' => 'App promotion',
            default => ucfirst(strtolower(str_replace(['OUTCOME_', '_'], ['', ' '], $objective))),
        };
    }

    /** One line on what picking it means, since the difference is not obvious. */
    public static function hint(string $objective): ?string
    {
        return match ($objective) {
            'OUTCOME_SALES' => 'Optimise for purchases. Needs a pixel.',
            'OUTCOME_LEADS' => 'Optimise for form fills and sign-ups. Needs a pixel.',
            'OUTCOME_TRAFFIC' => 'Optimise for clicks to the landing page.',
            'OUTCOME_ENGAGEMENT' => 'Optimise for reactions, comments and shares rather than clicks.',
            'OUTCOME_AWARENESS' => 'Optimise for how many people see it, not what they do next.',
            default => null,
        };
    }

    public static function supports(?string $objective): bool
    {
        return in_array($objective, self::SUPPORTED, true);
    }

    public static function optimizationGoal(string $objective): string
    {
        return self::OPTIMIZATION_GOAL[$objective] ?? 'LINK_CLICKS';
    }

    public static function conversionEvent(?string $objective): ?string
    {
        return self::CONVERSION_EVENT[$objective] ?? null;
    }

    /** Whether this optimisation goal takes a promoted object at all. */
    public static function needsPromotedObject(string $optimizationGoal): bool
    {
        return self::NEEDS_PROMOTED_OBJECT[$optimizationGoal] ?? true;
    }
}
