<?php

namespace App\Campaigns\Publishing;

use App\Campaigns\Objectives;
use App\Campaigns\Targeting\CountryCatalog;
use App\Campaigns\Targeting\MetaAudienceSelections;
use App\Campaigns\Targeting\MetaDetailedTargeting;
use App\Campaigns\Targeting\TargetingSelections;
use App\Campaigns\TrackedUrl;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\CampaignAdSet;
use App\Services\Meta\AdSetSpec;
use App\Services\Meta\AdsMcp;
use App\Services\Meta\CampaignSpec;
use App\Services\Meta\CreativeSpec;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use App\Services\Meta\PublishedObjectReport;
use App\Support\CurrencyMinorUnits;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Sleep;
use RuntimeException;
use Throwable;

/**
 * Meta's half of publishing: campaign, ad set, then a creative and an ad per
 * copy variation.
 *
 * Moved out of Publisher unchanged when Google needed the same lifecycle around
 * a different payload. Publisher had no platform dispatch at all, so it built
 * Meta specs for whatever it was handed and the only thing stopping a Google
 * campaign reaching Meta's API was a line of text in a rules class.
 */
class MetaPublisher implements AddsToLiveCampaigns, PlatformPublisher
{
    private int $rollbackRetriesLeft = 0;

    private bool $draftsPublishedForRemoval = false;

    /** A publish is still running, so rollback must not pause or delete yet. */
    private bool $removalBlockedByPublish = false;

    /**
     * What an ad set and an ad are created as when a campaign launches.
     *
     * The campaign is paused either way, and that is what stops delivery: Meta
     * gates a whole tree on its campaign, so an active ad set under a paused
     * campaign spends nothing and reads as CAMPAIGN_PAUSED. Pausing all three
     * levels was a stronger form of the same guarantee, and it cost the buyer
     * two extra switches - a campaign started at the top over a paused ad set
     * delivers nothing and looks like a slow start, which is the most expensive
     * silence this product can produce.
     *
     * Only on a first launch. addAdSet() and addAds() still create paused,
     * because they attach to a campaign that is already live: an ad set added
     * there and left active would begin spending the moment it existed, with
     * nobody having reviewed it.
     */
    private function childLaunchStatus(): string
    {
        return config('platforms.guardrails.publish_pause_level') === 'all' ? 'PAUSED' : 'ACTIVE';
    }

    public function __construct(
        private readonly Meta $meta,
        private readonly CountryCatalog $countries,
        private readonly TargetingSelections $selections,
        private readonly MetaAudienceSelections $metaAudiences,
        private readonly MetaDetailedTargeting $detailedTargeting,
    ) {}

    /**
     * One more ad set under a campaign that is already live, paused.
     *
     * The same steps publishing takes per ad set against a campaign that exists
     * rather than one being built. Its
     * ads go with it: an ad set added with no ads delivers nothing, and Meta
     * will happily hold one forever without saying so.
     *
     * @return array<string,mixed>
     */
    public function addAdSet(CampaignAdSet $adSet, string $actor): array
    {
        $campaign = $adSet->campaign;
        $meta = $this->meta->on($campaign->id, $actor);

        $created = ['ad_sets' => [], 'ads' => []];

        try {
            $this->verifyPixel($campaign);
            $targeting = $this->targeting($campaign, $adSet);
            $adSetId = $meta->createAdSet(
                $this->adSet($campaign, $adSet, (string) $campaign->external_campaign_id, $targeting),
            );

            $adSet->update(['external_adset_id' => $adSetId, 'status' => 'published', 'last_error' => null]);

            $created['ad_sets'][] = ['ad_set_row' => $adSet->id, 'adset_id' => $adSetId];
            $adSetId = $this->replaceWithLiveAdSetId(
                $created,
                $this->publishedAdSetIds($campaign, $meta, [['id' => $adSetId, 'type' => 'ad_set']]),
            );
            $created['ads'] = $this->ads($campaign, $adSet, $meta, $adSetId, $created);
            $this->publishNewAds($campaign, $meta, $created['ads']);

            if ($meta->usingMcp()) {
                app(MetaDraftPause::class)->pauseOnceCreated($campaign->ad_account_id, [
                    ['id' => $adSetId, 'type' => 'ad_set'],
                    ...$this->asAdObjects($created['ads']),
                ]);
            }

            return $created;
        } catch (Throwable $e) {
            // Rolled back here rather than by the caller, and only this ad set:
            // the campaign above is live and may be spending, so the broad
            // rollback publishing uses would delete somebody's running campaign
            // because its new ad set failed.
            $this->rollBack($campaign, $created, $actor);

            $adSet->update(['status' => 'failed', 'last_error' => $e->getMessage()]);

            throw $e;
        }
    }

    /**
     * More ads inside an ad set that already exists, paused.
     *
     * @param  Collection<int, CampaignAd>  $ads
     * @return array<string,mixed>
     */
    public function addAds(CampaignAdSet $adSet, Collection $ads, string $actor): array
    {
        $campaign = $adSet->campaign;
        $meta = $this->meta->on($campaign->id, $actor);

        $created = ['ads' => []];

        try {
            // Numbered from what is already there, so the second batch is "ad 4"
            // rather than a second "ad 1". The names are what a buyer reads in
            // Ads Manager to tell the ads apart.
            $adSetId = (string) $adSet->external_adset_id;

            if ($meta->usingMcp()) {
                $adSetId = $this->liveIdOrFail($campaign, $meta, $adSetId, 'ad set');

                if ($adSetId !== (string) $adSet->external_adset_id) {
                    $adSet->update(['external_adset_id' => $adSetId]);
                }
            }

            $created['ads'] = $this->createAds(
                $campaign,
                $meta,
                $adSetId,
                $ads,
                $created,
                $campaign->ads()->whereNotNull('external_ad_id')->count(),
            );
            $this->publishNewAds($campaign, $meta, $created['ads']);

            if ($meta->usingMcp() && $created['ads'] !== []) {
                app(MetaDraftPause::class)->pauseOnceCreated(
                    $campaign->ad_account_id,
                    $this->asAdObjects($created['ads']),
                );
            }

            return $created;
        } catch (Throwable $e) {
            $this->rollBack($campaign, $created, $actor);

            throw $e;
        }
    }

    /**
     * @param  array<string,mixed>  $created
     * @return array<string,mixed>
     */
    public function create(Campaign $campaign, string $actor, array &$created): array
    {
        if (array_key_exists('meta_custom_audience_criteria', (array) $campaign->external_ids)) {
            throw new RuntimeException('Imported Meta ad-set audience criteria must be reviewed at their original scope before republishing.');
        }

        $this->verifyPixel($campaign);
        $targetings = [];
        foreach ($campaign->adSets as $adSet) {
            $targetings[$adSet->id] = $this->targeting($campaign, $adSet);
        }

        $meta = $this->meta->on($campaign->id, $actor);

        $spec = $this->campaign($campaign);

        // Ask the platform to check the payload before anything exists. Cheap,
        // and it turns a rollback into a clean refusal whenever Meta changes
        // what it requires.
        $meta->validateCampaign($spec);

        $created['campaign_id'] = $meta->createCampaign($spec);

        // Every ad set checked before any of them is created.
        //
        // This is where Meta's refusals actually land, and until now nothing
        // asked: the campaign went through its dry run, the campaign was created,
        // and the first the buyer heard of a bad ad set was the ad set create
        // failing with the campaign already on the account. Through the MCP that
        // arrives as {"error_category":"INTERNAL","is_retryable":true}, which
        // names neither the field nor the value, so it reads as a platform outage
        // and invites a retry that cannot work. It happened three times in three
        // days on one pixel's only event.
        //
        // All of them first, rather than each before its own create, so a campaign
        // with a second ad set cannot end up half published: the whole set is
        // either publishable or refused with one campaign to roll back.
        //
        // Unconditional here, because validateAdSet() is the thing that knows
        // when it cannot run. It returns without asking Graph anything once the
        // MCP is in play: MCP creates an unpublished draft Graph cannot address,
        // so the dry run would refuse the id MCP had just returned with "<id> is
        // not a valid campaign id" [100/1815148], abandon the publish, and leave
        // a campaign the rollback cannot delete either - DELETE on an MCP draft
        // answers "(#10) Application does not have permission". Production,
        // api_calls 863-866 on 7 Oct.
        //
        // This loop briefly carried that condition as well. One guard, in the
        // method that owns the limitation, rather than two that have to agree.
        foreach ($campaign->adSets as $adSet) {
            $meta->validateAdSet(
                $this->adSet($campaign, $adSet, $created['campaign_id'], $targetings[$adSet->id]),
                status: $this->childLaunchStatus(),
            );
        }

        $created['ad_sets'] = [];
        $created['ads'] = [];

        // One Meta ad set per row, and its ads with it. A campaign has had
        // exactly one of these since it was written, which is why the ad set
        // only ever existed as an id in external_ids; they are rows now, so
        // this is a loop and the ids come back onto the rows that asked for
        // them.
        foreach ($campaign->adSets as $adSet) {
            $adSetId = $meta->createAdSet(
                $this->adSet($campaign, $adSet, $created['campaign_id'], $targetings[$adSet->id]),
                status: $this->childLaunchStatus(),
            );

            $adSet->update(['external_adset_id' => $adSetId, 'status' => 'published']);

            $created['ad_sets'][] = ['ad_set_row' => $adSet->id, 'adset_id' => $adSetId];

            // Kept for the one ad set every campaign published before this, so
            // nothing that reads the published result has to know whether it
            // was written before or after ad sets became rows.
            $created['adset_id'] ??= $adSetId;
        }

        $liveIds = $this->publishedAdSetIds($campaign, $meta, [
            ['id' => $created['campaign_id'], 'type' => 'campaign'],
            ...array_map(
                static fn (array $adSet): array => ['id' => $adSet['adset_id'], 'type' => 'ad_set'],
                $created['ad_sets'],
            ),
        ]);
        $this->replaceWithLiveAdSetId($created, $liveIds);

        foreach ($campaign->adSets as $adSet) {
            $adSetId = (string) ($adSet->fresh()->external_adset_id ?? '');

            if ($adSetId === '') {
                continue;
            }

            $this->ads($campaign, $adSet, $meta, $adSetId, $created, status: $this->childLaunchStatus());
        }

        $this->publishNewAds($campaign, $meta, $created['ads']);

        if ($meta->usingMcp()) {
            app(MetaDraftPause::class)->pauseOnceCreated($campaign->ad_account_id, [
                ['id' => $created['campaign_id'], 'type' => 'campaign'],
                ...array_map(
                    static fn (array $adSet): array => ['id' => $adSet['adset_id'], 'type' => 'ad_set'],
                    $created['ad_sets'],
                ),
                ...$this->asAdObjects($created['ads']),
            ], pauseChildren: $this->childLaunchStatus() === 'PAUSED');
        }

        return $created;
    }

    /**
     * Publish ads that were created after their ad set was already live.
     *
     * The ad set publish cannot include them, because they do not exist yet.
     * Left as drafts they are invisible to Graph, so the campaign pause waits
     * forever and the campaign stays in whatever state that publish staged.
     *
     * @param  list<array{ad_row: int, creative_id: string, ad_id: string}>  $ads
     */
    private function publishNewAds(Campaign $campaign, Meta $meta, array $ads): void
    {
        if (! $meta->usingMcp() || $ads === []) {
            return;
        }

        $meta->publishDraft($campaign->ad_account_id, $this->asAdObjects($ads));
    }

    /**
     * Publish the drafts, then keep the ad set id Graph reads back.
     *
     * Ads are not created here. A Graph ad that names the draft id is refused
     * with "Choose an ad set" (100/1487006) because that id is not an ad set
     * Graph can see yet, and it may not be the id of the ad set once it is.
     *
     * @param  list<array{id: string, type: string}>  $objects
     * @return array<string, string> draft id => id Graph returned
     */
    private function publishedAdSetIds(Campaign $campaign, Meta $meta, array $objects): array
    {
        if (! $meta->usingMcp()) {
            return [];
        }

        try {
            $payload = $meta->publishDraft($campaign->ad_account_id, $objects);
        } catch (MetaException $exception) {
            Log::error('Meta ad set publish failed', [
                'campaign' => $campaign->id,
                'error' => $exception->getMessage(),
                'objects' => $objects,
            ]);

            throw $exception;
        }

        $errors = PublishedObjectReport::errors($payload);
        $adSetErrors = array_values(array_filter(
            $errors,
            static fn (array $error): bool => $error['type'] === 'ad_set' || $error['type'] === '',
        ));
        $relevant = $adSetErrors !== [] ? $adSetErrors : $errors;

        if ($relevant !== []) {
            Log::error('Meta ad set publish failed', [
                'campaign' => $campaign->id,
                'errors' => $relevant,
            ]);

            throw new MetaException($relevant[0]['message']);
        }

        $live = [];

        foreach ($objects as $object) {
            if ($object['type'] !== 'ad_set') {
                continue;
            }

            $live[$object['id']] = $this->liveIdOrFail($campaign, $meta, $object['id'], 'ad set');
        }

        return $live;
    }

    private function liveIdOrFail(Campaign $campaign, Meta $meta, string $objectId, string $type): string
    {
        try {
            return $meta->awaitLiveObject($objectId, $type, $campaign->ad_account_id)['id'];
        } catch (MetaException $exception) {
            Log::error('Meta ad set publish failed', [
                'campaign' => $campaign->id,
                'ad_set_id' => $objectId,
                'error' => $exception->getMessage(),
            ]);

            throw $exception;
        }
    }

    /**
     * Point the ad set rows at the id Graph returned.
     *
     * @param  array<string, mixed>  $created
     * @param  array<string, string>  $liveIds
     */
    private function replaceWithLiveAdSetId(array &$created, array $liveIds): string
    {
        $current = '';

        foreach ($created['ad_sets'] as $index => $row) {
            $draftId = (string) ($row['adset_id'] ?? '');
            $liveId = $liveIds[$draftId] ?? $draftId;
            $current = $liveId;

            if ($liveId === '' || $liveId === $draftId) {
                continue;
            }

            if ($set = CampaignAdSet::find($row['ad_set_row'] ?? null)) {
                $set->update(['external_adset_id' => $liveId]);
            }

            $created['ad_sets'][$index]['adset_id'] = $liveId;

            if (($created['adset_id'] ?? null) === $draftId) {
                $created['adset_id'] = $liveId;
            }
        }

        return $current;
    }

    /**
     * @param  list<array{ad_row: int, creative_id: string, ad_id: string}>  $ads
     * @return list<array{id: string, type: string}>
     */
    private function asAdObjects(array $ads): array
    {
        return array_map(
            static fn (array $ad): array => ['id' => $ad['ad_id'], 'type' => 'ad'],
            array_values(array_filter($ads, static fn (array $ad): bool => filled($ad['ad_id'] ?? null))),
        );
    }

    /**
     * Deepest first: Meta refuses to delete a campaign that still has children.
     *
     * @param  array<string,mixed>  $created
     */
    public function rollBack(Campaign $campaign, array $created, string $actor): array
    {
        // Shared across every object, so the rollback stays well inside a web request's timeout.
        $this->rollbackRetriesLeft = $this->meta->usingMcp() ? 4 : 0;
        $this->removalBlockedByPublish = false;
        $this->draftsPublishedForRemoval = $this->publishDraftsForRemoval($campaign, $created);

        $left = [];

        foreach (array_reverse($created['ads'] ?? []) as $ad) {
            $left = [
                ...$left,
                ...$this->quietlyDelete($ad['ad_id'] ?? null, $campaign, 'ad'),
                ...$this->quietlyDelete($ad['creative_id'] ?? null, $campaign, 'creative'),
            ];

            if ($row = CampaignAd::find($ad['ad_row'] ?? null)) {
                $row->update(['external_creative_id' => null, 'external_ad_id' => null, 'status' => 'failed']);
            }
        }

        foreach (array_reverse($created['ad_sets'] ?? []) as $adSet) {
            $left = [...$left, ...$this->quietlyDelete($adSet['adset_id'] ?? null, $campaign, 'ad_set')];

            if ($row = CampaignAdSet::find($adSet['ad_set_row'] ?? null)) {
                $row->update(['external_adset_id' => null, 'status' => 'failed']);
            }
        }

        return [...$left, ...$this->quietlyDelete($created['campaign_id'] ?? null, $campaign, 'campaign')];
    }

    /**
     * The campaign itself, which now carries the budget whenever the advertiser
     * chose Advantage campaign budget rather than a per-ad-set one.
     */
    private function campaign(Campaign $campaign): CampaignSpec
    {
        return new CampaignSpec(
            adAccountId: $campaign->ad_account_id,
            name: $campaign->name,
            objective: $campaign->objective,
            // Declared by the advertiser, not defaulted. The gate refuses to
            // publish until this has actually been answered.
            specialAdCategories: (array) ($campaign->special_ad_categories ?? []),
            budgetLevel: $campaign->budgetLevel(),
            budgetMode: $campaign->budgetMode(),
            budgetMinorUnits: $campaign->budgetInMinorUnits(),
            bidStrategy: $campaign->bid_strategy ?? 'LOWEST_COST_WITHOUT_CAP',
            endsAt: $campaign->ends_at,
        );
    }

    /**
     * One ad set's payload, built from its own row.
     *
     * The money comes through the ad set rather than off the campaign, because
     * an ad set may hold its own amount and most do not: the row answers with
     * its override or the campaign's arrangement, and this does not need to
     * know which. budgetLevel still decides whether Meta is sent the amount
     * here at all, and that is the campaign's to say.
     *
     * @param  array<string, mixed>|null  $targeting
     */
    private function adSet(Campaign $campaign, CampaignAdSet $adSet, string $campaignId, ?array $targeting = null): AdSetSpec
    {
        return new AdSetSpec(
            adAccountId: $campaign->ad_account_id,
            campaignId: $campaignId,
            name: $adSet->name,
            budgetMinorUnits: $adSet->budgetInMinorUnits() ?? 0,
            optimizationGoal: $adSet->optimization_goal ?? Objectives::optimizationGoal($campaign->objective),
            targeting: $targeting ?? $this->targeting($campaign, $adSet),
            pageId: $campaign->page_id,
            pixelId: $campaign->pixel_id,
            // What was chosen, or the objective's default when nobody chose.
            //
            // The default alone is what put a LEAD optimisation on a pixel that
            // only fires PageView and Subscribe.
            conversionEvent: $adSet->conversion_event ?: Objectives::conversionEvent($campaign->objective),
            bidStrategy: $adSet->effectiveBidStrategy(),
            bidAmountCents: $adSet->bidInMinorUnits(),
            startsAt: $adSet->starts_at,
            endsAt: $adSet->ends_at,
            budgetLevel: $campaign->budgetLevel(),
            budgetMode: $adSet->effectiveBudgetMode(),
            currency: $campaign->currency,
            dsaBeneficiary: $this->advertiser($campaign, 'dsa_beneficiary'),
            dsaPayor: $this->advertiser($campaign, 'dsa_payor'),
            universalBeneficiary: $this->advertiser($campaign, 'universal_beneficiary'),
            universalPayer: $this->advertiser($campaign, 'universal_payer'),
            regionalRegulatedCategories: array_values(array_filter(
                (array) ($campaign->meta['regional_regulated_categories'] ?? []),
                fn (mixed $category): bool => is_string($category) && $category !== '',
            )),
        );
    }

    private function advertiser(Campaign $campaign, string $field): ?string
    {
        $value = $campaign->meta[$field] ?? null;

        return is_string($value) && $value !== '' ? $value : null;
    }

    private function verifyPixel(Campaign $campaign): void
    {
        if (filled($campaign->pixel_id)
            && ! collect($this->meta->pixels((string) $campaign->ad_account_id, fresh: true))
                ->contains(fn (array $pixel): bool => (string) ($pixel['id'] ?? '') === (string) $campaign->pixel_id)) {
            throw new RuntimeException('The selected Meta pixel is unavailable. Review it before publishing.');
        }
    }

    /** @return array<string, mixed> */
    private function targeting(Campaign $campaign, CampaignAdSet $adSet): array
    {
        if (! $adSet->is($campaign->primaryAdSet) || $campaign->isPublished()) {
            if ($problems = $this->selections->additionalMetaAdSetProblems($adSet)) {
                throw new RuntimeException(implode(' ', $problems));
            }

            $this->countries->resolve('meta', (array) ($adSet->locations['countries'] ?? []), $campaign->ad_account_id);

            return $adSet->targeting();
        }

        $this->countries->resolve('meta', $this->selections->countries($campaign), $campaign->ad_account_id);
        $geoLocations = $this->selections->metaGeoLocations($campaign);
        foreach ($geoLocations['geo_markets'] ?? [] as $market) {
            $this->meta->marketAudienceEstimate((string) $campaign->ad_account_id, $market['key']);
        }

        $audiences = $this->metaAudiences->verifiedForPublish($campaign);
        $interests = $this->verifiedInterests($campaign);
        $detailed = $this->detailedTargeting->verifiedForPublish($campaign);

        $built = [
            ...$adSet->targeting(),
            'geo_locations' => $geoLocations,
            'meta_interests' => $interests,
            'meta_detailed' => $detailed,
            'meta_custom_audiences' => array_values(array_map(
                static fn (array $audience): array => ['id' => $audience['id']],
                array_filter($audiences, static fn (array $audience): bool => $audience['operation'] === 'include'),
            )),
            'meta_excluded_custom_audiences' => array_values(array_map(
                static fn (array $audience): array => ['id' => $audience['id']],
                array_filter($audiences, static fn (array $audience): bool => $audience['operation'] === 'exclude'),
            )),
        ];

        $this->assertAudienceCanDeliver($campaign, $adSet, $built);

        return $built;
    }

    /**
     * Meta rejects an ad set whose audience cannot deliver (subcode 2446395).
     * Ask for the estimate with the same spec before creating it.
     *
     * @param  array<string, mixed>  $targeting
     */
    private function assertAudienceCanDeliver(Campaign $campaign, CampaignAdSet $adSet, array $targeting): void
    {
        $hasDetail = ($targeting['meta_interests'] ?? []) !== []
            || (is_array($targeting['meta_detailed'] ?? null) && $targeting['meta_detailed'] !== []);

        if (! $hasDetail || blank($campaign->ad_account_id)) {
            return;
        }

        $objective = is_string($campaign->objective) ? $campaign->objective : '';
        $spec = new AdSetSpec(
            adAccountId: (string) $campaign->ad_account_id,
            campaignId: (string) ($campaign->external_campaign_id ?: '0'),
            name: (string) ($adSet->name ?: $campaign->name),
            budgetMinorUnits: 0,
            optimizationGoal: $adSet->optimization_goal
                ?? ($objective !== '' ? Objectives::optimizationGoal($objective) : 'LINK_CLICKS'),
            targeting: $targeting,
            pageId: (string) ($campaign->page_id ?? ''),
        );

        try {
            $estimate = $this->meta->deliveryEstimate(
                (string) $campaign->ad_account_id,
                $spec->optimizationGoal,
                $spec->targetingSpec(),
            );
        } catch (MetaException $exception) {
            if (str_contains($exception->getMessage(), '2446395')
                || str_contains(strtolower($exception->getMessage()), 'broaden your audience')) {
                throw new RuntimeException('Meta cannot deliver to this audience. Remove a detailed target or widen the locations, then try again.');
            }

            throw $exception;
        }

        $row = is_array($estimate['data'][0] ?? null) ? $estimate['data'][0] : $estimate;
        $lower = $row['estimate_mau_lower_bound'] ?? $row['estimate_dau'] ?? null;

        if ($lower !== null && (int) $lower === 0) {
            throw new RuntimeException('Meta cannot deliver to this audience. Remove a detailed target or widen the locations, then try again.');
        }
    }

    /** @return list<array{id: string, name: string}> */
    private function verifiedInterests(Campaign $campaign): array
    {
        $stored = $campaign->audience['meta_interests'] ?? [];

        if (! is_array($stored) || ! array_is_list($stored)) {
            throw new RuntimeException('Saved Meta interests are invalid. Search and select them again.');
        }

        if ($stored === []) {
            return [];
        }

        $ids = [];

        foreach ($stored as $interest) {
            $id = is_array($interest) ? ($interest['id'] ?? null) : null;

            if ((! is_string($id) && ! is_int($id)) || preg_match('/^[0-9]+$/D', (string) $id) !== 1) {
                throw new RuntimeException('Saved Meta interests are invalid. Search and select them again.');
            }

            $ids[] = (string) $id;
        }

        $ids = array_values(array_unique($ids));

        if (count($ids) > 20) {
            throw new RuntimeException('Saved Meta interests are invalid. Choose up to 20 interests.');
        }

        $validated = collect($this->meta->validateTargetingInterests((string) $campaign->ad_account_id, $ids))
            ->keyBy(static fn (array $interest): string => (string) ($interest['id'] ?? ''));
        $verified = [];

        foreach ($ids as $id) {
            $current = $validated->get($id);

            if (! is_array($current) || ($current['valid'] ?? false) !== true || blank($current['name'] ?? null)) {
                throw new RuntimeException('A selected Meta interest is no longer available. Review audience targeting before publishing.');
            }

            $verified[] = ['id' => $id, 'name' => (string) $current['name']];
        }

        return $verified;
    }

    /**
     * One creative and one ad per copy row.
     *
     * @param  array<string,mixed>  $created  updated as we go, so a failure
     *                                        halfway still knows what to undo
     * @return list<array{ad_row: int, creative_id: string, ad_id: string}>
     */
    private function ads(Campaign $campaign, CampaignAdSet $adSet, Meta $meta, string $adSetId, array &$created, string $status = 'PAUSED'): array
    {
        return $this->createAds($campaign, $meta, $adSetId, $this->adsOf($campaign, $adSet), $created, status: $status);
    }

    /**
     * One creative and one ad per row, into whichever ad set is named.
     *
     * Shared by publishing and by adding ads to a live campaign, which do the
     * same work against a different parent. The only difference is where the
     * numbering starts: a second batch continues from the ads already there
     * rather than beginning again at one.
     *
     * @param  Collection<int, CampaignAd>  $ads
     * @param  array<string,mixed>  $created  updated as we go, so a failure
     *                                        halfway still knows what to undo
     * @return list<array{ad_row: int, creative_id: string, ad_id: string}>
     */
    private function createAds(
        Campaign $campaign,
        Meta $meta,
        string $adSetId,
        Collection $ads,
        array &$created,
        int $startingAt = 0,
        string $status = 'PAUSED',
    ): array {
        $made = [];

        // The landing page plus whatever tracking was agreed. Built once here
        // rather than per ad, so every ad in a campaign is tagged the same.
        $destination = TrackedUrl::for($campaign);

        foreach ($ads->values() as $offset => $ad) {
            $index = $startingAt + $offset;

            $creativeId = $meta->createCreative($this->creative($campaign, $ad, $meta, $destination, $index));

            $adId = $meta->createAd(
                $campaign->ad_account_id,
                $adSetId,
                $creativeId,
                $campaign->name.' - ad '.($index + 1),
                status: $status,
            );

            $ad->update([
                'external_creative_id' => $creativeId,
                'external_ad_id' => $adId,
                'status' => 'published',
            ]);

            $created['ads'] = [...($created['ads'] ?? []), $entry = [
                'ad_row' => $ad->id,
                'creative_id' => $creativeId,
                'ad_id' => $adId,
            ]];

            $made[] = $entry;
        }

        return $made;
    }

    /**
     * The ads belonging to one ad set.
     *
     * ad_set_id is null on every ad written before ad sets were rows, and those
     * ads were all in the campaign's only ad set, so the first ad set answers
     * for them. Reading it as "no ad set" instead would publish a campaign with
     * no ads at all and report success.
     *
     * @return Collection<int, CampaignAd>
     */
    private function adsOf(Campaign $campaign, CampaignAdSet $adSet): Collection
    {
        return $campaign->ads()
            ->where(function ($query) use ($campaign, $adSet): void {
                $query->where('ad_set_id', $adSet->id);

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

    /**
     * The creative for one ad, built from whichever kind of asset it carries.
     *
     * An image and a video are not two spellings of the same payload. The
     * reference Meta gave us is a hash for one and an id for the other, they
     * live in different columns, and this read the hash whatever the asset was:
     * a video produced a null hash and a TypeError, thrown after the campaign
     * and ad set already existed on the account.
     *
     * A video also has to be ready before an ad can name it, and needs a still,
     * both of which Meta only has once transcoding finishes.
     */
    private function creative(Campaign $campaign, CampaignAd $ad, Meta $meta, string $destination, int $index): CreativeSpec
    {
        $reference = $ad->asset->refFor($campaign->platform, $campaign->ad_account_id);

        $shared = [
            'adAccountId' => $campaign->ad_account_id,
            'pageId' => $campaign->page_id,
            'landingUrl' => $destination,
            'headline' => $ad->headline,
            'primaryText' => $ad->primary_text,
            'callToAction' => $ad->cta,
            'name' => $campaign->name.' - creative '.($index + 1),
            'description' => (string) $ad->description,
            'instagramUserId' => $campaign->instagram_account_id,
        ];

        if ($ad->asset->kind !== 'video') {
            return new CreativeSpec(...$shared, imageHash: $reference->external_hash);
        }

        $videoId = $reference->external_id;

        $meta->awaitVideoReady($videoId);

        $thumbnailUrl = $meta->videoThumbnail($videoId);

        return new CreativeSpec(
            ...$shared,
            videoId: $videoId,
            thumbnailUrl: $thumbnailUrl,
            thumbnailHash: $meta->usingMcp()
                ? $meta->uploadImageFromUrl($campaign->ad_account_id, $thumbnailUrl, "video-{$videoId}-cover.jpg")
                : null,
        );
    }

    /**
     * Make MCP drafts deletable.
     *
     * Graph refuses to delete an unpublished draft (#10) and the MCP refuses
     * status DELETED on one (1487564). Publishing it paused, with nothing
     * active, turns it into an ordinary object Graph can delete. Verified on
     * act_1418821929380936 on 8 Oct.
     *
     * @param  array<string,mixed>  $created
     */
    private function publishDraftsForRemoval(Campaign $campaign, array $created): bool
    {
        if (! $this->meta->usingMcp() || blank($created['campaign_id'] ?? null)) {
            return false;
        }

        $objects = [
            ['id' => $created['campaign_id'], 'type' => 'campaign'],
            ...array_map(
                static fn (array $adSet): array => ['id' => $adSet['adset_id'], 'type' => 'ad_set'],
                array_values(array_filter($created['ad_sets'] ?? [], static fn (array $adSet): bool => filled($adSet['adset_id'] ?? null))),
            ),
            ...$this->asAdObjects($created['ads'] ?? []),
        ];

        try {
            $payload = $this->meta->publishDraft($campaign->ad_account_id, $objects);
            $errors = PublishedObjectReport::errors($payload);

            if ($errors !== []) {
                Log::error('Meta ad set publish failed', [
                    'campaign' => $campaign->id,
                    'errors' => $errors,
                ]);
            }

            foreach ($objects as $object) {
                $this->meta->awaitLiveObject($object['id'], str_replace('_', ' ', $object['type']), $campaign->ad_account_id);
            }

            $this->pauseForRemoval($campaign, $objects);
        } catch (Throwable $e) {
            $stillPublishing = $e instanceof MetaException && (
                $e->isDraftStillPublishing() || str_contains($e->getMessage(), 'did not finish publishing')
            );

            if ($stillPublishing) {
                $this->removalBlockedByPublish = true;
                Log::warning('Rollback is waiting because the Meta publish is still in flight', [
                    'campaign' => $campaign->id,
                    'error' => $e->getMessage(),
                ]);
            } else {
                Log::warning('Could not publish MCP drafts paused for rollback', [
                    'campaign' => $campaign->id, 'error' => $e->getMessage(),
                ]);
            }

            return false;
        }

        return ! $this->removalBlockedByPublish;
    }

    /**
     * Pause only after Graph can see the objects.
     *
     * Pausing while ads_activate_entity is still publishing is refused with
     * 1815558. Deleting in that window is refused too, so a pause that is still
     * waiting blocks the deletes that follow.
     *
     * @param  list<array{id: string, type: string}>  $objects
     */
    private function pauseForRemoval(Campaign $campaign, array $objects): void
    {
        $pending = $objects;

        foreach ([0, ...AdsMcp::PAUSE_RETRY_SECONDS] as $seconds) {
            if ($seconds > 0) {
                Sleep::for($seconds)->seconds();
            }

            $still = [];

            foreach ($pending as $object) {
                try {
                    $this->meta->updateEntity($campaign->ad_account_id, $object['id'], $object['type'], ['status' => 'PAUSED']);
                } catch (MetaException $exception) {
                    if (! $exception->isDraftStillPublishing()) {
                        throw $exception;
                    }

                    Log::warning('Meta is still publishing the draft, so the pause waits for that publish', [
                        'ad_account_id' => $campaign->ad_account_id,
                        'entity_id' => $object['id'],
                        'entity_type' => $object['type'],
                        'error' => $exception->getMessage(),
                    ]);
                    $still[] = $object;
                }
            }

            $pending = $still;

            if ($pending === []) {
                return;
            }
        }

        $this->removalBlockedByPublish = true;
        Log::warning('Rollback is waiting because the Meta publish is still in flight', [
            'campaign' => $campaign->id,
            'objects' => $pending,
        ]);
    }

    /**
     * Remove one object, and say so when it could not be removed.
     *
     * Still quiet in the sense that matters - it never throws, because a failed
     * rollback must not mask the error that caused it - but no longer silent.
     * The id comes back so the caller can tell the buyer what is still on their
     * account instead of assuring them it is gone.
     *
     * @return list<string> the id, when it is still there
     */
    private function quietlyDelete(?string $objectId, Campaign $campaign, string $entityType): array
    {
        if (! $objectId) {
            return [];
        }

        if ($this->removalBlockedByPublish) {
            return [$objectId];
        }

        // A just-published MCP draft refuses edits for a few seconds while Meta finishes publishing it.
        $error = 'Meta refused the delete';

        while (true) {
            try {
                if ($this->meta->delete($objectId, $campaign->ad_account_id, $entityType)) {
                    return [];
                }
            } catch (Throwable $e) {
                $error = $e->getMessage();
            }

            if ($entityType === 'creative' || $this->rollbackRetriesLeft <= 0) {
                break;
            }

            $this->rollbackRetriesLeft--;
            Sleep::sleep(3);
        }

        Log::warning('Campaign rollback failed', [
            'object' => $objectId,
            'error' => $error,
            // Published paused for removal, so what remains is a live paused object, not a hidden draft.
            'left_as' => $this->draftsPublishedForRemoval ? 'published_paused' : 'as_created',
        ]);

        return [$objectId];
    }

    /**
     * Send approved changes to the live campaign.
     *
     * Lifted from CampaignUpdater, which did this for every platform against
     * Meta. The grouping is Meta's and belongs here: name lives on the
     * campaign; budget, bidding and schedule live on the ad set, unless the
     * campaign holds the budget itself, in which case the money and the bid
     * strategy move up with it. Sending a budget to a campaign id is accepted
     * and quietly ignored, which is worse than an error.
     *
     * @param  array<string, array{from: mixed, to: mixed}>  $changes
     */
    public function update(Campaign $campaign, array $changes, string $actor): void
    {
        $meta = $this->meta->on($campaign->id, $actor);

        foreach ($this->byEntity($campaign, $changes) as $entity => $fields) {
            [$type, $id] = explode(':', $entity);

            $meta->updateEntity($campaign->ad_account_id, $id, $type, $fields);
        }
    }

    /**
     * Start it, without resurrecting what somebody paused on purpose.
     *
     * A first activation starts every level, because Meta needs all three: a
     * campaign set ACTIVE over a PAUSED ad set delivers nothing, and Meta reports
     * that as a campaign with no impressions, which is what an ordinary
     * slow-starting campaign also looks like - so the failure is invisible for as
     * long as anyone is willing to wait for it. Deepest first, so that if it stops
     * half way the campaign above is still paused and nothing is spending; the
     * other order leaves a live campaign over paused ads and a buyer who has been
     * told it started.
     *
     * That was unconditional, and pause() only ever touched the campaign, so the
     * two were not symmetric: a buyer who paused one losing ad by hand in Ads
     * Manager, paused the campaign from the chat, and restarted it later got that
     * ad spending again, with nothing said. Mohsin described exactly that workflow
     * - "we sometimes pause campaigns and restart them after months as per danny's
     * instructions" - so it is a question of when rather than whether.
     *
     * The two cases are told apart by asking Meta rather than by remembering:
     * before a first activation every ad set is paused, and after one at least
     * one is live. activated_at cannot be used for this - pause() nulls it, so a
     * paused campaign is indistinguishable from one that never ran.
     *
     * A buyer who pauses every ad by hand and then restarts from the chat gets
     * them all back. That is the one reading this cannot separate from a first
     * activation without storing state on every pause, and it is the harmless
     * direction: they asked for the campaign to run and nothing in it was running.
     */
    public function activate(Campaign $campaign, string $actor): void
    {
        $this->setStatus($campaign, $actor, 'ACTIVE', children: $this->nothingIsRunning($campaign, $actor));
    }

    /**
     * Whether Meta reports every ad set on this campaign as paused.
     *
     * Fails towards the old behaviour: if the read fails there is no evidence
     * anything is running, and a campaign that will not start is a worse outcome
     * than one that starts an ad somebody had paused.
     */
    private function nothingIsRunning(Campaign $campaign, string $actor): bool
    {
        if (blank($campaign->external_campaign_id)) {
            return true;
        }

        try {
            $adSets = $this->meta->on($campaign->id, $actor)
                ->adSets((string) $campaign->external_campaign_id, $campaign->ad_account_id, fresh: true);
        } catch (Throwable $e) {
            Log::warning('Could not read ad set statuses before activating', [
                'campaign' => $campaign->id, 'error' => $e->getMessage(),
            ]);

            return true;
        }

        if ($adSets === []) {
            return true;
        }

        return ! collect($adSets)->contains(
            fn (array $adSet): bool => strtoupper((string) ($adSet['status'] ?? '')) === 'ACTIVE',
        );
    }

    /**
     * Stop at the campaign, which is enough to halt delivery.
     *
     * The ad set and the ads are left as they are on purpose: they were set live
     * by activate(), and putting them back to PAUSED here would mean activate()
     * had to know which of them the buyer had since changed by hand on Meta.
     */
    public function pause(Campaign $campaign, string $actor): void
    {
        $meta = $this->meta->on($campaign->id, $actor);

        $meta->setObjectStatus(
            $campaign->ad_account_id,
            (string) $campaign->external_campaign_id,
            'PAUSED',
        );
    }

    /**
     * New copy on an ad that is already live, without replacing the ad.
     *
     * Meta cannot reword a creative in place, which is where "ad copy cannot be
     * changed after publishing" came from - but that conclusion went one step
     * too far. A creative is immutable; an *ad* is not. Creating a new creative
     * and pointing the existing ad at it keeps the ad's id, its history and its
     * place in whatever the buyer is comparing, where adding a second ad beside
     * it does not.
     *
     * The copy is read off the row, so the caller writes locally first and this
     * sends whatever is there. Returns the new creative id.
     *
     * Worth saying back to the buyer: Meta restarts the learning phase when an
     * ad's creative changes, so the first day after this is not comparable with
     * the day before.
     */
    public function replaceCreative(CampaignAd $ad, string $actor): string
    {
        $campaign = $ad->campaign;

        if (blank($ad->external_ad_id)) {
            throw new RuntimeException('That ad is not on the platform yet, so there is no creative to replace.');
        }

        $meta = $this->meta->on($campaign->id, $actor);

        // Numbered from the ad's own place in the campaign, so the creative name
        // still reads as belonging to the ad it is for.
        $index = max(0, $campaign->ads()->where('id', '<=', $ad->id)->count() - 1);

        $creativeId = $meta->createCreative(
            $this->creative($campaign, $ad, $meta, TrackedUrl::for($campaign), $index),
        );

        $meta->updateEntity($campaign->ad_account_id, (string) $ad->external_ad_id, 'ad', [
            'creative' => json_encode(['creative_id' => $creativeId], JSON_THROW_ON_ERROR),
        ]);

        // Only once Meta has taken it. The old creative is left on the account
        // rather than deleted: it is still referenced by the ad's own history,
        // and removing it is not what was asked for.
        $ad->forceFill(['external_creative_id' => $creativeId])->save();

        return $creativeId;
    }

    /**
     * What Meta says the campaign's state is.
     *
     * effective_status in preference to status, because status is only what the
     * advertiser asked for: a campaign set ACTIVE under a disabled account reads
     * ACTIVE there and is not running. effective_status folds in the account and
     * review state, which is the question actually being asked.
     *
     * Campaign level, deliberately. It is the level activate() and pause() write,
     * so it is the level that answers "would pausing this do anything".
     */
    public function isLive(Campaign $campaign, string $actor): ?bool
    {
        if (blank($campaign->external_campaign_id)) {
            return null;
        }

        try {
            $remote = $this->meta->on($campaign->id, $actor)
                ->campaign((string) $campaign->external_campaign_id, $campaign->ad_account_id);
        } catch (Throwable $e) {
            Log::warning('Could not read campaign status from Meta', [
                'campaign' => $campaign->id, 'error' => $e->getMessage(),
            ]);

            return null;
        }

        $status = strtoupper((string) ($remote['effective_status'] ?? $remote['status'] ?? ''));

        return $status === '' ? null : $status === 'ACTIVE';
    }

    private function setStatus(Campaign $campaign, string $actor, string $status, bool $children = true): void
    {
        $meta = $this->meta->on($campaign->id, $actor);

        // The campaign alone, when the children already hold a status somebody
        // chose. Pausing a campaign stops delivery without changing them, so
        // starting it again only has to undo that one stop.
        if (! $children) {
            $meta->setObjectStatus(
                $campaign->ad_account_id,
                (string) $campaign->external_campaign_id,
                $status,
            );

            return;
        }

        foreach ($campaign->ads()->whereNotNull('external_ad_id')->pluck('external_ad_id') as $adId) {
            $meta->setObjectStatus($campaign->ad_account_id, (string) $adId, $status);
        }

        // Every ad set, not just the first. One left paused under a live
        // campaign delivers nothing and looks exactly like a slow start, which
        // is the failure this method's own docblock is about.
        //
        // Named ad_set here and adset_id in our own column; sending our spelling
        // is rejected as "Invalid entity_type: adset", and only when a real
        // update is attempted.
        foreach ($campaign->adSets()->whereNotNull('external_adset_id')->pluck('external_adset_id') as $adSetId) {
            $meta->setObjectStatus($campaign->ad_account_id, (string) $adSetId, $status);
        }

        $meta->setObjectStatus(
            $campaign->ad_account_id,
            (string) $campaign->external_campaign_id,
            $status,
        );
    }

    /**
     * Group changed fields by the Meta object that owns them.
     *
     * @param  array<string, array{from: mixed, to: mixed}>  $changes
     * @return array<string, array<string, mixed>>
     */
    private function byEntity(Campaign $campaign, array $changes): array
    {
        $campaignKey = 'campaign:'.$campaign->external_campaign_id;

        // The first ad set, because that is the one the campaign's own
        // attributes address and these changes were diffed from them. An ad set
        // added later has its own settings and is edited through itself, not
        // through the campaign.
        //
        // Meta names the entity type ad_set, not adset. Our own external_ids
        // key was adset_id, and using that spelling here was rejected as
        // "Invalid entity_type: adset" only once a real update was attempted.
        $adSetKey = 'ad_set:'.($campaign->primaryAdSet?->external_adset_id ?? '');

        // Whichever object is holding the money is the one to send it to.
        $budgetKey = $campaign->usesCampaignBudget() ? $campaignKey : $adSetKey;
        $budgetField = $campaign->usesLifetimeBudget() ? 'lifetime_budget' : 'daily_budget';

        $grouped = [];
        $unaddressable = [];

        foreach ($changes as $field => $change) {
            [$key, $name, $value] = match ($field) {
                'name' => [$campaignKey, 'name', $change['to']],
                'budget' => [$budgetKey, $budgetField, CurrencyMinorUnits::toMinor($change['to'], $campaign->currency)],
                'bid_strategy' => [$budgetKey, 'bid_strategy', $change['to']],
                'bid_amount' => [$adSetKey, 'bid_amount', CurrencyMinorUnits::toMinor($change['to'], $campaign->currency)],
                // Read off the model, not the diff: the diff holds a comparison
                // string with no timezone, and Meta reads an unqualified string
                // in the ad account's own timezone rather than ours.
                'starts_at' => [$adSetKey, 'start_time', $campaign->starts_at?->format(\DateTimeInterface::ATOM)],
                'ends_at' => [$adSetKey, 'end_time', $campaign->ends_at?->format(\DateTimeInterface::ATOM)],
                default => [null, null, null],
            };

            if ($key === null) {
                continue;
            }

            // A change we cannot address is refused, not dropped.
            //
            // An adopted campaign whose ad set list came back empty has no
            // adset_id, so this key was "ad_set:" and the field was skipped in
            // silence. update() then returned cleanly, CampaignUpdater wrote
            // the new published_state and marked the change applied, and the
            // buyer was told their budget had changed while Meta was never
            // asked. starts_at, ends_at and bid_amount always route to the ad
            // set, so on such a campaign they were all lost the same way.
            if (str_ends_with($key, ':')) {
                $unaddressable[] = $field;

                continue;
            }

            $grouped[$key][$name] = $value;
        }

        if ($unaddressable !== []) {
            throw new RuntimeException(sprintf(
                'This campaign has no ad set recorded, so %s cannot be changed on the platform. '
                .'It was adopted without one; open it again to re-read its ad sets.',
                implode(' or ', $unaddressable),
            ));
        }

        return $grouped;
    }
}
