<?php

namespace App\Campaigns;

use App\Campaigns\Publishing\AddsToLiveCampaigns;
use App\Campaigns\Publishing\PlatformPublisher;
use App\Campaigns\Publishing\Publishers;
use App\Campaigns\Targeting\CountryCatalog;
use App\Campaigns\Targeting\GoogleUserListSelections;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\CampaignAdSet;
use App\Models\Decision;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use RuntimeException;
use Throwable;

/**
 * The only class that creates anything on a live ad account.
 *
 * The agent cannot reach it. A proposal is recorded first, a human approves,
 * and only then does anything reach the platform. Everything is created paused,
 * and a failure part-way through removes whatever was already made, so an
 * account is never left holding half a campaign.
 *
 * Everything here is true whatever the platform. The payload itself is not, so
 * that part lives behind {@see PlatformPublisher} and a new platform
 * inherits the decision, the approval, the gate re-check, the double publish
 * guard and the rollback by existing rather than by remembering to.
 */
class Publisher
{
    public function __construct(
        private readonly PublishGate $gate,
        private readonly PendingChanges $pending,
        private readonly Publishers $publishers,
        private readonly TargetingSelections $selections,
        private readonly CountryCatalog $countries,
        private readonly SearchKeywordSelections $searchKeywords,
        private readonly GoogleUserListSelections $userLists,
    ) {}

    /** Record the intent. Nothing happens on the platform until approve() runs. */
    public function propose(Campaign $campaign, string $actor): Decision
    {
        $blocking = $this->gate->check($campaign);
        $params = $campaign->only([
            'name', 'platform', 'objective', 'budget', 'budget_level', 'budget_mode',
            'ad_account_id', 'page_id', 'pixel_id',
        ]);

        if ($campaign->platform === 'meta' && $blocking === []) {
            $params['meta_targeting'] = $this->metaTargetingReview($campaign);
        }

        if ($campaign->platform === 'google' && $blocking === []) {
            $params['google_targeting'] = $this->googleTargetingReview($campaign);
        }

        if ($campaign->platform === 'linkedin' && $blocking === []) {
            $params['linkedin_targeting'] = $this->linkedinTargetingReview($campaign);
        }

        if ($blocking === [] && in_array($campaign->platform, ['meta', 'google', 'linkedin'], true)) {
            try {
                $params['country_targeting'] = $this->countryTargetingReview($campaign);
            } catch (Throwable $exception) {
                $blocking[] = 'country targeting could not be verified: '.$exception->getMessage();
            }
        }

        return Decision::create([
            'origin' => 'agent',
            'action' => 'publish_campaign',
            'subject_type' => 'campaign',
            'subject_id' => (string) $campaign->id,
            'params' => $params,
            'evidence' => ['blocking' => $blocking],
            'state' => $blocking ? 'blocked' : 'proposed',
            'actor' => $actor,
            'reason' => $blocking ? 'not ready: '.implode('; ', $blocking) : null,
        ]);
    }

    /**
     * Carry out an approved proposal: campaign, ad set, then one creative and
     * one ad per copy variation.
     */
    public function approve(Decision $decision, string $actor): Decision
    {
        $campaign = Campaign::findOrFail((int) $decision->subject_id);

        // Refuse a second publish outright.
        //
        // Two routes reach this: the chat tool and the panel button. Publishing
        // from one leaves the other's page showing a stale, still-enabled
        // button, and a second run created a whole second campaign on the
        // account while external_ids kept only the last one, orphaning the
        // first. The guard belongs here rather than in either caller, because
        // neither can see what the other did.
        if ($campaign->external_campaign_id) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => 'already published as '.$campaign->external_campaign_id,
                'result' => $campaign->external_ids,
            ]);
        }

        // Re-check now, not just at proposal time. A campaign can change
        // between the two, and approving a stale summary must not publish a
        // different campaign from the one that was shown.
        if ($blocking = $this->gate->check($campaign)) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => 'no longer ready: '.implode('; ', $blocking),
            ]);
        }

        if (in_array($campaign->platform, ['meta', 'google', 'linkedin'], true)) {
            try {
                $reviewedCountries = $this->countryTargetingReview($campaign);
            } catch (Throwable $exception) {
                return tap($decision)->update([
                    'state' => 'blocked',
                    'reason' => 'country targeting could not be verified: '.$exception->getMessage(),
                ]);
            }

            if (! $this->reviewsMatch($decision->params['country_targeting'] ?? null, $reviewedCountries)) {
                return tap($decision)->update([
                    'state' => 'blocked',
                    'reason' => 'Country targeting or provider mappings changed since review. Review and approve the current selection again.',
                ]);
            }
        }

        if ($campaign->platform === 'meta'
            && ! $this->reviewsMatch($decision->params['meta_targeting'] ?? null, $this->metaTargetingReview($campaign))) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => 'Meta location or audience targeting changed since review. Review and approve the current selection again.',
            ]);
        }

        if ($campaign->platform === 'google'
            && ! $this->reviewsMatch($decision->params['google_targeting'] ?? null, $this->googleTargetingReview($campaign))) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => 'Google location or audience targeting changed since review. Review and approve the current selection again.',
            ]);
        }

        if ($campaign->platform === 'linkedin'
            && ! $this->reviewsMatch($decision->params['linkedin_targeting'] ?? null, $this->linkedinTargetingReview($campaign))) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => 'LinkedIn location or audience targeting changed since review. Review and approve the current selection again.',
            ]);
        }

        // Which platform's payload to build. A platform with no publisher is
        // refused by name rather than by exception: "not implemented for
        // taboola" is something a user can act on.
        //
        // This is the second lock, after the gate. The gate is a list of reasons
        // that a rules class can stop supplying, and by the time a campaign for
        // an unimplemented platform reached the API the damage would be a real
        // campaign on a real account.
        $platform = $this->publishers->for($campaign->platform);

        if ($platform === null) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => sprintf(
                    'publishing is not implemented for [%s] yet',
                    $campaign->platform,
                ),
            ]);
        }

        $claimed = Campaign::query()
            ->whereKey($campaign->id)
            ->whereNull('external_campaign_id')
            ->where('status', $campaign->status)
            ->where('status', '!=', 'publishing')
            ->update(['status' => 'publishing', 'last_error' => null]);

        if ($claimed !== 1) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => 'This campaign changed or another publication is already in progress. Review it before retrying.',
            ]);
        }

        $campaign->refresh();

        $created = [];

        try {
            $created = $platform->create($campaign, $actor, $created);

            $campaign->update([
                'status' => 'published',
                'external_campaign_id' => $created['campaign_id'],
                'external_ids' => $created,
            ]);

            // Record what the platform now holds, so any later edit can be
            // compared against it rather than silently diverging.
            $campaign->refresh()->update([
                'published_state' => $this->pending->snapshot($campaign),
                'last_synced_at' => now(),
            ]);

            return tap($decision)->update([
                'state' => 'applied',
                'actor' => $actor,
                'result' => $created,
                'applied_at' => now(),
            ]);
        } catch (Throwable $e) {
            // What the rollback could not take back is recorded on the decision
            // rather than only logged, so the caller can tell the buyer what is
            // still on their account instead of assuring them it is gone. On 5
            // Oct a production publish left campaign 120249729445410510 on
            // AutoAutomotive - Graph answered #10 on an MCP-created draft - and
            // the chat reported a clean rollback.
            $left = $platform->rollBack($campaign, $created, $actor);

            // The campaign is recorded when the rollback could not take it back.
            //
            // external_campaign_id is what the double publish guard above reads,
            // and it was only ever written on success. So a publish that created
            // the campaign and then failed - and whose rollback could not remove
            // it, which is the ordinary outcome on an MCP draft Graph answers #10
            // for - left a live campaign on the account with nothing here
            // pointing at it. The guard could not fire, the buyer saw a failure
            // and approved again, and Meta refused the second publish with "ad
            // set ... is already publishing from an earlier request".
            //
            // This does make isPublished() true, which is filled(external_
            // campaign_id), and that is the point rather than a side effect: the
            // campaign really is on the account, so delete_entity,
            // set_entity_status and list_campaign_structure should all be able
            // to reach it. Before this they refused with "this campaign has not
            // been published", which was false and left the orphan unreachable
            // from the chat that made it. status stays failed and last_error
            // still says what broke, so nothing reports it as a success.
            $campaignId = $created['campaign_id'] ?? null;
            $stillThere = filled($campaignId) && in_array((string) $campaignId, array_map('strval', $left), true);

            $campaign->update(array_filter([
                'status' => 'failed',
                'last_error' => $e->getMessage(),
                'external_campaign_id' => $stillThere ? (string) $campaignId : null,
                'external_ids' => $stillThere ? $created : null,
            ], static fn (mixed $value): bool => $value !== null));

            if (str_contains($e->getMessage(), '3858634')) {
                $meta = (array) ($campaign->fresh()->meta ?? []);
                unset(
                    $meta['verified_advertiser_status'],
                    $meta['dsa_beneficiary'],
                    $meta['dsa_payor'],
                    $meta['universal_beneficiary'],
                    $meta['universal_payer'],
                    $meta['regional_regulated_categories'],
                );
                $meta['verified_advertiser_required'] = true;
                $campaign->forceFill(['meta' => $meta])->save();
            }
            $decision->update([
                'state' => 'blocked',
                'reason' => $e->getMessage(),
                'result' => array_filter([
                    'rolled_back' => $created,
                    'left_behind' => $left ?: null,
                ]),
            ]);

            Log::error('Campaign publish failed', [
                'campaign' => $campaign->id,
                'error' => $e->getMessage(),
                'left_behind' => $left,
            ]);

            throw $e;
        }
    }

    /** @return array{revision: int, geo_locations: array<string, mixed>, places: list<array<string, mixed>>, shared_places: list<array<string, mixed>>, place_intent_mode: string, audience: array<string, mixed>, placements: array<int, string>} */
    private function metaTargetingReview(Campaign $campaign): array
    {
        return [
            'revision' => $campaign->targetingSet()->value('revision') ?? 0,
            'geo_locations' => $this->selections->metaGeoLocations($campaign),
            'places' => $this->selections->reviewedCampaignPlaces($campaign),
            'shared_places' => $this->selections->sharedPlaceIntents($campaign),
            'place_intent_mode' => (string) ($campaign->targetingSet()->first()?->options['place_intent_mode'] ?? 'inherit'),
            'audience' => (array) ($campaign->audience ?? []),
            'placements' => (array) ($campaign->placements ?? []),
        ];
    }

    /** @return array{revision: int, locations: array{countries: list<string>, geo_targets: list<string>}, places: list<array<string, mixed>>, shared_places: list<array<string, mixed>>, place_intent_mode: string, audience: array<string, mixed>, placements: array<int, string>} */
    private function googleTargetingReview(Campaign $campaign): array
    {
        return [
            'revision' => $campaign->targetingSet()->value('revision') ?? 0,
            'locations' => $this->selections->googleGeoTargets($campaign),
            'positive_geo_target_type' => $this->selections->googlePresenceMode($campaign),
            'search_keywords' => $this->searchKeywords->criteria($campaign),
            'user_lists' => $this->userLists->selected($campaign),
            'places' => $this->selections->reviewedCampaignPlaces($campaign),
            'shared_places' => $this->selections->sharedPlaceIntents($campaign),
            'place_intent_mode' => (string) ($campaign->targetingSet()->first()?->options['place_intent_mode'] ?? 'inherit'),
            'audience' => (array) ($campaign->audience ?? []),
            'placements' => (array) ($campaign->placements ?? []),
        ];
    }

    /** @return array{revision: int, dma_urns: list<string>, places: list<array<string, mixed>>, audience: array<string, mixed>, placements: array<int, string>} */
    private function linkedinTargetingReview(Campaign $campaign): array
    {
        return [
            'revision' => $campaign->targetingSet()->value('revision') ?? 0,
            'dma_urns' => $this->selections->linkedinDmaUrns($campaign),
            'places' => $this->selections->reviewedCampaignPlaces($campaign),
            'audience' => (array) ($campaign->audience ?? []),
            'placements' => (array) ($campaign->placements ?? []),
        ];
    }

    /** Ignore JSON object key order while retaining list order and scalar types. */
    private function reviewsMatch(mixed $reviewed, array $current): bool
    {
        return is_array($reviewed)
            && $this->normaliseReview($reviewed) === $this->normaliseReview($current);
    }

    /** @param array<array-key, mixed> $review
     * @return array<array-key, mixed>
     */
    private function normaliseReview(array $review): array
    {
        foreach ($review as $key => $value) {
            if (is_array($value)) {
                $review[$key] = $this->normaliseReview($value);
            }
        }

        if (! array_is_list($review)) {
            ksort($review);
        }

        return $review;
    }

    /** @return array{platform: string, account_id: string, revision: int, codes: list<string>, mappings: array<string, array{mapping_id: int, external_id: string}>} */
    private function countryTargetingReview(Campaign $campaign): array
    {
        $codes = $this->selections->countries($campaign);

        return [
            'platform' => $campaign->platform,
            'account_id' => (string) $campaign->ad_account_id,
            'revision' => (int) ($campaign->targetingSet()->value('revision') ?? 0),
            'codes' => $codes,
            'mappings' => $this->countries->reviewedMappings($campaign->platform, $codes, $campaign->ad_account_id),
        ];
    }

    /**
     * Propose adding an ad set to a campaign that is already live.
     *
     * Its own decision, like publishing and activation, and for the same
     * reason: this creates objects on a real account under a campaign that may
     * already be spending. The agent may ask; only an approval makes it happen.
     *
     * @return Decision the proposal, blocked when the gate says so
     */
    public function proposeAdSet(CampaignAdSet $adSet, string $actor): Decision
    {
        $blocking = $this->adSetProblems($adSet);

        return Decision::create([
            'origin' => 'agent',
            'action' => 'add_ad_set',
            'subject_type' => 'campaign_ad_set',
            'subject_id' => (string) $adSet->id,
            'params' => [
                'campaign_id' => $adSet->campaign_id,
                'external_campaign_id' => $adSet->campaign?->external_campaign_id,
                ...$adSet->only(['name', 'position', 'budget', 'budget_mode', 'locations', 'placements']),
            ],
            'evidence' => ['blocking' => $blocking],
            'state' => $blocking ? 'blocked' : 'proposed',
            'actor' => $actor,
            'reason' => $blocking ? 'cannot be added: '.implode('; ', $blocking) : null,
        ]);
    }

    /**
     * Carry out an approved ad set addition.
     *
     * Re-checked here as well as at proposal, for the same reason publishing is:
     * the campaign may have been paused, the ad set edited, or the account
     * removed from the allowlist between the two.
     */
    public function approveAdSet(Decision $decision, string $actor): Decision
    {
        $adSet = CampaignAdSet::findOrFail((int) $decision->subject_id);

        if ($blocking = $this->adSetProblems($adSet)) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => 'cannot be added: '.implode('; ', $blocking),
            ]);
        }

        $platform = $this->addsToLiveCampaigns($adSet->campaign);

        if (! $platform instanceof AddsToLiveCampaigns) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => sprintf(
                    'adding an ad set to a live campaign is not implemented for [%s] yet',
                    $adSet->campaign?->platform,
                ),
            ]);
        }

        try {
            $created = $platform->addAdSet($adSet, $actor);

            return tap($decision)->update([
                'state' => 'applied',
                'actor' => $actor,
                'result' => $created,
                'applied_at' => now(),
            ]);
        } catch (Throwable $e) {
            // The publisher has already undone its own work and marked the row
            // failed. Nothing is rolled back here, because the campaign above
            // is live and is not this failure's to remove.
            $decision->update(['state' => 'blocked', 'reason' => $e->getMessage()]);

            Log::error('Adding an ad set failed', ['ad_set' => $adSet->id, 'error' => $e->getMessage()]);

            throw $e;
        }
    }

    /**
     * Propose adding ads to an ad set that is already live.
     *
     * The ads are the ones already written and still waiting - a draft row on a
     * published campaign - rather than anything created here. Which ad set they
     * go into is the caller's to decide; it defaults to the first.
     */
    public function proposeAds(CampaignAdSet $adSet, string $actor): Decision
    {
        $ads = $this->adsAwaitingPublish($adSet);
        $blocking = $this->addAdsProblems($adSet, $ads);

        return Decision::create([
            'origin' => 'agent',
            'action' => 'add_ads',
            'subject_type' => 'campaign_ad_set',
            'subject_id' => (string) $adSet->id,
            'params' => [
                'campaign_id' => $adSet->campaign_id,
                'ad_set' => $adSet->name,
                'ad_ids' => $ads->pluck('id')->all(),
                'headlines' => $ads->pluck('headline')->all(),
            ],
            'evidence' => ['blocking' => $blocking],
            'state' => $blocking ? 'blocked' : 'proposed',
            'actor' => $actor,
            'reason' => $blocking ? 'cannot be added: '.implode('; ', $blocking) : null,
        ]);
    }

    /** Carry out an approved ad addition, re-checked. */
    public function approveAds(Decision $decision, string $actor): Decision
    {
        $adSet = CampaignAdSet::findOrFail((int) $decision->subject_id);

        // Re-read rather than taken from the decision. An ad added or removed
        // between the proposal and the approval would otherwise be published or
        // skipped on the strength of a stale list.
        $ads = $this->adsAwaitingPublish($adSet);

        if ($blocking = $this->addAdsProblems($adSet, $ads)) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => 'cannot be added: '.implode('; ', $blocking),
            ]);
        }

        $platform = $this->addsToLiveCampaigns($adSet->campaign);

        if (! $platform instanceof AddsToLiveCampaigns) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => sprintf(
                    'adding ads to a live campaign is not implemented for [%s] yet',
                    $adSet->campaign?->platform,
                ),
            ]);
        }

        try {
            $created = $platform->addAds($adSet, $ads, $actor);

            // The campaign's ads changed, so the fingerprint the pending-changes
            // comparison holds has to move with them. Without this, the ads just
            // published read as an unsent local edit for ever.
            $campaign = $adSet->campaign->refresh();
            $campaign->update([
                'published_state' => $this->pending->snapshot($campaign),
                'last_synced_at' => now(),
            ]);

            return tap($decision)->update([
                'state' => 'applied',
                'actor' => $actor,
                'result' => $created,
                'applied_at' => now(),
            ]);
        } catch (Throwable $e) {
            $decision->update(['state' => 'blocked', 'reason' => $e->getMessage()]);

            Log::error('Adding ads failed', ['ad_set' => $adSet->id, 'error' => $e->getMessage()]);

            throw $e;
        }
    }

    /**
     * The ads written for this ad set that are not on the platform yet.
     *
     * Public because the chat asks before proposing: a tool that records a
     * decision in order to discover there was nothing to publish leaves a
     * blocked row behind every question.
     *
     * ad_set_id is null on ads written before ad sets were rows, and those
     * belong to the first ad set.
     *
     * @return Collection<int, CampaignAd>
     */
    public function adsAwaitingPublish(CampaignAdSet $adSet): Collection
    {
        return $adSet->campaign->ads()
            ->whereNull('external_ad_id')
            ->where(function ($query) use ($adSet): void {
                $query->where('ad_set_id', $adSet->id);

                if ($adSet->is($adSet->campaign->primaryAdSet)) {
                    $query->orWhereNull('ad_set_id');
                }
            })
            ->orderBy('id')
            ->get();
    }

    /**
     * Why these ads cannot be added, if they cannot.
     *
     * @param  Collection<int, CampaignAd>  $ads
     * @return list<string>
     */
    public function addAdsProblems(CampaignAdSet $adSet, Collection $ads): array
    {
        $campaign = $adSet->campaign;

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

        if (! $campaign->isPublished()) {
            return [
                'the campaign has not been published yet, so its ads go out when it is published',
            ];
        }

        if (! $adSet->isPublished()) {
            return [
                'the ad set these would go into is not on the platform yet, so there is nothing to add them to',
            ];
        }

        if ($ads->isEmpty()) {
            return ['every ad written for this ad set is already on the platform'];
        }

        return $this->gate->adsReadyToAdd($campaign, $ads);
    }

    /**
     * Why this ad set cannot be added, if it cannot.
     *
     * @return list<string>
     */
    public function adSetProblems(CampaignAdSet $adSet): array
    {
        return $this->gate->adSetProblems($adSet);
    }

    /**
     * The platform's publisher, when it can add to a live campaign.
     *
     * Returns null for a platform with no publisher at all and for one whose
     * publisher cannot do this yet, so the two are refused by name in the
     * callers rather than by exception here.
     */
    private function addsToLiveCampaigns(?Campaign $campaign): ?PlatformPublisher
    {
        $platform = $campaign === null ? null : $this->publishers->for($campaign->platform);

        return $platform instanceof AddsToLiveCampaigns ? $platform : null;
    }

    /**
     * Propose starting a campaign that is already built.
     *
     * Its own decision, separate from publishing, because publishing and spending
     * are separate acts. Everything this product builds is created paused - Meta
     * and Google PAUSED at every level, LinkedIn DRAFT - and it stays that way
     * until a buyer asks for it in the chat and approves this.
     *
     * Approving a publish does not pre-authorise this. That was the choice worth
     * making deliberately: the alternative is that one click both creates a
     * campaign and starts it spending, and the parking would be decoration.
     */
    public function proposeActivation(Campaign $campaign, string $actor): Decision
    {
        $blocking = $this->activationProblems($campaign);

        return Decision::create([
            'origin' => 'agent',
            'action' => 'activate_campaign',
            'subject_type' => 'campaign',
            'subject_id' => (string) $campaign->id,
            'params' => $campaign->only(['name', 'platform', 'budget', 'budget_mode', 'ad_account_id']),
            'evidence' => ['blocking' => $blocking],
            'state' => $blocking ? 'blocked' : 'proposed',
            'actor' => $actor,
            'reason' => $blocking ? 'cannot be started: '.implode('; ', $blocking) : null,
        ]);
    }

    /**
     * Carry out an approved activation: the whole tree, then the local record.
     *
     * Re-checked here as well as at proposal, for the same reason publishing is: a
     * campaign can change between the two, and approving a minute-old summary must
     * not start something else.
     */
    public function activate(Decision $decision, string $actor): Decision
    {
        $campaign = Campaign::findOrFail((int) $decision->subject_id);

        if ($blocking = $this->activationProblems($campaign)) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => 'cannot be started: '.implode('; ', $blocking),
            ]);
        }

        $platform = $this->publishers->for($campaign->platform);

        if ($platform === null) {
            return tap($decision)->update([
                'state' => 'blocked',
                'reason' => sprintf('starting a campaign is not implemented for [%s] yet', $campaign->platform),
            ]);
        }

        try {
            $platform->activate($campaign, $actor);

            // Written after the platform agreed, never before. A campaign recorded
            // as running that is not is worse than the reverse: the reverse shows
            // up as a buyer asking why nothing is spending, and this shows up as
            // nobody asking anything.
            $campaign->update(['activated_at' => now()]);

            return tap($decision)->update([
                'state' => 'applied',
                'actor' => $actor,
                'applied_at' => now(),
                'result' => ['activated_at' => $campaign->fresh()->activated_at?->toIso8601String()],
            ]);
        } catch (Throwable $e) {
            // Deliberately not rolled back. Activation walks from the deepest
            // object up, so a failure leaves the campaign itself still paused and
            // nothing spending; trying to put the lower levels back would be a
            // second set of calls against a platform that has just failed one.
            $campaign->update(['last_error' => $e->getMessage()]);

            $decision->update(['state' => 'blocked', 'reason' => $e->getMessage()]);

            Log::error('Campaign activation failed', ['campaign' => $campaign->id, 'error' => $e->getMessage()]);

            throw $e;
        }
    }

    /**
     * Stop a running campaign.
     *
     * Not gated behind an approval. Approvals exist to stand between a buyer and
     * spending their money, and this is the direction that stops it - asking
     * somebody to confirm twice before they can halt a campaign is a way to lose
     * money, not to protect it.
     *
     * Published, not running: the condition is deliberately the weaker one.
     *
     * This asked isRunning(), which is isPublished() && activated_at !== null,
     * and activated_at is written by exactly one place - activate(), below. An
     * adopted campaign never goes through it: CampaignImporter writes
     * external_campaign_id and status=published and never touches activated_at.
     * So every campaign this product did not itself start read as "not running"
     * and returned here without a single call to the platform, however live it
     * was. Adopting somebody's running campaign and asking the chat to stop it
     * is the whole point of open_campaign, and it was the one case that could
     * not work.
     *
     * Pausing something already paused is idempotent at every platform - all
     * three implementations write one campaign-level status - so the early
     * return was only ever saving a redundant call, and it was paying for that
     * with the possibility of leaving a campaign spending. One call is the
     * cheaper mistake.
     */
    public function pause(Campaign $campaign, string $actor): void
    {
        if (! $campaign->isPublished()) {
            return;
        }

        $platform = $this->publishers->for($campaign->platform)
            ?? throw new RuntimeException(sprintf(
                'pausing is not implemented for [%s] yet',
                $campaign->platform,
            ));

        $platform->pause($campaign, $actor);

        $campaign->update(['activated_at' => null]);
    }

    /**
     * Whether the platform says this campaign is live. Null when it cannot say.
     *
     * The one place that asks, so every caller gets the same fallback and the
     * same failure behaviour. A platform with no publisher is null rather than
     * false for the same reason LinkedIn's own answer is: false and "cannot tell"
     * lead to opposite decisions, and conflating them is what offers to start a
     * campaign that is already spending.
     *
     * Never call this from anything that renders per turn - it is a platform
     * read and it counts against the hourly call budget.
     */
    public function isLiveOnPlatform(Campaign $campaign, string $actor): ?bool
    {
        if (! $campaign->isPublished()) {
            return null;
        }

        return $this->publishers->for($campaign->platform)?->isLive($campaign, $actor);
    }

    /**
     * Why this campaign cannot be started, if it cannot.
     *
     * Public because the chat asks before proposing anything: a tool that creates a
     * decision row in order to find out whether it could have is leaving a trail of
     * blocked decisions behind every question.
     *
     * @return list<string>
     */
    public function activationProblems(Campaign $campaign, string $actor = 'activation check'): array
    {
        $problems = [];

        if (! $campaign->isPublished()) {
            $problems[] = 'it has not been published yet, so there is nothing on the platform to start';
        }

        // The platform first, local state only when it cannot be asked.
        //
        // activated_at records that this product started a campaign, which an
        // adopted one never did, so local state alone says "not running" about
        // every campaign somebody brought under management - and this is the
        // check standing between a buyer and starting a campaign that is
        // already spending.
        if ($this->isLiveOnPlatform($campaign, $actor) ?? $campaign->isRunning()) {
            $problems[] = 'it is already running';
        }

        // The same questions publishing asks, minus the one they disagree on:
        // check() refuses a campaign that is already on the platform, and this
        // requires it. A campaign can lose something between being published and
        // being started - a creative removed, an account no longer permitted - and
        // starting it then spends money against a campaign that would be refused a
        // publish today.
        return [...$problems, ...$this->gate->soundness($campaign)];
    }
}
