<?php

namespace App\Campaigns\Manager\Editing;

use App\Campaigns\CampaignImporter;
use App\Campaigns\Manager\CampaignSynchronizer;
use App\Campaigns\Publisher;
use App\Models\Campaign;
use App\Models\CampaignChange;
use App\Models\CampaignEntityEdit;
use App\Models\CampaignPlatformDrift;
use App\Models\CampaignPlatformEntity;
use App\Models\User;
use App\Services\LinkedIn\LinkedInUrn;
use App\Services\Platforms\Support\Guardrails;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use RuntimeException;
use Throwable;

/**
 * Proposes, applies and confirms one change to one platform object.
 *
 * The order in apply() is the safety argument, so it is spelled out:
 *
 * 1. Nothing is sent unless the kill switch, account allow list and change
 *    limits all allow it. A refusal here leaves the proposal open to retry.
 * 2. The platform is read again first. If the object is gone, or differs in
 *    anything a person can change from what the user was looking at when they
 *    proposed the change, the edit is marked stale and nothing is sent.
 *    Someone changing it in Ads Manager in the meantime is exactly the case
 *    this exists for. Delivery state the platform derives itself (ad review,
 *    a parent pausing) does not count; see editBaseline().
 * 3. Only the proposed fields are sent, through the existing platform calls.
 * 4. The platform is read once more, and the edit is called applied only if
 *    it now holds the proposed values. Accepted-but-different is reported as
 *    unconfirmed, never as done.
 *
 * A delete or a duplicate goes through the same steps. A delete also reads
 * lifetime delivery when it is proposed, shows it, and is refused as stale if
 * the object has delivered more by the time it is confirmed. A duplicate is
 * applied once the copy shows up in the read-back.
 */
class EntityEditor
{
    private const int LOCK_SECONDS = 300;

    public function __construct(
        private readonly EditCapabilities $capabilities,
        private readonly CampaignSynchronizer $synchronizer,
        private readonly Guardrails $guardrails,
        private readonly Publisher $publisher,
        private readonly CampaignImporter $importer,
    ) {}

    /**
     * @param  array<string, mixed>  $values  field => new value, as the user typed it
     *
     * @throws EditRefused when nothing on this object can be changed, or nothing differs
     * @throws ValidationException when a value is not acceptable
     */
    public function propose(Campaign $campaign, CampaignPlatformEntity $entity, User $user, array $values): CampaignEntityEdit
    {
        if ($entity->campaign_id !== $campaign->id) {
            throw new InvalidArgumentException('That object does not belong to this campaign.');
        }

        $fields = $this->capabilities->editableFields($entity);

        if ($fields === []) {
            throw new EditRefused((string) $this->capabilities->refusal($entity));
        }

        if ($unknown = array_diff(array_keys($values), $fields)) {
            throw new EditRefused(sprintf('%s cannot be changed here.', implode(', ', $unknown)));
        }

        $values = array_map(fn (mixed $value): mixed => is_string($value) ? trim($value) : $value, $values);
        if ($values === []) {
            throw new EditRefused('Nothing is different from what the platform has now.');
        }

        $valid = Validator::make($values, array_intersect_key($this->capabilities->rules($entity, $values), $values))->validate();

        $changes = [];

        foreach ($valid as $field => $after) {
            $after = EditCapabilities::normalize($entity, $field, $after);
            $before = EditCapabilities::current($entity, $field);

            if (! EditCapabilities::same($entity, $field, $before, $after)) {
                $changes[$field] = ['before' => $before, 'after' => $after];
            }
        }

        $changes = $this->capabilities->prune($entity, $changes);

        if ($changes === []) {
            throw new EditRefused('Nothing is different from what the platform has now.');
        }

        $entity->edits()->where('user_id', $user->id)->where('state', CampaignEntityEdit::Proposed)
            ->update(['state' => CampaignEntityEdit::Cancelled]);

        return $entity->edits()->create([
            'campaign_id' => $campaign->id,
            'user_id' => $user->id,
            'platform' => $entity->platform,
            'entity_type' => $entity->entity_type,
            'external_id' => $entity->external_id,
            'changes' => $changes,
            'base_fingerprint' => $entity->editBaseline(),
            'state' => CampaignEntityEdit::Proposed,
        ]);
    }

    /**
     * Write down a delete or a duplicate against what was last read.
     *
     * @throws EditRefused when it cannot be done to this object, or delivery could not be read
     */
    public function proposeAction(Campaign $campaign, CampaignPlatformEntity $entity, User $user, string $action, array $details = []): CampaignEntityEdit
    {
        if ($entity->campaign_id !== $campaign->id) {
            throw new InvalidArgumentException('That object does not belong to this campaign.');
        }

        if (! in_array($action, [CampaignEntityEdit::Delete, CampaignEntityEdit::Duplicate], true)) {
            throw new EditRefused('Choose delete or duplicate.');
        }

        if ($reason = $this->capabilities->actionRefusal($entity, $action)) {
            throw new EditRefused($reason);
        }

        $this->validateActionDetails($entity, $action, $details);
        $details = $action === CampaignEntityEdit::Delete ? $this->delivery($campaign, $entity, $this->actor($user)) : ($details ?: null);

        $entity->edits()->where('user_id', $user->id)->where('state', CampaignEntityEdit::Proposed)
            ->update(['state' => CampaignEntityEdit::Cancelled]);

        return $entity->edits()->create([
            'campaign_id' => $campaign->id,
            'user_id' => $user->id,
            'platform' => $entity->platform,
            'entity_type' => $entity->entity_type,
            'external_id' => $entity->external_id,
            'action' => $action,
            'changes' => [],
            'details' => $details,
            'base_fingerprint' => $entity->editBaseline(),
            'state' => CampaignEntityEdit::Proposed,
        ]);
    }

    public function cancel(CampaignEntityEdit $edit, User $user): void
    {
        if ($edit->user_id === $user->id && $edit->isOpen()) {
            $edit->update(['state' => CampaignEntityEdit::Cancelled]);
        }
    }

    /**
     * @param  bool  $acknowledged  the user ticked the confirmations shown with this change
     *
     * @throws EditRefused when nothing was sent and the proposal is still open
     */
    public function apply(CampaignEntityEdit $edit, User $user, bool $acknowledged = false): CampaignEntityEdit
    {
        if ($edit->user_id !== $user->id || ! $edit->isOpen()) {
            throw new EditRefused('This change is no longer waiting to be applied.');
        }

        $lock = Cache::lock('campaign-manager:edit:'.$edit->campaign_id, self::LOCK_SECONDS);

        if (! $lock->get()) {
            throw new EditRefused('Another change to this campaign is being applied. Try again in a moment.');
        }

        try {
            return $this->applyLocked($edit->refresh(), $user, $acknowledged);
        } finally {
            $lock->release();
        }
    }

    private function applyLocked(CampaignEntityEdit $edit, User $user, bool $acknowledged): CampaignEntityEdit
    {
        if (! $edit->isOpen()) {
            throw new EditRefused('This change is no longer waiting to be applied.');
        }

        $campaign = $edit->campaign;
        $entity = $edit->entity;
        $patch = $edit->patch();
        $actor = $this->actor($user);

        if ($edit->isStructural()) {
            if ($reason = $this->capabilities->actionRefusal($entity, $edit->action)) {
                throw new EditRefused($reason.' Nothing was sent.');
            }
            $this->validateActionDetails($entity, $edit->action, $edit->action === CampaignEntityEdit::Duplicate ? (array) $edit->details : []);

            if (! $acknowledged && $this->capabilities->actionConfirmations($entity, $edit->action, (array) $edit->details) !== []) {
                throw new EditRefused('This needs to be acknowledged before it is sent. Nothing was sent.');
            }
        } else {
            if (array_diff(array_keys($patch), $this->capabilities->editableFields($entity)) !== []) {
                throw new EditRefused((string) ($this->capabilities->refusal($entity) ?? 'These fields can no longer be changed here.'));
            }

            // Limits are checked again now: a ceiling lowered or a rate refreshed
            // since the proposal applies to it.
            $check = Validator::make($patch, array_intersect_key($this->capabilities->rules($entity, $patch), $patch));

            if ($check->fails()) {
                throw new EditRefused($check->errors()->first().' Nothing was sent.');
            }

            if (! $acknowledged && $this->capabilities->confirmations($entity, $edit->changes) !== []) {
                throw new EditRefused('This change needs to be acknowledged before it is sent. Nothing was sent.');
            }
        }

        try {
            $this->guardrails->assertWritesAllowed();
            $this->guardrails->assertAccountAllowed((string) $campaign->ad_account_id, (string) $campaign->platform);
            $this->guardrails->assertChangeAllowed($campaign->id);
        } catch (RuntimeException $exception) {
            throw new EditRefused($exception->getMessage().' Nothing was sent.');
        }

        $edit->update(['approved_at' => now()]);
        $readFrom = now()->startOfSecond();

        $before = $this->read($campaign, 'pre_apply', $actor);

        if ($before !== null) {
            throw new EditRefused($before.' Nothing was sent; the change is still waiting.');
        }

        $entity->refresh();

        if ($entity->removed_at !== null) {
            return $this->close($edit, CampaignEntityEdit::Stale, 'This object is no longer on the platform. Nothing was sent.');
        }

        if ($entity->last_seen_at->lt($readFrom)) {
            return $this->close($edit, CampaignEntityEdit::Failed, 'This object could not be read just now, so its current state is unknown. Nothing was sent.');
        }

        if ($entity->editBaseline() !== $edit->base_fingerprint) {
            $moved = CampaignPlatformDrift::query()
                ->where('campaign_platform_entity_id', $entity->id)
                ->where('detected_at', '>=', $edit->created_at)
                ->whereNotNull('field')
                ->where('field', '!=', 'effective_status')
                ->distinct()
                ->pluck('field')
                ->map(fn (string $field): string => Str::after($field, 'settings.'))
                ->all();

            return $this->close($edit, CampaignEntityEdit::Stale, sprintf(
                'This object changed on the platform after the change was proposed%s. Nothing was sent. Check the current values and propose it again.',
                $moved === [] ? '' : ' ('.implode(', ', $moved).')',
            ));
        }

        if ($edit->isStructural()) {
            return $this->applyAction($edit, $campaign, $entity, $actor);
        }

        $starting = $this->startsCampaign($campaign, $entity, $patch);

        if ($starting && ($problems = $this->publisher->activationProblems($campaign, $actor)) !== []) {
            throw new EditRefused('The campaign cannot be started: '.implode('; ', $problems).'. Nothing was sent.');
        }

        $record = CampaignChange::create([
            'campaign_id' => $campaign->id,
            'actor' => $actor,
            'changes' => [$entity->entity_type.':'.$entity->external_id => $patch],
            'state' => 'pending',
        ]);
        $edit->update(['campaign_change_id' => $record->id]);

        try {
            $this->capabilities->writer((string) $campaign->platform)->write($campaign, $entity, $patch, $actor);
        } catch (Throwable $exception) {
            if (! $exception instanceof RuntimeException) {
                report($exception);
            }

            $message = Str::limit($exception->getMessage() ?: class_basename($exception), 1000);
            $record->update(['state' => 'failed', 'error' => $message]);

            return $this->close($edit, CampaignEntityEdit::Failed, 'The platform refused the change: '.$message.$this->landedAnyway($edit, $entity, $actor));
        }

        $record->update(['state' => 'applied', 'applied_at' => now()]);
        $edit->update(['applied_at' => now()]);

        // The same record Publisher keeps, written only after the platform agreed.
        if ($this->isTheCampaign($campaign, $entity) && isset($patch['status'])) {
            $campaign->update(['activated_at' => $starting ? now() : null]);
        }

        $after = $this->read($campaign, 'readback', $actor);

        if ($after !== null) {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, 'The platform accepted the change, but it could not be read back to confirm it. '.$after);
        }

        $entity->refresh();
        $readback = [];
        $differs = [];

        foreach ($patch as $field => $value) {
            $readback[$field] = EditCapabilities::current($entity, $field);

            if (! EditCapabilities::same($entity, $field, $readback[$field], $value)) {
                $differs[] = $field;
            }
        }

        $edit->update(['readback' => $readback]);

        if ($differs !== []) {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, sprintf(
                'The platform accepted the change but now reports a different %s. It may still be processing, or have adjusted the value.',
                implode(', ', $differs),
            ));
        }

        $edit->update(['state' => CampaignEntityEdit::Applied, 'verified_at' => now()]);

        return $edit;
    }

    /**
     * A delete or a duplicate, once the object has been read again and found
     * as it was when proposed.
     */
    private function applyAction(CampaignEntityEdit $edit, Campaign $campaign, CampaignPlatformEntity $entity, string $actor): CampaignEntityEdit
    {
        $deleting = $edit->action === CampaignEntityEdit::Delete;

        if ($deleting) {
            $now = $this->delivery($campaign, $entity, $actor);
            $then = (array) $edit->details;

            if ($now['spend'] > ($then['spend'] ?? 0) || $now['impressions'] > ($then['impressions'] ?? 0)) {
                return $this->close($edit, CampaignEntityEdit::Stale, sprintf(
                    'This %s has delivered since the delete was proposed (now %s %s spent, %s impressions). Nothing was sent. Review it again.',
                    strtolower(Str::headline($entity->entity_type)), EditCapabilities::money($now['spend'], $now['currency']), $now['currency'], number_format($now['impressions']),
                ));
            }
        }

        $record = CampaignChange::create([
            'campaign_id' => $campaign->id,
            'actor' => $actor,
            'changes' => [$entity->entity_type.':'.$entity->external_id => [
                'action' => $edit->action,
                ...(isset($edit->details['conversion_event']) ? ['conversion_event' => $edit->details['conversion_event']] : []),
            ]],
            'state' => 'pending',
        ]);
        $edit->update(['campaign_change_id' => $record->id]);
        $writer = $this->capabilities->writer((string) $campaign->platform);

        try {
            $result = match (true) {
                $deleting => $writer->delete($campaign, $entity, $actor),
                isset($edit->details['conversion_event']) && $writer instanceof Writers\MetaEntityWriter => $writer->duplicateWithEvent($campaign, $entity, $actor, $edit->details['conversion_event']),
                default => $writer->duplicate($campaign, $entity, $actor),
            };
        } catch (Throwable $exception) {
            if (! $exception instanceof RuntimeException) {
                report($exception);
            }

            $message = Str::limit($exception->getMessage() ?: class_basename($exception), 1000);
            $record->update(['state' => 'failed', 'error' => $message]);

            return $this->close($edit, CampaignEntityEdit::Failed, 'The platform refused it: '.$message);
        }

        $record->update(['state' => 'applied', 'applied_at' => now()]);
        $edit->update(['applied_at' => now()]);

        return $deleting
            ? $this->confirmDeleted($edit, $campaign, $entity, (bool) $result, $actor)
            : $this->confirmCopied($edit, $campaign, $entity, (string) $result, $actor);
    }

    private function confirmDeleted(CampaignEntityEdit $edit, Campaign $campaign, CampaignPlatformEntity $entity, bool $gone, string $actor): CampaignEntityEdit
    {
        $edit->update(['details' => [...(array) $edit->details, 'pending' => ! $gone]]);

        // The local record follows only what the platform confirmed, as the
        // chat's delete does: the campaign is no longer on the platform, so it
        // goes back to a draft and leaves the manager. Nothing is left to read.
        if ($gone && $this->isTheCampaign($campaign, $entity)) {
            $campaign->forceFill(['external_campaign_id' => null, 'activated_at' => null, 'status' => 'draft'])->save();
            $campaign->platformEntities()->whereNull('removed_at')->update(['removed_at' => now(), 'last_changed_at' => now()]);
            $edit->update(['readback' => ['deleted' => true]]);

            return $this->confirmed($edit);
        }

        if (($after = $this->read($campaign, 'readback', $actor)) !== null) {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, 'The platform accepted the delete, but it could not be read back to confirm it. '.$after);
        }

        $entity->refresh();
        $edit->update(['readback' => ['status' => $entity->status, 'removed' => $entity->removed_at !== null]]);

        if ($entity->removed_at === null && ! in_array(strtoupper((string) $entity->status), ['DELETED', 'REMOVED', 'PENDING_DELETION'], true)) {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, 'The platform accepted the delete but still reports this object. It may still be processing.');
        }

        return $this->confirmed($edit);
    }

    private function confirmCopied(CampaignEntityEdit $edit, Campaign $campaign, CampaignPlatformEntity $entity, string $copyId, string $actor): CampaignEntityEdit
    {
        $originalBaseline = $entity->editBaseline();
        $originalAds = $campaign->platformEntities()->where('entity_type', 'ad')->where('parent_external_id', $entity->external_id)->whereNull('removed_at')->count();
        $edit->update(['details' => [...(array) $edit->details, 'copy_id' => $copyId]]);

        if ($this->isTheCampaign($campaign, $entity)) {
            return $this->confirmCampaignCopied($edit, $campaign, $copyId, $actor);
        }

        if (($after = $this->read($campaign, 'readback', $actor)) !== null) {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, sprintf('The platform made the copy (%s), but it could not be read back to confirm it. %s', $copyId, $after));
        }

        $copy = $campaign->platformEntities()
            ->where('entity_type', $entity->entity_type)
            ->where('external_id', $copyId)
            ->whereNull('removed_at')
            ->first();

        if ($copy === null) {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, sprintf('The platform made the copy (%s), but it did not show up when read back. It may take a moment to appear.', $copyId));
        }
        if ($entity->platform === 'linkedin' && $copy->status !== 'DRAFT') {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, 'The LinkedIn copy exists but its DRAFT state could not be confirmed. Review it before using it.');
        }
        if ($entity->platform === 'google' && $copy->status !== 'PAUSED') {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, 'The Google copy exists but its PAUSED state could not be confirmed. Review it before using it.');
        }

        $edit->update([
            'details' => [...(array) $edit->details, 'copy_id' => $copyId, 'copy_entity_id' => $copy->id, 'copy_name' => $copy->name],
            'readback' => [
                'status' => $copy->status,
                ...(isset($edit->details['conversion_event']) ? ['conversion_event' => data_get($copy->settings, 'promoted_object.custom_event_type')] : []),
            ],
        ]);

        if (isset($edit->details['conversion_event']) && (
            $copy->status !== 'PAUSED'
            || data_get($copy->settings, 'promoted_object.custom_event_type') !== $edit->details['conversion_event']
            || (string) data_get($copy->settings, 'promoted_object.pixel_id') !== (string) data_get($entity->settings, 'promoted_object.pixel_id')
            || $entity->refresh()->editBaseline() !== $originalBaseline
            || ($copiedAds = $campaign->platformEntities()->where('entity_type', 'ad')->where('parent_external_id', $copyId)->whereNull('removed_at')->get())->count() !== $originalAds
            || $copiedAds->contains(fn (CampaignPlatformEntity $ad): bool => $ad->status !== 'PAUSED')
        )) {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, 'The copy exists, but its paused status, pixel, conversion event, copied ads or unchanged original could not be confirmed. Review it before using it.');
        }

        return $this->confirmed($edit);
    }

    /** @param array<string, mixed> $details */
    private function validateActionDetails(CampaignPlatformEntity $entity, string $action, array $details): void
    {
        if ($details === []) {
            return;
        }
        if ($action !== CampaignEntityEdit::Duplicate || array_keys($details) !== ['conversion_event']) {
            throw new EditRefused('These copy options are not supported.');
        }
        if (($reason = $this->capabilities->eventCopyRefusal($entity)) !== null) {
            throw new EditRefused($reason);
        }
        $event = $details['conversion_event'];
        if (! is_string($event) || ! array_key_exists($event, EditCapabilities::options($entity, 'conversion_event'))
            || $event === data_get($entity->settings, 'promoted_object.custom_event_type')) {
            throw new EditRefused('Choose an available conversion event different from the original.');
        }
    }

    /**
     * A whole campaign's copy is a campaign of its own: it is brought under
     * management for the same owner and read, so it opens in the manager.
     */
    private function confirmCampaignCopied(CampaignEntityEdit $edit, Campaign $campaign, string $copyId, string $actor): CampaignEntityEdit
    {
        try {
            $copy = match ($campaign->platform) {
                'linkedin' => $this->importer->adoptLinkedIn($copyId, (string) $campaign->ad_account_id, $campaign->user),
                'google' => $this->importer->adoptGoogle($copyId, $campaign->user, (string) $campaign->ad_account_id),
                default => $this->importer->adopt($copyId, $campaign->user),
            };
        } catch (RuntimeException $exception) {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, sprintf('The platform made the copy (%s), but it could not be brought into the campaign manager: %s', $copyId, $exception->getMessage()));
        }

        $edit->update(['details' => ['copy_id' => $copyId, 'copy_campaign_id' => $copy->id, 'copy_name' => $copy->name]]);

        if (($after = $this->read($copy, 'import', $actor)) !== null) {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, sprintf('The platform made the copy (%s) and it was added here, but it could not be read yet. %s', $copy->name, $after));
        }
        if ($copy->platform === 'linkedin' && (
            $copy->platformEntities()->where('entity_type', 'campaign')->where('status', 'DRAFT')->doesntExist()
            || $copy->platformEntities()->where('entity_type', 'creative')->whereNull('removed_at')->where('status', '!=', 'DRAFT')->exists()
        )) {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, 'The LinkedIn campaign copy was imported, but its campaign or creatives are not confirmed DRAFT.');
        }
        if ($copy->platform === 'google' && (
            $copy->platformEntities()->where('entity_type', 'campaign')->where('status', 'PAUSED')->doesntExist()
            || $copy->platformEntities()->whereIn('entity_type', ['ad_group', 'ad', 'asset_group'])->whereNull('removed_at')->where(fn ($query) => $query->whereNull('status')->orWhere('status', '!=', 'PAUSED'))->exists()
        )) {
            return $this->close($edit, CampaignEntityEdit::Unconfirmed, 'The Google copy was imported, but all campaign and child PAUSED states could not be confirmed.');
        }

        $edit->update(['readback' => ['status' => $copy->platformEntities()->where('external_id', $copyId)->value('status')]]);

        return $this->confirmed($edit);
    }

    /**
     * Lifetime spend and impressions, read now. A delete is never offered on
     * the strength of a read that failed.
     *
     * @return array{spend: float, impressions: int, currency: string}
     */
    private function delivery(Campaign $campaign, CampaignPlatformEntity $entity, string $actor): array
    {
        try {
            $seen = $this->capabilities->writer((string) $campaign->platform)->delivery($campaign, $entity, $actor);
        } catch (EditRefused $exception) {
            throw $exception;
        } catch (Throwable $exception) {
            throw new EditRefused('What this has delivered could not be read just now, so nothing was sent: '.Str::limit($exception->getMessage(), 300));
        }

        return [...$seen, 'currency' => EditCapabilities::currency($entity)];
    }

    private function confirmed(CampaignEntityEdit $edit): CampaignEntityEdit
    {
        $edit->update(['state' => CampaignEntityEdit::Applied, 'verified_at' => now()]);

        return $edit;
    }

    private function actor(User $user): string
    {
        return sprintf('User#%d campaign manager', $user->id);
    }

    /** @param  array<string, mixed>  $patch */
    private function startsCampaign(Campaign $campaign, CampaignPlatformEntity $entity, array $patch): bool
    {
        return $this->isTheCampaign($campaign, $entity)
            && in_array($patch['status'] ?? null, EditCapabilities::LIVE, true);
    }

    /** The platform object this product's campaign record stands for, rather than a group above or a child below it. */
    private function isTheCampaign(Campaign $campaign, CampaignPlatformEntity $entity): bool
    {
        $own = LinkedInUrn::numericId((string) $campaign->external_campaign_id);

        return $entity->entity_type === 'campaign' && $own !== null && $own === LinkedInUrn::numericId($entity->external_id);
    }

    /**
     * After a refused write, what reached the platform anyway.
     *
     * A change that takes more than one call (a Google campaign's budget and
     * name are separate resources) can fail halfway, and saying "not applied"
     * about a budget that did change would be the worst kind of wrong. Read
     * once more and say which fields now hold the new value.
     */
    private function landedAnyway(CampaignEntityEdit $edit, CampaignPlatformEntity $entity, string $actor): string
    {
        if (count($edit->changes) < 2 && array_intersect(['budget_schedules', 'conversion_rules', 'conversion_goals', 'keywords'], array_keys($edit->changes)) === []) {
            return '';
        }

        if ($this->read($edit->campaign, 'readback', $actor) !== null) {
            return ' It could not be read back afterwards, so check the platform for which parts, if any, changed.';
        }

        $entity->refresh();
        $landed = [];
        $incomplete = [];
        $readback = [];

        foreach ($edit->changes as $field => $change) {
            $readback[$field] = EditCapabilities::current($entity, $field);

            if (EditCapabilities::same($entity, $field, $readback[$field], $change['after'])
                && ! EditCapabilities::same($entity, $field, $readback[$field], $change['before'])) {
                $landed[] = $field;
            } elseif (! EditCapabilities::same($entity, $field, $readback[$field], $change['before'])) {
                $incomplete[] = $field;
            }
        }

        if ($incomplete !== []) {
            $edit->update(['readback' => $readback]);

            return sprintf(' Partly applied: %s changed but did not reach the requested value. Review the reported values before trying again.', implode(', ', array_unique([...$landed, ...$incomplete])));
        }

        if ($landed === []) {
            return ' Nothing changed on the platform.';
        }

        $edit->update(['readback' => $readback]);

        return sprintf(' Partly applied: %s did change before it stopped; the rest did not.', implode(', ', array_map(fn (string $field): string => strtolower(Str::headline($field)), $landed)));
    }

    /** Null when the platform was read in full enough to rely on, otherwise why not. */
    private function read(Campaign $campaign, string $trigger, string $actor): ?string
    {
        try {
            $run = $this->synchronizer->sync($campaign, $trigger, $actor);
        } catch (InvalidArgumentException|RuntimeException $exception) {
            return $exception->getMessage();
        }

        return $run->succeeded() ? null : 'The platform could not be read: '.$run->error;
    }

    private function close(CampaignEntityEdit $edit, string $state, string $error): CampaignEntityEdit
    {
        $edit->update(['state' => $state, 'error' => $error]);

        return $edit;
    }
}
