<?php

namespace App\Campaigns;

use App\Agent\Workspace;
use App\Campaigns\Platforms\Platforms;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\CampaignAdSet;
use App\Support\AssetOriginal;
use Illuminate\Support\Collection;

/**
 * Decides whether a campaign may be published.
 *
 * Plain code on purpose. The agent may request publication; only this grants
 * it. Every reason is phrased so it can be shown to the user unchanged, because
 * the same list drives both the prompt and whatever the interface renders.
 *
 * The shared checks below apply everywhere. Anything a platform disagrees about
 * comes from its own rules, so this class never learns which platform it is
 * looking at and a new platform inherits every shared protection by existing.
 */
class PublishGate
{
    public function __construct(
        private readonly Workspace $workspace,
        private readonly Platforms $platforms,
        private readonly TargetingSelections $selections,
    ) {}

    /**
     * @return list<string> reasons publishing is blocked; empty means allowed
     */
    public function check(Campaign $campaign): array
    {
        if (! $this->platforms->supports($campaign->platform)) {
            return ["[{$campaign->platform}] is not a platform this product supports"];
        }

        return array_values(array_filter([
            // First, so it is the only thing reported once a campaign is live.
            // Everything below describes how to make it publishable, which is
            // misleading for something already on the platform.
            $campaign->isPublished()
                ? 'already published as '.$campaign->external_campaign_id
                : null,
            ...$this->soundness($campaign),
        ]));
    }

    /**
     * Whether one ad set may be added to a campaign that is already live.
     *
     * Its own list rather than soundness(), which asks about the campaign as a
     * whole and would re-litigate the objective, the Page, the pixel, the
     * destination and every existing ad - all settled when the campaign was
     * published, and none of them this ad set's to answer for. Running them
     * again would also report a problem with an ad somewhere else in the
     * campaign as a reason this ad set cannot be added.
     *
     * What is left is what an ad set actually decides: who sees the ads, when,
     * and for how much.
     *
     * @return list<string> reasons it cannot be added; empty means allowed
     */
    public function adSetProblems(CampaignAdSet $adSet): array
    {
        $campaign = $adSet->campaign;

        if ($campaign === null) {
            return ['this ad set is not attached to a campaign'];
        }

        if (! $this->platforms->supports($campaign->platform)) {
            return ["[{$campaign->platform}] is not a platform this product supports"];
        }

        // Nothing to add it to. Publishing the campaign is what creates its ad
        // sets, so an unpublished campaign's second ad set is simply part of
        // the campaign and goes out with it.
        if (! $campaign->isPublished()) {
            return [
                'the campaign has not been published yet, so there is nothing to add an ad set to. '
                .'Publish the campaign and its ad sets go out together.',
            ];
        }

        if ($adSet->isPublished()) {
            return ['this ad set is already on the platform as '.$adSet->external_adset_id];
        }

        $rules = $this->platforms->for($campaign);

        return array_values(array_filter([
            ...$this->adSetAudience($campaign, $adSet, $rules),
            ...$this->adSetBudget($campaign, $adSet, $rules),
            ...$this->adSetSchedule($adSet),
        ]));
    }

    /** @return list<string|null> */
    private function adSetAudience(Campaign $campaign, CampaignAdSet $adSet, $rules): array
    {
        $chosen = (array) ($adSet->placements ?? []);

        $impossible = filled($campaign->objective)
            ? array_diff($chosen, $rules->placementsFor($campaign->objective))
            : [];

        return [
            empty($adSet->locations['countries'] ?? []) ? 'target country not set for this ad set' : null,
            ...$this->selections->additionalMetaAdSetProblems($adSet),

            $impossible !== [] ? sprintf(
                '%s cannot run on %s. Supported for this objective: %s',
                $campaign->objective,
                implode(', ', $impossible),
                implode(', ', $rules->placementsFor($campaign->objective)),
            ) : null,
        ];
    }

    /**
     * The ad set's money, against the same floor and ceiling a campaign's is.
     *
     * An ad set under a campaign holding the budget itself has none of its own,
     * and must not: Meta moves the money between ad sets and an amount here
     * would be refused. So that case checks that it is absent rather than
     * checking an amount.
     *
     * @return list<string|null>
     */
    private function adSetBudget(Campaign $campaign, CampaignAdSet $adSet, $rules): array
    {
        if ($campaign->usesCampaignBudget()) {
            return [
                $adSet->budget !== null
                    ? 'this campaign holds its budget at campaign level and moves it between ad sets, '
                        .'so an ad set under it cannot have an amount of its own'
                    : null,
            ];
        }

        $amount = $adSet->effectiveBudget();
        $lifetime = $adSet->effectiveBudgetMode() === 'lifetime';
        $label = $lifetime ? 'lifetime budget' : 'daily budget';

        if ($amount === null || $amount <= 0) {
            return [$label.' not set for this ad set'];
        }

        if ($lifetime && ! $adSet->ends_at) {
            return ['a lifetime budget needs an end date, since it is the total to spend by then'];
        }

        $ceiling = BudgetCeiling::for($campaign);

        if ($ceiling === null) {
            return [BudgetCeiling::missingReason($campaign)];
        }

        $days = $lifetime
            ? max((int) ($adSet->starts_at ?? now())->diffInDays($adSet->ends_at), 1)
            : 1;
        $perDay = $amount / max($days, 1);
        $floor = (float) $rules->minimumDailyBudget();

        return [
            $perDay < $floor ? sprintf(
                '%s of %.2f is %.2f a day, below %s\'s %.2f minimum',
                $label, $amount, $perDay, $rules->name(), $floor,
            ) : null,

            $perDay > $ceiling ? sprintf(
                '%s of %.2f is %.2f a day, above the %.2f ceiling this product allows',
                $label, $amount, $perDay, $ceiling,
            ) : null,
        ];
    }

    /**
     * Whether these ads may be added to a campaign that is already live.
     *
     * The same copy, call-to-action and asset checks publishing makes, run
     * against the ads being added rather than every ad on the campaign. Running
     * them against all of them would report an ad published weeks ago as the
     * reason a new one cannot go out, and nothing could be done about it.
     *
     * max_ads_per_publish counts the new ones too. It is a guardrail on how much
     * one approval may create, which is what this is, and counting the existing
     * ads as well would make the limit fall as a campaign grew until no ad could
     * ever be added again.
     *
     * @param  Collection<int, CampaignAd>  $ads
     * @return list<string>
     */
    public function adsReadyToAdd(Campaign $campaign, Collection $ads): array
    {
        $rules = $this->platforms->for($campaign);
        $limit = (int) config('platforms.guardrails.max_ads_per_publish');

        // As above: what the platform will create, not how many rows describe it.
        $creating = $rules->buildsOneAdFromEveryVariation() ? min(1, $ads->count()) : $ads->count();

        $problems = [
            $creating > $limit
                ? sprintf('%d ads, but at most %d may be created at once', $creating, $limit)
                : null,
        ];

        foreach ($ads->values() as $index => $ad) {
            $problems = [...$problems, ...$this->oneAd($campaign, $ad, $rules, $ads->count() > 1 ? 'ad '.($index + 1).': ' : '')];
        }

        return array_values(array_filter($problems));
    }

    /**
     * The event the ad set optimises toward, against what it will accept.
     *
     * The last line of defence for the defect found on production on 5 Oct. The
     * chooser now narrows what it offers, and this is what makes it impossible
     * to arrive here another way: a campaign adopted from the platform, one whose
     * objective changed after the event was chosen, or a model that set the
     * column directly.
     *
     * It belongs in the gate rather than only in the tool because the cost is
     * not a refused request. ads_create_campaign succeeds first, so the campaign
     * exists on the account before the ad set is refused, and the rollback cannot
     * remove an MCP draft.
     *
     * @return list<string|null>
     */
    private function conversionEvent(Campaign $campaign): array
    {
        $event = $campaign->conversion_event;

        if (MetaPromotedConversion::customConversionId($event) !== null) {
            return [];
        }

        $event = MetaPromotedConversion::eventType($event);

        if (blank($event) || Objectives::acceptsEventType($campaign->objective, $event)) {
            return [];
        }

        $accepted = collect(Objectives::acceptedEventTypes($campaign->objective) ?? [])
            ->map(fn (string $type): string => Objectives::eventName($type) ?? $type)
            ->implode(', ');

        return [sprintf(
            '%s cannot be optimised toward on a %s campaign, and Meta refuses it at the ad set '
            .'after the campaign has already been created. It accepts %s there.',
            Objectives::eventName($event) ?? $event,
            Objectives::label((string) $campaign->objective),
            $accepted,
        )];
    }

    /** @return list<string|null> */
    private function adSetSchedule(CampaignAdSet $adSet): array
    {
        return [
            $adSet->starts_at && $adSet->ends_at && $adSet->ends_at->lte($adSet->starts_at)
                ? 'end date must be after the start date' : null,

            $adSet->ends_at && $adSet->ends_at->isPast()
                ? 'end date is in the past' : null,
        ];
    }

    /**
     * Everything that has to be true for this campaign to run, except whether it
     * has been published.
     *
     * Publishing and starting need the same answers to almost the same questions,
     * and differ on exactly one: publishing refuses a campaign that already exists
     * on the platform, and starting requires it. So the shared part is named, and
     * the one difference lives in the two callers rather than in a flag.
     *
     * Without this, activation re-checking the gate would refuse every campaign it
     * could possibly be asked about - the first thing check() says about anything
     * published is that it is published.
     *
     * @return list<string>
     */
    public function soundness(Campaign $campaign): array
    {
        if (! $this->platforms->supports($campaign->platform)) {
            return ["[{$campaign->platform}] is not a platform this product supports"];
        }

        $rules = $this->platforms->for($campaign);

        return array_values(array_filter([
            ...$this->basics($campaign, $rules),
            ...$this->share($campaign),
            ...$this->schedule($campaign),
            ...$this->audience($campaign),
            ...$this->ads($campaign, $rules),
            ...$this->account($campaign, $rules),
            ...$this->destination($campaign),
            ...$this->conversionEvent($campaign),
            ...$this->provenance($campaign),
            ...$rules->additionalProblems($campaign),
        ]));
    }

    public function passes(Campaign $campaign): bool
    {
        return $this->check($campaign) === [];
    }

    /** @return list<string|null> */
    private function basics(Campaign $campaign, $rules): array
    {
        $ceiling = BudgetCeiling::for($campaign);
        $floor = $rules->minimumDailyBudget();

        return [
            blank($campaign->name) ? 'campaign name not set' : null,

            // Not defaulted. Every campaign so far declared "no special
            // category" because the write paths hardcoded an empty list, which
            // for a housing, employment or credit ad is a false declaration to
            // Meta rather than a missing field. Somebody has to answer.
            match (true) {
                $rules->specialAdCategories() === [] => null,
                $campaign->special_ad_categories === null => 'special ad category not declared. '
                    .'Ask whether this is housing, employment, credit or social issues, and say NONE if it is none of them',
                $this->unknownCategories($campaign, $rules) !== [] => sprintf(
                    'unknown special ad category: %s. Allowed: %s',
                    implode(', ', $this->unknownCategories($campaign, $rules)),
                    implode(', ', $rules->specialAdCategories()),
                ),
                default => null,
            },

            match (true) {
                blank($campaign->objective) => 'objective not set',
                ! in_array($campaign->objective, $rules->objectives(), true) => sprintf(
                    '%s does not support the %s objective. Supported: %s',
                    $rules->name(),
                    $campaign->objective,
                    implode(', ', $rules->objectives()),
                ),
                default => null,
            },

            match (true) {
                blank($campaign->landing_url) => 'landing page URL not set',
                ! filter_var($campaign->landing_url, FILTER_VALIDATE_URL) => 'landing page URL is not valid',
                default => null,
            },

            ...$this->budget($campaign, $floor, $ceiling, $rules),

            match (true) {
                blank($campaign->bid_strategy) => null,
                ! in_array($campaign->bid_strategy, $rules->bidStrategies($campaign->objective, $campaign->campaign_type), true) => sprintf(
                    '%s does not support the %s bid strategy%s. Supported: %s',
                    $rules->name(),
                    $campaign->bid_strategy,
                    filled($campaign->objective) ? ' on a '.$campaign->objective.' campaign' : '',
                    implode(', ', $rules->bidStrategies($campaign->objective, $campaign->campaign_type)),
                ),
                // Asked of the platform. Written as a comparison against Meta's
                // uncapped strategy, it demanded a target cost from every
                // Google strategy including the ones that take none.
                $rules->bidStrategyNeedsTarget((string) $campaign->bid_strategy)
                    && blank($campaign->bid_amount) => 'bid strategy needs a target cost',
                default => null,
            },
        ];
    }

    /**
     * The budget, read against the mode it was set in.
     *
     * A lifetime budget is a total rather than a rate, so neither the floor nor
     * the ceiling can be compared against it directly: 300 over thirty days is
     * ten a day, not a 300 daily spend. Both limits are applied to the implied
     * daily amount, which is also how Meta reads its own minimum.
     *
     * @return list<string|null>
     */
    private function budget(Campaign $campaign, float $floor, ?float $ceiling, $rules): array
    {
        $lifetime = $campaign->usesLifetimeBudget();
        $label = $lifetime ? 'lifetime budget' : 'daily budget';

        if (blank($campaign->budget) || (float) $campaign->budget <= 0) {
            return [$label.' not set'];
        }

        // Meta refuses a lifetime budget with no end time, and refuses it after
        // the campaign exists rather than during validation.
        if ($lifetime && ! $campaign->ends_at) {
            return ['a lifetime budget needs an end date, since it is the total to spend by then'];
        }

        // No ceiling configured for this account's currency. Refuse rather than
        // fall back to one expressed in a different currency, which would be a
        // spending limit that means nothing.
        if ($ceiling === null) {
            return [BudgetCeiling::missingReason($campaign)];
        }

        $days = $lifetime ? $this->days($campaign) : 1;
        $perDay = (float) $campaign->budget / max($days, 1);

        $tooLow = $lifetime
            ? sprintf(
                'lifetime budget of %.2f over %d days is %.2f a day, below %s\'s %.2f minimum',
                $campaign->budget, $days, $perDay, $rules->name(), $floor,
            )
            : sprintf('daily budget of %.2f is below %s\'s %.2f minimum', $campaign->budget, $rules->name(), $floor);

        $tooHigh = $lifetime
            ? sprintf(
                'lifetime budget of %.2f over %d days is %.2f a day, above the %.2f ceiling this product allows',
                $campaign->budget, $days, $perDay, $ceiling,
            )
            : sprintf('daily budget of %.2f is above the %.2f ceiling this product allows', $campaign->budget, $ceiling);

        return [
            $perDay < $floor ? $tooLow : null,
            $perDay > $ceiling ? $tooHigh : null,
        ];
    }

    /**
     * What every platform together would spend, against what was agreed once.
     *
     * The per-campaign budget check above is blind to this. Each share can sit
     * happily between the floor and the ceiling while the shares together spend
     * several times the number the buyer actually said. Seen on 21 Sep: a brief
     * total of 5.00 a day with two campaigns holding 10.00 each, and nothing
     * anywhere reported a problem, so publishing both would have spent four
     * times the agreed amount.
     *
     * Only over-allocation is a problem. Spending less than the total is a
     * choice, and holding some back is a normal one.
     *
     * Summed through ownBudget() on purpose: {@see ResolvesFromBrief} makes
     * $campaign->budget fall back to the brief's total, so summing the accessor
     * would count the total once per platform and call an unsplit budget
     * perfectly balanced. ownBudget() asks whichever object holds this
     * campaign's money - its ad set, or the campaign itself under Advantage
     * campaign budget - and never the brief.
     *
     * @return list<string|null>
     */
    private function share(Campaign $campaign): array
    {
        $brief = $campaign->brief;

        if (! $brief || (float) $brief->budget <= 0) {
            return [];
        }

        $siblings = $brief->campaigns()->get();

        // One platform spending the whole total is the total, not a share.
        if ($siblings->count() < 2) {
            return [];
        }

        // A lifetime total and a daily rate are different units, so comparing
        // them would produce a confident wrong number. Say nothing instead.
        $mode = $brief->budget_mode ?: 'daily';

        if ($siblings->contains(fn (Campaign $c): bool => $c->budgetMode() !== $mode)) {
            return [];
        }

        $label = $mode === 'lifetime' ? 'lifetime' : 'a day';

        if ($brief->needsBudgetSplit()) {
            return [sprintf(
                'the %.2f %s total has not been split across the %d platforms yet, '
                .'so each would spend it in full',
                $brief->budget, $label, $siblings->count(),
            )];
        }

        $total = (float) $brief->budget;
        $sum = (float) $siblings->sum(fn (Campaign $c): float => (float) $c->ownBudget());

        // Compared in minor units. Three shares of a tenth of a penny each are
        // not an overspend, and float addition should not invent one.
        if (round($sum * 100) <= round($total * 100)) {
            return [];
        }

        return [sprintf(
            'the shares across %d platforms add up to %.2f %s, over the %.2f %s total set for this brief',
            $siblings->count(), $sum, $label, $total, $label,
        )];
    }

    /** How long a lifetime budget has to last, counted from the start or from now. */
    private function days(Campaign $campaign): int
    {
        $from = $campaign->starts_at && $campaign->starts_at->isFuture() ? $campaign->starts_at : now();

        return max(1, (int) ceil($from->diffInDays($campaign->ends_at, absolute: false)));
    }

    /**
     * A campaign that ends before it starts, or in the past, is accepted by the
     * platform's own validation only sometimes, and rejected on create after
     * the campaign already exists.
     *
     * @return list<string|null>
     */
    /**
     * Categories the platform does not recognise.
     *
     * @return list<string>
     */
    private function unknownCategories(Campaign $campaign, $rules): array
    {
        return array_values(array_diff(
            (array) ($campaign->special_ad_categories ?? []),
            $rules->specialAdCategories(),
        ));
    }

    private function schedule(Campaign $campaign): array
    {
        return [
            $campaign->starts_at && $campaign->ends_at && $campaign->ends_at->lte($campaign->starts_at)
                ? 'end date must be after the start date' : null,

            $campaign->ends_at && $campaign->ends_at->isPast()
                ? 'end date is in the past' : null,
        ];
    }

    /** @return list<string|null> */
    private function audience(Campaign $campaign): array
    {
        $rules = $this->platforms->for($campaign);
        $chosen = (array) ($campaign->placements ?? []);

        // A placement the objective cannot use is refused at the ad set, after
        // the campaign already exists.
        $impossible = filled($campaign->objective)
            ? array_diff($chosen, $rules->placementsFor($campaign->objective))
            : [];
        $hasImportedGeography = $campaign->isPublished() && (
            ($campaign->platform === 'meta' && filled($campaign->locations['meta_geo_locations'] ?? null))
            || ($campaign->platform === 'google' && (
                collect($campaign->locations['google_location_criteria'] ?? [])
                    ->contains(fn (array $criterion): bool => ! $criterion['negative'])
                || filled($campaign->locations['google_proximity_criteria'] ?? null)
            ))
        );

        return [
            $this->selections->countries($campaign) === []
                && ! $hasImportedGeography
                    ? 'target country not set' : null,
            ...$this->selections->locationProblems($campaign),

            $impossible !== [] ? sprintf(
                '%s cannot run on %s. Supported for this objective: %s',
                $campaign->objective,
                implode(', ', $impossible),
                implode(', ', $rules->placementsFor($campaign->objective)),
            ) : null,

            // An Instagram placement with no Instagram account runs the ads
            // under the Facebook Page's name and picture. Meta allows it, so
            // nothing fails; it simply does not look like the brand. Empty
            // string is the advertiser having been asked and having none.
            in_array('instagram', $chosen, true) && $campaign->instagram_account_id === null
                ? 'Instagram is a chosen placement but no Instagram account has been picked, '
                    .'so those ads would run under the Facebook Page' : null,
        ];
    }

    /**
     * Where the click actually lands.
     *
     * Both of these are part of the creative on Meta, so neither can be fixed
     * after publish without building a new creative and a new ad.
     *
     * @return list<string|null>
     */
    private function destination(Campaign $campaign): array
    {
        return [
            // Shape only. A malformed query string breaks every click on the
            // ad, and "utm_source=facebook&&" looks fine to a human.
            $campaign->utm !== null && $campaign->utm !== ''
            && ! preg_match('/^[^=&\s]+=[^&]*(&[^=&\s]+=[^&]*)*$/', $campaign->utm)
                ? 'click tracking is not a valid query string, so the destination URL would be broken' : null,

            // Only meaningful once there is an objective to disagree with. An
            // adopted campaign can carry an optimisation goal read off its ad
            // set while Meta returned no objective, and without this the reason
            // reads "does not match the  objective" alongside "objective not set".
            filled($campaign->objective)
            && $campaign->optimization_goal !== null
            && $campaign->optimization_goal !== $this->platforms->for($campaign)->optimizationGoal((string) $campaign->objective)
                ? sprintf(
                    'optimisation goal %s does not match the %s objective, which Meta refuses as "conversion event unavailable"',
                    $campaign->optimization_goal,
                    $campaign->objective,
                ) : null,
        ];
    }

    /** @return list<string|null> */
    private function ads(Campaign $campaign, $rules): array
    {
        $ads = $campaign->ads()->with('asset.platformRefs')->get();
        $limit = (int) config('platforms.guardrails.max_ads_per_publish');

        // Counted as ads the platform will create, not as rows. Google builds
        // one responsive search ad out of the headlines of every row and takes
        // fifteen of them, so counting rows held it to five headlines against a
        // cap aimed at how much one approval may create - and one approval
        // creates one ad there however many headlines it carries.
        $creating = $rules->buildsOneAdFromEveryVariation() ? min(1, $ads->count()) : $ads->count();

        $problems = [
            $ads->isEmpty() ? 'no ad copy written yet' : null,
            $creating > $limit
                ? sprintf('%d ads, but at most %d may be published at once', $creating, $limit)
                : null,
        ];

        foreach ($ads as $index => $ad) {
            $problems = [...$problems, ...$this->oneAd(
                $campaign,
                $ad,
                $rules,
                $ads->count() > 1 ? 'ad '.($index + 1).': ' : '',
            )];
        }

        return $problems;
    }

    /**
     * What has to be true of a single ad.
     *
     * Pulled out of ads() so that adding ads to a live campaign asks exactly the
     * same questions rather than a copy of them. A second list would be a second
     * thing to keep in step, and the one that drifted would be the one guarding
     * the ads nobody watched go out.
     *
     * @param  CampaignAd  $ad
     * @param  string  $label  which ad this is, when there is more than one
     * @return list<string|null>
     */
    private function oneAd(Campaign $campaign, $ad, $rules, string $label): array
    {
        $problems = [
            blank($ad->headline) ? $label.'headline missing' : null,
            blank($ad->primary_text) ? $label.'primary text missing' : null,
        ];

        // Over the limit the platform does not refuse the ad, it truncates
        // it and runs it. Nobody finds out until someone reads a live ad
        // and sees a headline ending mid-word.
        foreach ($rules->copyLimits() as $field => $longest) {
            $value = (string) $ad->getAttribute($field);

            $problems[] = mb_strlen($value) > $longest ? sprintf(
                '%s%s is %d characters, over %s\'s %d limit. %s shortens it rather than refusing it',
                $label,
                str_replace('_', ' ', $field),
                mb_strlen($value),
                $rules->name(),
                $longest,
                $rules->name(),
            ) : null;
        }

        $problems[] = match (true) {
            // A platform with no call to action field has nothing to be
            // missing. Google writes the button itself from the final URL
            // and the copy, so demanding one here was a block no answer
            // could clear, the same shape as asking Google for a Page.
            $rules->callsToAction() === [] => null,
            blank($ad->cta) => $label.'call to action missing',
            ! in_array($ad->cta, $rules->callsToAction(), true) => sprintf(
                '%s%s is not a call to action %s accepts',
                $label,
                $ad->cta,
                $rules->name(),
            ),
            default => null,
        };

        // Only where an ad is built around one. A Google responsive search
        // ad is headlines, descriptions and a URL, with no asset anywhere,
        // so this was a block that no upload could ever clear.
        $problems[] = ! $rules->requiresCreativeAsset($campaign) || $this->assetReady($campaign, $ad)
            ? null : $label.'creative not uploaded to the platform yet';

        return $problems;
    }

    /** @return list<string|null> */
    private function account(Campaign $campaign, $rules): array
    {
        return [
            blank($campaign->ad_account_id) ? 'ad account not verified' : null,
            $rules->requiresPage() && blank($campaign->page_id) ? 'Page not selected' : null,
            $campaign->objective
            && $rules->requiresPixel($campaign->objective)
            && blank($campaign->pixel_id)
                ? 'pixel not selected, and a conversion objective requires one' : null,
        ];
    }

    /**
     * A value guessed after a lookup failed must be confirmed before it can
     * spend money. This is the check that makes provenance worth recording.
     *
     * @return list<string>
     */
    private function provenance(Campaign $campaign): array
    {
        return collect($this->workspace->unconfirmed($campaign))
            // A generated name is recorded as a fallback so the panel can show
            // that nobody chose it, but it cannot spend money wrongly, and the
            // agent is told never to ask for one. Blocking on it left the
            // guided flow with a step no click could clear: publishing refused
            // until the name was confirmed, and nothing ever asked.
            //
            // The conversion event is exempt for the same reason. When the
            // pixel has fired nothing there is no list to choose from, so the
            // objective's default is recorded as a guess - honestly, because
            // the panel should show that nobody picked it - and then nothing
            // can ever clear it: the step counts as done the moment the column
            // is filled, so the flow never asks again, and there is nothing to
            // offer if it did. Blocking here would refuse every campaign whose
            // pixel is new, which is exactly the campaigns most likely to be
            // someone's first.
            ->reject(fn (string $field): bool => in_array($field, ['name', 'conversion_event'], true))
            ->map(fn (string $field): string => str_replace('_', ' ', $field).' was guessed and needs confirming')
            ->values()
            ->all();
    }

    /**
     * Whether this ad's creative has reached the platform.
     *
     * An ad with no asset at all used to pass on LinkedIn. That is the one case
     * this check exists for, and LinkedInRules::requiresCreativeAsset() returns
     * true, so the exemption only ever fired where the answer should have been
     * no. The publisher then had nothing to sponsor and built a reference out
     * of a database row id to fill the gap.
     *
     * Whether a platform needs a creative at all is the platform's answer, and
     * the caller already asks requiresCreativeAsset() before reaching here.
     */
    private function assetReady(Campaign $campaign, $ad): bool
    {
        if (! $ad->asset || ! $campaign->ad_account_id) {
            return false;
        }

        // Where the creative is created during the publish rather than before
        // it, there is no reference to look for and readiness is whether the
        // file is there to send. Asking for a reference here is what blocked
        // Google Display and Performance Max: the only paths that write one
        // are the Meta and LinkedIn uploads, so the gate asked for something
        // no Google campaign could ever have, and said "creative not uploaded
        // to the platform yet" about a file sitting ready on disk.
        if (! $this->platforms->for($campaign->platform)->uploadsCreativeBeforePublish()) {
            return ! AssetOriginal::isMissing($ad->asset);
        }

        return (bool) $ad->asset->refFor($campaign->platform, $campaign->ad_account_id)?->reference();
    }
}
