<?php

namespace App\Campaigns\Manager\Editing;

use App\Campaigns\BudgetCeiling;
use App\Campaigns\Manager\Canonical;
use App\Campaigns\Manager\Editing\Writers\GoogleEntityWriter;
use App\Campaigns\Manager\Editing\Writers\LinkedInEntityWriter;
use App\Campaigns\Manager\Editing\Writers\MetaEntityWriter;
use App\Campaigns\Manager\ManagerFormat;
use App\Campaigns\Objectives;
use App\Campaigns\Platforms\Platforms;
use App\Models\CampaignEntityEdit;
use App\Models\CampaignPlatformDrift;
use App\Models\CampaignPlatformEntity;
use App\Support\CurrencyMinorUnits;
use Carbon\CarbonImmutable;
use Carbon\CarbonTimeZone;
use Closure;
use Illuminate\Contracts\Container\Container;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use JsonException;
use Throwable;

/**
 * What the manager may change, per platform, object type and field.
 *
 * The answer comes from here and never from what happens to be in a stored
 * settings snapshot: a field being readable says nothing about whether the
 * platform takes it back, or what else changing it would touch.
 *
 * Budgets and bids are offered only where the platform already holds one on
 * that object. Nothing here moves a budget between levels or switches between
 * daily and lifetime: a Meta ad set under a campaign budget has no budget to
 * edit, and a Google budget shared with other campaigns is not offered at all.
 */
class EditCapabilities
{
    /** @var array<string, array<string, list<string>>> */
    private const array FIELDS = [
        'meta' => [
            'campaign' => ['name', 'status', 'daily_budget', 'lifetime_budget', 'bid_strategy', 'spend_cap'],
            'ad_set' => [
                'name', 'status', 'daily_budget', 'lifetime_budget', 'optimization_goal', 'bid_strategy', 'bid_amount',
                'daily_min_spend_target', 'daily_spend_cap', 'lifetime_min_spend_target', 'lifetime_spend_cap',
                'frequency_max', 'frequency_days', 'countries', 'age_min', 'age_max', 'genders', 'publisher_platforms',
                'start_time', 'end_time',
                ...AdvancedEditFields::META_TARGETING,
                ...AdvancedEditFields::META_SETTINGS,
            ],
            'ad' => ['name', 'status'],
        ],
        'google' => [
            'campaign' => ['name', 'status', 'daily_budget', 'bid_strategy', 'target_cpa', 'target_roas', 'start_time', 'end_time', ...AdvancedEditFields::GOOGLE, ...AdvancedEditFields::GOOGLE_SETTINGS],
            'ad_group' => ['name', 'status', 'cpc_bid', ...AdvancedEditFields::GOOGLE_GROUP],
            'ad' => ['status'],
            'asset_group' => ['status'],
        ],
        'linkedin' => [
            'campaign_group' => ['name', 'status'],
            'campaign' => ['name', 'status', 'daily_budget', 'total_budget', 'bid_strategy', 'unit_cost', 'start_time', 'end_time', ...AdvancedEditFields::LINKEDIN],
            'creative' => ['name', 'status'],
        ],
    ];

    /** @var array<string, 'name'|'status'|'budget'|'bid'|'bid_strategy'|'optimization'|'spend'|'frequency'|'targeting'|'schedule'> */
    private const array CATEGORY = [
        'name' => 'name',
        'status' => 'status',
        'daily_budget' => 'budget',
        'lifetime_budget' => 'budget',
        'total_budget' => 'budget',
        'bid_amount' => 'bid',
        'cpc_bid' => 'bid',
        'unit_cost' => 'bid',
        'bid_strategy' => 'bid_strategy',
        'target_cpa' => 'bid_strategy',
        'target_roas' => 'bid_strategy',
        'optimization_goal' => 'optimization',
        'spend_cap' => 'spend',
        'daily_min_spend_target' => 'spend',
        'daily_spend_cap' => 'spend',
        'lifetime_min_spend_target' => 'spend',
        'lifetime_spend_cap' => 'spend',
        'frequency_max' => 'frequency',
        'frequency_days' => 'frequency',
        'countries' => 'targeting',
        'age_min' => 'targeting',
        'age_max' => 'targeting',
        'genders' => 'targeting',
        'publisher_platforms' => 'targeting',
        'geo_locations' => 'targeting',
        'excluded_geo_locations' => 'targeting',
        'locales' => 'targeting',
        'custom_audiences' => 'targeting',
        'excluded_custom_audiences' => 'targeting',
        'flexible_spec' => 'targeting',
        'advantage_audience' => 'targeting',
        'targeting_relaxation_types' => 'targeting',
        'facebook_positions' => 'targeting',
        'instagram_positions' => 'targeting',
        'audience_network_positions' => 'targeting',
        'messenger_positions' => 'targeting',
        'threads_positions' => 'targeting',
        'device_platforms' => 'targeting',
        'user_os' => 'targeting',
        'user_device' => 'targeting',
        'excluded_user_device' => 'targeting',
        'wireless_carrier' => 'targeting',
        'location_targets' => 'targeting',
        'excluded_locations' => 'targeting',
        'language_targets' => 'targeting',
        'device_exclusions' => 'targeting',
        'delivery_schedule' => 'schedule',
        'targeting_criteria' => 'targeting',
        'audience_expansion' => 'targeting',
        'offsite_delivery' => 'targeting',
        'frequency_optimization' => 'frequency',
        'adset_schedule' => 'schedule',
        'pacing_type' => 'bid_strategy',
        'roas_floor' => 'bid_strategy',
        'conversion_event' => 'optimization',
        'conversion_rules' => 'optimization',
        'budget_schedules' => 'budget',
        'audience_criteria' => 'targeting',
        'frequency_caps' => 'frequency',
        'network_settings' => 'targeting',
        'geo_target_type' => 'targeting',
        'keywords' => 'targeting',
        'conversion_goals' => 'optimization',
        'start_time' => 'schedule',
        'end_time' => 'schedule',
    ];

    /**
     * Moments rather than amounts. A Meta campaign's start and stop times are
     * left out on purpose: Graph derives them from the ad sets, so the ad set
     * is changed. A start only moves while it is still ahead.
     */
    private const array SCHEDULE = ['start_time', 'end_time'];

    /**
     * Statuses each platform's objects can be moved between from here, in
     * that platform's own words. Removing is not a status here: it cannot be
     * undone, and is offered separately.
     *
     * @var array<string, list<string>>
     */
    private const array STATUSES = [
        'meta' => ['ACTIVE', 'PAUSED', 'ARCHIVED'],
        'google' => ['ENABLED', 'PAUSED'],
        'linkedin' => ['ACTIVE', 'PAUSED', 'ARCHIVED'],
    ];

    /** Statuses that let an object deliver. */
    public const array LIVE = ['ACTIVE', 'ENABLED'];

    /** Paused this long or more, restarting resets delivery learning. */
    private const int STALE_PAUSE_DAYS = 7;

    /** How close to now an end may be set, so delivery is not cut mid-request. */
    private const int MIN_LEAD_MINUTES = 60;

    /** Spent over the whole run rather than per day. */
    private const array LIFETIME = ['lifetime_budget', 'total_budget'];

    /**
     * Where a field sits in the stored settings when it is not under its own
     * name. LinkedIn keeps money as {amount, currencyCode}.
     *
     * @var array<string, array<string, string>>
     */
    private const array PATHS = [
        'meta' => [
            'frequency_max' => 'frequency_control_specs.0.max_frequency',
            'frequency_days' => 'frequency_control_specs.0.interval_days',
            'countries' => 'targeting.geo_locations.countries',
            'age_min' => 'targeting.age_min',
            'age_max' => 'targeting.age_max',
            'genders' => 'targeting.genders',
            'publisher_platforms' => 'targeting.publisher_platforms',
        ],
        'linkedin' => [
            'daily_budget' => 'dailyBudget.amount',
            'total_budget' => 'totalBudget.amount',
            'unit_cost' => 'unitCost.amount',
            'bid_strategy' => 'optimizationTargetType',
            'start_time' => 'runSchedule.start',
            'end_time' => 'runSchedule.end',
        ],
    ];

    /**
     * Settings the platform itself will not change once the object is live,
     * with the reason shown next to them.
     *
     * @var array<string, array<string, array<string, string>>>
     */
    private const array SETTLED = [
        'meta' => [
            'campaign' => [
                'objective' => 'Meta fixes the objective once a campaign is published. A different objective needs a new campaign.',
                'buying_type' => 'Meta fixes the buying type once a campaign is published.',
            ],
            'ad_set' => [
                'destination_type' => 'Meta fixes where an ad set sends people once it is published.',
                'is_dynamic_creative' => 'Meta fixes whether an ad set uses dynamic creative when it is created.',
                'promoted_object' => 'The pixel, page, app and destination stay fixed. Only the website conversion event is changed separately.',
                'billing_event' => 'The billing event is read-only for post-launch editing.',
                'attribution_spec' => 'The attribution setting is read-only for post-launch editing.',
            ],
        ],
        'google' => [
            'campaign' => ['channel_type' => 'Google fixes the campaign type once it is created.'],
            'ad_group' => ['type' => 'Google fixes the ad group type once it is created.'],
        ],
        'linkedin' => [
            'campaign' => [
                'objectiveType' => 'LinkedIn fixes the objective once a campaign has launched.',
                'type' => 'LinkedIn fixes the campaign type once it is created.',
            ],
        ],
    ];

    /**
     * Settings the platform lets change but this product does not edit yet.
     * Changing them in the platform's own tool is safe: the next read records
     * it, and any open proposal here is held back.
     *
     * @var array<string, array<string, list<string>>>
     */
    private const array LATER = [
        'meta' => [
            'campaign' => ['special_ad_categories'],
        ],
    ];

    /**
     * What can be done to each kind of object besides changing its fields.
     *
     * @var array<string, array<string, list<string>>>
     */
    private const array ACTIONS = [
        'meta' => ['campaign' => ['delete', 'duplicate'], 'ad_set' => ['delete', 'duplicate'], 'ad' => ['delete', 'duplicate']],
        'google' => ['campaign' => ['delete', 'duplicate'], 'ad_group' => ['delete', 'duplicate'], 'ad' => ['delete', 'duplicate'], 'asset_group' => ['duplicate']],
        'linkedin' => ['campaign_group' => ['delete'], 'campaign' => ['delete', 'duplicate'], 'creative' => ['delete', 'duplicate']],
    ];

    /** Statuses that mean the object is already on its way out. */
    private const array GOING = ['DELETED', 'REMOVED', 'PENDING_DELETION'];

    /**
     * Performance goals a Meta ad set can be moved between, by the campaign's
     * objective and where the ad sends people. Only website, on-ad (lead form)
     * and on-post/on-video destinations are listed; messaging, app and call
     * destinations have goals tied to setup that is done in Ads Manager.
     * VALUE is left out, like a ROAS bid: it needs value optimisation set up.
     *
     * @var array<string, array<string, list<string>>>
     */
    private const array META_GOALS = [
        'OUTCOME_AWARENESS' => ['' => ['REACH', 'IMPRESSIONS', 'AD_RECALL_LIFT', 'THRUPLAY']],
        'OUTCOME_TRAFFIC' => ['WEBSITE' => ['LANDING_PAGE_VIEWS', 'LINK_CLICKS', 'REACH', 'IMPRESSIONS']],
        'OUTCOME_ENGAGEMENT' => [
            'ON_POST' => ['POST_ENGAGEMENT', 'REACH', 'IMPRESSIONS'],
            'ON_VIDEO' => ['THRUPLAY', 'TWO_SECOND_CONTINUOUS_VIDEO_VIEWS'],
        ],
        'OUTCOME_LEADS' => [
            'WEBSITE' => ['OFFSITE_CONVERSIONS', 'LANDING_PAGE_VIEWS', 'LINK_CLICKS', 'REACH', 'IMPRESSIONS'],
            'ON_AD' => ['LEAD_GENERATION', 'QUALITY_LEAD'],
        ],
        'OUTCOME_SALES' => ['WEBSITE' => ['OFFSITE_CONVERSIONS', 'LANDING_PAGE_VIEWS', 'LINK_CLICKS', 'REACH', 'IMPRESSIONS']],
    ];

    /** @var array<string, string> */
    private const array META_GOAL_LABELS = [
        'REACH' => 'Daily unique reach',
        'IMPRESSIONS' => 'Impressions',
        'AD_RECALL_LIFT' => 'Ad recall lift',
        'THRUPLAY' => 'ThruPlay views',
        'TWO_SECOND_CONTINUOUS_VIDEO_VIEWS' => '2-second continuous video views',
        'LANDING_PAGE_VIEWS' => 'Landing page views',
        'LINK_CLICKS' => 'Link clicks',
        'POST_ENGAGEMENT' => 'Post engagement',
        'OFFSITE_CONVERSIONS' => 'Conversions',
        'LEAD_GENERATION' => 'Leads',
        'QUALITY_LEAD' => 'Conversion leads',
        'VALUE' => 'Conversion value',
    ];

    /** Goals that count a result through the ad set's pixel and event. */
    private const array PIXEL_GOALS = ['OFFSITE_CONVERSIONS', 'VALUE'];

    /** Meta's "no spending limit": what is sent to take a campaign's cap away. */
    public const string META_NO_SPEND_CAP = '922337203685478';

    /** The smallest campaign spending limit Meta takes, in USD. */
    private const float META_MIN_SPEND_CAP_USD = 100.0;

    /** Meta's bounds on a reach ad set's frequency cap. */
    private const int FREQUENCY_MAX = 90;

    /** Where a Meta ad set can show, value => label. None ticked is Advantage+ placements. */
    public const array META_PLATFORMS = [
        'facebook' => 'Facebook',
        'instagram' => 'Instagram',
        'audience_network' => 'Audience Network',
        'messenger' => 'Messenger',
        'threads' => 'Threads',
    ];

    /** Meta's own bounds on an ad set's age range; 65 means 65 and older. */
    private const int META_AGE_MIN = 18;

    private const int META_AGE_MAX = 65;

    /** The people an ad set reaches, by Meta's gender codes. */
    private const array META_GENDERS = ['all' => 'Everyone', 'men' => 'Men', 'women' => 'Women'];

    /** Ad set spend limits, as minimum => cap for each kind of campaign budget. */
    private const array SPEND_LIMITS = [
        'daily_budget' => ['daily_min_spend_target', 'daily_spend_cap'],
        'lifetime_budget' => ['lifetime_min_spend_target', 'lifetime_spend_cap'],
    ];

    /** Meta strategies that read bid_amount. The others ignore or refuse it. */
    private const array META_BID_STRATEGIES = ['LOWEST_COST_WITH_BID_CAP', 'COST_CAP', 'TARGET_COST'];

    /**
     * Strategies that can be chosen from here, value => label in the
     * platform's own terms. A Meta ROAS goal is offered only for value
     * optimization, alongside its required floor.
     *
     * @var array<string, array<string, string>>
     */
    private const array STRATEGIES = [
        'meta' => [
            'LOWEST_COST_WITHOUT_CAP' => 'Highest volume (no cap)',
            'COST_CAP' => 'Cost per result goal (cost cap)',
            'LOWEST_COST_WITH_BID_CAP' => 'Bid cap',
            'LOWEST_COST_WITH_MIN_ROAS' => 'ROAS goal',
        ],
        'google' => [
            'MAXIMIZE_CONVERSIONS' => 'Maximize conversions',
            'MAXIMIZE_CONVERSION_VALUE' => 'Maximize conversion value',
            'TARGET_SPEND' => 'Maximize clicks',
            'MANUAL_CPC' => 'Manual CPC',
        ],
    ];

    /** Google channels whose bidding is changed here, with the strategies each one runs. */
    private const array GOOGLE_CHANNEL_STRATEGIES = [
        'SEARCH' => ['MAXIMIZE_CONVERSIONS', 'MAXIMIZE_CONVERSION_VALUE', 'TARGET_SPEND', 'MANUAL_CPC'],
        'DISPLAY' => ['MAXIMIZE_CONVERSIONS', 'MAXIMIZE_CONVERSION_VALUE', 'TARGET_SPEND', 'MANUAL_CPC'],
        'PERFORMANCE_MAX' => ['MAXIMIZE_CONVERSIONS', 'MAXIMIZE_CONVERSION_VALUE'],
    ];

    /**
     * LinkedIn's optimizationTargetType values allowed for each objective, as
     * its "allowable combinations" table lists them. MAX_QUALIFIED_LEAD is
     * left out because it depends on the API version; it is kept when a
     * campaign already has it.
     *
     * @var array<string, list<string>>
     */
    private const array LINKEDIN_STRATEGIES = [
        'BRAND_AWARENESS' => ['NONE', 'MAX_IMPRESSION', 'TARGET_COST_PER_IMPRESSION', 'CAP_COST_AND_MAXIMIZE_IMPRESSIONS'],
        'CREATIVE_ENGAGEMENT' => ['NONE', 'MAX_CONVERSION', 'MAX_IMPRESSION', 'MAX_CLICK', 'ENHANCED_CONVERSION', 'TARGET_COST_PER_CLICK'],
        'ENGAGEMENT' => ['NONE', 'ENHANCED_CONVERSION', 'MAX_CLICK', 'TARGET_COST_PER_CLICK', 'CAP_COST_AND_MAXIMIZE_CLICKS'],
        'JOB_APPLICANT' => ['NONE', 'MAX_CLICK'],
        'LEAD_GENERATION' => ['NONE', 'ENHANCED_CONVERSION', 'MAX_LEAD'],
        'TALENT_LEAD' => ['NONE', 'MAX_CLICK'],
        'VIDEO_VIEW' => ['NONE', 'MAX_VIDEO_VIEW', 'TARGET_COST_PER_VIDEO_VIEW', 'CAP_COST_AND_MAXIMIZE_VIDEO_VIEWS'],
        'WEBSITE_CONVERSION' => ['NONE', 'ENHANCED_CONVERSION', 'MAX_CONVERSION'],
        'WEBSITE_TRAFFIC' => ['NONE', 'MAX_CLICK', 'MAX_CONVERSION', 'MAX_IMPRESSION', 'ENHANCED_CONVERSION'],
        'WEBSITE_VISIT' => ['NONE', 'MAX_CLICK', 'ENHANCED_CONVERSION', 'TARGET_COST_PER_CLICK', 'CAP_COST_AND_MAXIMIZE_CLICKS'],
    ];

    /**
     * The amount each platform's strategies read. Google's targets are
     * optional and clearing one is a change of its own; Meta's and LinkedIn's
     * amounts are required by the strategies that use them and never cleared.
     *
     * @var array<string, list<string>>
     */
    private const array STRATEGY_AMOUNTS = [
        'meta' => ['bid_amount'],
        'google' => ['target_cpa', 'target_roas'],
        'linkedin' => ['unit_cost'],
    ];

    /** @var array<string, class-string<EntityWriter>> */
    private const array WRITERS = [
        'meta' => MetaEntityWriter::class,
        'google' => GoogleEntityWriter::class,
        'linkedin' => LinkedInEntityWriter::class,
    ];

    /**
     * Longest name accepted, in characters. The stored copy keeps 250, so a
     * longer name could never be confirmed on read-back; LinkedIn refuses
     * anything over 200 bytes.
     *
     * @var array<string, int>
     */
    private const array NAME_LIMIT = ['meta' => 250, 'google' => 250, 'linkedin' => 200];

    public function __construct(
        private readonly Container $container,
        private readonly Platforms $platforms,
    ) {}

    public function platformEnabled(?string $platform): bool
    {
        return isset(self::FIELDS[(string) $platform])
            && in_array((string) $platform, (array) config('campaign-manager.edit_platforms', []), true);
    }

    public function categoryEnabled(string $field): bool
    {
        return in_array(self::CATEGORY[$field] ?? null, (array) config('campaign-manager.edit_categories', []), true);
    }

    public static function isMoney(string $field): bool
    {
        return $field === 'target_cpa' || in_array(self::CATEGORY[$field] ?? null, ['budget', 'bid', 'spend'], true);
    }

    /** A limit that only holds spend back, and can be left empty for none. */
    public static function isSpendLimit(string $field): bool
    {
        return (self::CATEGORY[$field] ?? null) === 'spend';
    }

    /** Who sees the ads or where: a part of a Meta ad set's targeting. */
    public static function isTargeting(string $field): bool
    {
        return (self::CATEGORY[$field] ?? null) === 'targeting';
    }

    public static function isBid(string $field): bool
    {
        return (self::CATEGORY[$field] ?? null) === 'bid';
    }

    /**
     * The statuses this object can be moved to, value => label.
     *
     * @return array<string, string>
     */
    public static function statusOptions(CampaignPlatformEntity $entity): array
    {
        $options = [];

        foreach (self::STATUSES[$entity->platform] ?? [] as $status) {
            $options[$status] = match ($status) {
                'ACTIVE', 'ENABLED' => 'On (delivering)',
                'PAUSED' => 'Paused',
                'ARCHIVED' => 'Archived',
                default => Str::headline(strtolower($status)),
            };
        }

        return $options;
    }

    /**
     * The choices for a field picked from a list, value => label; empty for a
     * field typed in.
     *
     * @return array<string, string>
     */
    public static function options(CampaignPlatformEntity $entity, string $field): array
    {
        return match ($field) {
            'status' => self::statusOptions($entity),
            'bid_strategy' => self::strategyOptions($entity),
            'optimization_goal' => self::goalOptions($entity),
            'conversion_event' => self::conversionEventOptions($entity),
            'genders' => self::META_GENDERS,
            'advantage_audience', 'audience_expansion', 'offsite_delivery' => [0 => 'Off', 1 => 'On'],
            default => [],
        };
    }

    /** @return array<string, string> */
    private static function conversionEventOptions(CampaignPlatformEntity $entity): array
    {
        if (strtoupper((string) data_get($entity->settings, 'optimization_goal')) === 'VALUE') {
            return ['PURCHASE' => 'Purchase'];
        }

        $options = [];
        foreach (Objectives::selectableEventNames(self::metaObjective($entity)) as $name) {
            $options[Objectives::eventType($name)] = (string) preg_replace('/(?<!^)([A-Z])/', ' $1', $name);
        }

        return $options;
    }

    /**
     * The performance goals this Meta ad set can be moved to, value => label.
     * The one it has now is always listed first.
     *
     * @return array<string, string>
     */
    public static function goalOptions(CampaignPlatformEntity $entity): array
    {
        $values = self::META_GOALS[(string) self::metaObjective($entity)][self::destination($entity)] ?? [];

        if (! self::tracksPixel($entity)) {
            $values = array_values(array_diff($values, self::PIXEL_GOALS));
        }

        $current = strtoupper((string) data_get($entity->settings, 'optimization_goal'));

        if ($current !== '' && ! in_array($current, $values, true)) {
            array_unshift($values, $current);
        }

        $options = [];

        foreach ($values as $value) {
            $options[$value] = self::goalLabel($value);
        }

        return $options;
    }

    public static function goalLabel(?string $goal): string
    {
        $goal = strtoupper((string) $goal);

        return self::META_GOAL_LABELS[$goal] ?? ManagerFormat::readable($goal);
    }

    /** The objective of the Meta campaign this ad set is in, as last read. */
    private static function metaObjective(CampaignPlatformEntity $entity): ?string
    {
        $objective = data_get(self::parentSettings($entity), 'objective');

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

    /**
     * The settings of the Meta campaign an ad set is in, as last read.
     *
     * @return array<string, mixed>
     */
    private static function parentSettings(CampaignPlatformEntity $entity): array
    {
        return (array) CampaignPlatformEntity::query()
            ->where('campaign_id', $entity->campaign_id)
            ->where('entity_type', 'campaign')
            ->where('external_id', $entity->parent_external_id)
            ->first(['settings'])?->settings;
    }

    /** Where the ad sends people; awareness has none, which reads as "". */
    private static function destination(CampaignPlatformEntity $entity): string
    {
        $destination = strtoupper((string) data_get($entity->settings, 'destination_type'));

        return in_array($destination, ['', 'UNDEFINED'], true) && self::metaObjective($entity) !== 'OUTCOME_AWARENESS'
            ? 'WEBSITE'
            : ($destination === 'UNDEFINED' ? '' : $destination);
    }

    private static function tracksPixel(CampaignPlatformEntity $entity): bool
    {
        return filled(data_get($entity->settings, 'promoted_object.pixel_id'))
            && filled(data_get($entity->settings, 'promoted_object.custom_event_type'));
    }

    /**
     * The bid strategies this object can be moved to, value => label. The one
     * it has now is always listed, so the form never shows a different value
     * from the platform's.
     *
     * @return array<string, string>
     */
    public static function strategyOptions(CampaignPlatformEntity $entity): array
    {
        $values = match ($entity->platform) {
            'meta' => array_keys(self::STRATEGIES['meta']),
            'google' => self::GOOGLE_CHANNEL_STRATEGIES[strtoupper((string) data_get($entity->settings, 'channel_type'))] ?? [],
            'linkedin' => self::LINKEDIN_STRATEGIES[strtoupper((string) data_get($entity->settings, 'objectiveType'))] ?? [],
            default => [],
        };

        if ($entity->platform === 'meta' && ($entity->entity_type !== 'ad_set' || strtoupper((string) data_get($entity->settings, 'optimization_goal')) !== 'VALUE')) {
            $values = array_values(array_diff($values, ['LOWEST_COST_WITH_MIN_ROAS']));
        }

        $current = self::current($entity, 'bid_strategy');

        if (is_string($current) && $current !== '' && ! in_array($current, $values, true)) {
            array_unshift($values, $current);
        }

        $options = [];

        foreach ($values as $value) {
            $options[$value] = self::strategyLabel($entity->platform, $value);
        }

        return $options;
    }

    public static function strategyLabel(?string $platform, ?string $strategy): string
    {
        $strategy = strtoupper((string) $strategy);

        if (isset(self::STRATEGIES[$platform][$strategy])) {
            return self::STRATEGIES[$platform][$strategy];
        }

        if ($platform === 'linkedin') {
            $result = fn (string $suffix): string => strtolower(ManagerFormat::readable(Str::singular($suffix)));

            return match (true) {
                $strategy === 'NONE' => 'Manual bidding',
                $strategy === 'ENHANCED_CONVERSION' => 'Manual bidding, adjusted for conversions',
                str_starts_with($strategy, 'MAX_') => sprintf('Maximum delivery (%s)', Str::plural($result(Str::after($strategy, 'MAX_')))),
                str_starts_with($strategy, 'CAP_COST_AND_MAXIMIZE_') => sprintf('Cost cap (per %s)', $result(Str::after($strategy, 'CAP_COST_AND_MAXIMIZE_'))),
                str_starts_with($strategy, 'TARGET_COST_PER_') => sprintf('Target cost (per %s)', $result(Str::after($strategy, 'TARGET_COST_PER_'))),
                default => ManagerFormat::readable($strategy),
            };
        }

        return ManagerFormat::readable($strategy);
    }

    /**
     * The amount a strategy reads, and whether it cannot run without one.
     *
     * @return array{field: string, required: bool}|null
     */
    public static function strategyAmount(CampaignPlatformEntity $entity, ?string $strategy): ?array
    {
        $strategy = strtoupper((string) $strategy);

        return match ($entity->platform) {
            'meta' => $strategy === 'LOWEST_COST_WITH_MIN_ROAS'
                ? ['field' => 'roas_floor', 'required' => true]
                : (in_array($strategy, self::META_BID_STRATEGIES, true) ? ['field' => 'bid_amount', 'required' => true] : null),
            'google' => match ($strategy) {
                'MAXIMIZE_CONVERSIONS' => ['field' => 'target_cpa', 'required' => false],
                'MAXIMIZE_CONVERSION_VALUE' => ['field' => 'target_roas', 'required' => false],
                default => null,
            },
            'linkedin' => str_starts_with($strategy, 'MAX_') ? null : ['field' => 'unit_cost', 'required' => true],
            default => null,
        };
    }

    /**
     * Amounts a strategy on this platform could read; the ones the chosen
     * strategy does not are hidden in the form and never sent.
     *
     * @return list<string>
     */
    public static function strategyAmounts(CampaignPlatformEntity $entity): array
    {
        return [...(self::STRATEGY_AMOUNTS[$entity->platform] ?? []), ...($entity->platform === 'meta' ? ['roas_floor'] : [])];
    }

    /**
     * The change as it will be sent: an amount the resulting strategy does
     * not read is dropped, and so is clearing one that cannot be cleared.
     *
     * @param  array<string, array{before: mixed, after: mixed}>  $changes
     * @return array<string, array{before: mixed, after: mixed}>
     */
    public function prune(CampaignPlatformEntity $entity, array $changes): array
    {
        if (! in_array('bid_strategy', $this->editableFields($entity), true)) {
            return $changes;
        }

        $strategy = $changes['bid_strategy']['after'] ?? self::current($entity, 'bid_strategy');
        $reads = self::strategyAmount($entity, is_string($strategy) ? $strategy : null);

        foreach (self::strategyAmounts($entity) as $field) {
            if (! isset($changes[$field])) {
                continue;
            }

            if ($field !== ($reads['field'] ?? null) || ($changes[$field]['after'] === null && $reads['required'])) {
                unset($changes[$field]);
            }
        }

        return self::ordered($entity, $changes);
    }

    /**
     * Values keyed by field, in the order the form lists the fields. A JSON
     * column does not keep key order, so this is applied where they are shown.
     *
     * @template TValue
     *
     * @param  array<string, TValue>  $changes
     * @return array<string, TValue>
     */
    public static function ordered(?CampaignPlatformEntity $entity, array $changes): array
    {
        $order = array_flip(self::FIELDS[$entity?->platform][$entity?->entity_type] ?? []);
        uksort($changes, fn (string $a, string $b): int => ($order[$a] ?? PHP_INT_MAX) <=> ($order[$b] ?? PHP_INT_MAX));

        return $changes;
    }

    /** One value of a field as a person reads it: money with its currency, a strategy by its name. */
    public static function display(CampaignPlatformEntity $entity, string $field, mixed $value): string
    {
        return match (true) {
            self::isMoney($field) && is_numeric($value) => self::money((float) $value, $currency = self::currency($entity)).' '.$currency,
            self::isSchedule($field) => self::showMoment($entity, $value),
            $field === 'status' => self::statusOptions($entity)[$value] ?? ManagerFormat::readable($value),
            $field === 'bid_strategy' => blank($value) ? '—' : self::strategyLabel($entity->platform, (string) $value),
            $field === 'optimization_goal' => blank($value) ? '—' : self::goalLabel((string) $value),
            in_array($field, ['target_cpa', 'target_roas'], true) && blank($value) => 'No target',
            (self::CATEGORY[$field] ?? null) === 'spend' && blank($value) => 'No limit',
            (self::CATEGORY[$field] ?? null) === 'frequency' && blank($value) => 'No cap',
            $field === 'frequency_max' => sprintf('%d %s', (int) $value, Str::plural('impression', (int) $value)),
            $field === 'frequency_days' => sprintf('every %d %s', (int) $value, Str::plural('day', (int) $value)),
            $field === 'countries' => ($list = self::normalize($entity, $field, $value)) === [] ? '—' : implode(', ', $list),
            $field === 'genders' => self::META_GENDERS[self::normalize($entity, $field, $value)] ?? '—',
            $field === 'publisher_platforms' => ($list = self::normalize($entity, $field, $value)) === []
                ? 'Automatic (Advantage+ placements)'
                : implode(', ', array_map(fn (string $platform): string => self::META_PLATFORMS[$platform] ?? ManagerFormat::readable($platform), $list)),
            $field === 'age_max' && (int) $value >= self::META_AGE_MAX => self::META_AGE_MAX.'+',
            $field === 'target_roas' && is_numeric($value) => rtrim(rtrim(number_format((float) $value, 2, '.', ''), '0'), '.').'× ('.round((float) $value * 100).'%)',
            default => ManagerFormat::value($value),
        };
    }

    public static function isSchedule(string $field): bool
    {
        return in_array($field, self::SCHEDULE, true);
    }

    public static function isBudget(string $field): bool
    {
        return (self::CATEGORY[$field] ?? null) === 'budget';
    }

    /** @return list<string> */
    public function editableFields(CampaignPlatformEntity $entity): array
    {
        if ($this->refusal($entity) !== null) {
            return [];
        }

        return array_values(array_filter(
            self::FIELDS[$entity->platform][$entity->entity_type],
            fn (string $field): bool => $this->fieldRefusal($entity, $field) === null,
        ));
    }

    /**
     * Fields this object has but that cannot be changed from here, with why.
     * Money fields the object does not use at all are left out, and the ad
     * set spend limits and the frequency cap are each listed once, as
     * spend_limits and frequency_cap.
     *
     * @return array<string, string>
     */
    public function lockedFields(CampaignPlatformEntity $entity): array
    {
        if ($this->refusal($entity) !== null) {
            return [];
        }

        $locked = [];

        foreach (self::FIELDS[$entity->platform][$entity->entity_type] as $field) {
            if (self::isMoney($field) && ! self::isSpendLimit($field) && ! self::holds($entity, $field)
                && ! ($entity->platform === 'meta' && $entity->entity_type === 'ad_set' && $field === 'daily_budget')) {
                continue;
            }

            if ($reason = $this->fieldRefusal($entity, $field)) {
                // Paired fields share one reason, so each pair is listed once.
                $key = match (true) {
                    self::isSpendLimit($field) && $field !== 'spend_cap' => 'spend_limits',
                    (self::CATEGORY[$field] ?? null) === 'frequency' => 'frequency_cap',
                    default => $field,
                };
                $locked[$key] ??= $reason;
            }
        }

        $settings = (array) $entity->settings;
        $present = fn (string $setting): bool => array_key_exists($setting, $settings) && $settings[$setting] !== null && $settings[$setting] !== [] && $settings[$setting] !== '';

        foreach (self::SETTLED[$entity->platform][$entity->entity_type] ?? [] as $setting => $reason) {
            if ($present($setting)) {
                $locked[$setting] = $reason;
            }
        }

        foreach (self::LATER[$entity->platform][$entity->entity_type] ?? [] as $setting) {
            if ($present($setting)) {
                $locked[$setting] = sprintf('Not changeable from the campaign manager yet. Changing it in %s is safe; the next read picks it up.', ManagerFormat::platform($entity->platform));
            }
        }

        if ($entity->platform === 'meta' && $entity->entity_type === 'ad_set') {
            $locked['exclusions'] = 'Meta removed detailed-targeting exclusions from the supported API. Saved custom-audience and geographic exclusions remain editable.';
            $locked['value_rule_set_id'] = 'The configured Meta API version does not expose a writable value-rule-set field on ad sets.';
        }
        if ($entity->platform === 'linkedin' && $entity->entity_type === 'campaign') {
            $locked['pacingStrategy'] = 'LinkedIn pacing strategy is set at creation only. A draft copy preserves it; it cannot be edited in place.';
        }

        return $locked;
    }

    /** Why nothing on this object can be changed here, or null when something might be. */
    public function refusal(CampaignPlatformEntity $entity): ?string
    {
        if (! $this->platformEnabled($entity->platform)) {
            return 'Editing from the campaign manager is not switched on for this platform.';
        }

        if (! isset(self::FIELDS[$entity->platform][$entity->entity_type])) {
            return 'This kind of object cannot be changed from the campaign manager yet.';
        }

        if ($entity->removed_at !== null) {
            return 'This object was not on the platform at the last read.';
        }

        return null;
    }

    /** Why this one field cannot be changed on this object, or null when it can. */
    public function fieldRefusal(CampaignPlatformEntity $entity, string $field): ?string
    {
        if (! in_array($field, self::FIELDS[$entity->platform][$entity->entity_type] ?? [], true)) {
            return 'This field cannot be changed from the campaign manager.';
        }

        if ($entity->platform === 'meta' && $field === 'optimization_goal') {
            return 'The optimization goal is read-only after launch. Use a paused ad-set copy for a different conversion event.';
        }
        if ($entity->platform === 'meta' && $field === 'conversion_event') {
            return 'Meta fixes the conversion event after publication. Use a paused copy with a different event; the original stays unchanged.';
        }

        if (! $this->categoryEnabled($field)) {
            return sprintf('%s changes are not switched on for the campaign manager.', Str::ucfirst(str_replace('_', ' ', self::CATEGORY[$field])));
        }

        if (AdvancedEditFields::handles($field)) {
            return AdvancedEditFields::refusal($entity, $field);
        }

        if ($field === 'status') {
            return $this->statusRefusal($entity);
        }

        if (self::isSchedule($field)) {
            return $this->scheduleRefusal($entity, $field);
        }

        if ($field === 'optimization_goal') {
            return $this->goalRefusal($entity);
        }

        if ((self::CATEGORY[$field] ?? null) === 'frequency') {
            return $this->frequencyRefusal($entity);
        }

        if (self::isTargeting($field)) {
            return $this->targetingRefusal($entity, $field);
        }

        if ((self::CATEGORY[$field] ?? null) === 'spend' && ($reason = $this->spendRefusal($entity, $field)) !== null) {
            return $reason;
        }

        if ($field === 'bid_strategy' || $field === 'target_cpa' || $field === 'target_roas') {
            if (($reason = $this->strategyRefusal($entity)) !== null || $field !== 'target_cpa') {
                return $reason;
            }
        }

        // An amount set together with the strategy that reads it may be empty
        // now: switching to bid cap is exactly when a bid is first added.
        $withStrategy = $this->pairsWithStrategy($entity, $field);

        if (! self::isMoney($field)) {
            return null;
        }

        if (! self::holds($entity, $field) && ! $withStrategy && (self::CATEGORY[$field] ?? null) !== 'spend') {
            return $entity->platform === 'meta' && $entity->entity_type === 'ad_set' && self::isBudget($field)
                ? 'The budget is held on the campaign, so this ad set has none of its own to change.'
                : sprintf('This %s has no %s set, and one is not added from here.', strtolower(ManagerFormat::type($entity->entity_type)), strtolower(ManagerFormat::field($field)));
        }

        $campaignCurrency = strtoupper((string) ($entity->campaign?->currency ?: 'USD'));

        if (self::currency($entity) !== $campaignCurrency) {
            return sprintf('The platform reports this amount in %s, not the %s this campaign was set up with, so it is not changed from here.', self::currency($entity), $campaignCurrency);
        }

        if ($entity->platform === 'google' && $field === 'daily_budget') {
            $sharedBy = data_get($entity->settings, 'budget_shared_by');

            if (! is_numeric($sharedBy)) {
                return 'Google did not say whether this budget is shared with other campaigns, so it is not changed from here.';
            }

            if ((int) $sharedBy > 1) {
                return sprintf('This budget is shared by %d campaigns; changing it here would change all of them.', (int) $sharedBy);
            }

            if (self::googleBudgetId($entity) === null) {
                return 'Google did not report which budget this campaign uses.';
            }
        }

        if ($entity->platform === 'meta' && $field === 'bid_amount' && ! $withStrategy
            && ! in_array(strtoupper((string) data_get($entity->settings, 'bid_strategy')), self::META_BID_STRATEGIES, true)) {
            return 'The bid strategy on this ad set does not use a bid amount.';
        }

        if (in_array($field, self::LIFETIME, true) && $this->runDays($entity) === null) {
            return 'There is no end date, so a total budget cannot be checked against the daily ceiling.';
        }

        return null;
    }

    /**
     * Server-side rules for each field, keyed as the values arrive.
     *
     * @return array<string, list<mixed>>
     */
    /**
     * @param  array<string, mixed>  $proposed  the other values in the same change, so a new start is checked against a new end
     */
    public function rules(CampaignPlatformEntity $entity, array $proposed = []): array
    {
        $rules = [];

        foreach ($this->editableFields($entity) as $field) {
            $rules[$field] = match (true) {
                $field === 'name' => $this->nameRules($entity),
                $field === 'status' => ['required', 'string', Rule::in(array_keys(self::statusOptions($entity)))],
                $field === 'bid_strategy' => [
                    'required', 'string', Rule::in(array_keys(self::strategyOptions($entity))),
                    fn (string $attribute, mixed $value, Closure $fail) => ($problem = $this->strategyProblem($entity, strtoupper((string) $value), $proposed)) !== null ? $fail($problem) : null,
                ],
                $field === 'target_roas' => ['nullable', 'numeric', 'gt:0', 'max:1000'],
                $field === 'optimization_goal' => ['required', 'string', Rule::in(array_keys(self::goalOptions($entity)))],
                AdvancedEditFields::handles($field) => [
                    in_array($field, ['geo_locations', 'targeting_criteria', 'pacing_type', 'advantage_audience', 'audience_expansion', 'conversion_event', 'roas_floor'], true) ? 'required' : 'present',
                    AdvancedEditFields::rule($entity, $field, $proposed),
                ],
                (self::CATEGORY[$field] ?? null) === 'spend' => $this->spendRules($entity, $field, $proposed),
                (self::CATEGORY[$field] ?? null) === 'frequency' => $this->frequencyRules($entity, $field, $proposed),
                self::isTargeting($field) => $this->targetingRules($entity, $field, $proposed),
                self::isSchedule($field) => $this->scheduleRules($entity, $field, $proposed),
                default => $this->moneyRules($entity, $field, required: ! $this->pairsWithStrategy($entity, $field)),
            };
            if ($field === 'daily_budget' && $entity->platform === 'meta' && ! array_key_exists('budget_schedules', $proposed)) {
                $rules[$field][] = function (string $attribute, mixed $value, Closure $fail) use ($entity): void {
                    if (is_numeric($value) && (float) $value === (float) self::current($entity, 'daily_budget')) {
                        return;
                    }
                    if ($entity->entity_type === 'ad_set' && array_key_exists('budget_schedules', (array) $entity->settings)
                        && ! is_array(data_get($entity->settings, 'budget_schedules'))) {
                        $fail('Read the complete budget schedules before changing the daily budget.');

                        return;
                    }
                    if (is_numeric($value) && ($problem = AdvancedEditFields::budgetLimitProblem(
                        $entity, (array) data_get($entity->settings, 'budget_schedules', []), (float) $value,
                    )) !== null) {
                        $fail($problem);
                    }
                };
            }
        }

        return $rules;
    }

    /**
     * What the user has to acknowledge before this change is sent. Empty when
     * nothing in it needs more than the usual review.
     *
     * @param  array<string, array{before: mixed, after: mixed}>  $changes
     * @return list<string>
     */
    public function confirmations(CampaignPlatformEntity $entity, array $changes): array
    {
        $notes = [];
        $currency = self::currency($entity);
        $percentLimit = (float) config('campaign-manager.confirm_change_percent', 20);
        $rate = BudgetCeiling::conversionRate($entity->campaign) ?? 1.0;
        $loud = (float) config('platforms.guardrails.confirm_daily_budget_above', 50) * $rate;

        $schedule = array_intersect_key($changes, array_flip(self::SCHEDULE));

        if ($schedule !== []) {
            array_push($notes, ...$this->scheduleConfirmations($entity, $schedule, $loud));
        }

        $targeting = array_filter($changes, fn (string $field): bool => self::isTargeting($field), ARRAY_FILTER_USE_KEY);

        if ($targeting !== []) {
            array_push($notes, ...$this->targetingConfirmations($targeting));
            $changes = array_diff_key($changes, $targeting);
        }

        foreach ($changes as $field => $change) {
            if (in_array($field, ['frequency_caps', 'frequency_optimization'], true)) {
                $notes[] = 'Frequency caps change how often each person sees the ads. Tighter caps can reduce delivery and leave budget unspent.';

                continue;
            }

            if ($field === 'budget_schedules') {
                $notes[] = 'Changed budget boosts are deleted and recreated because Meta retired in-place updates. If recreation fails, the old boost is already removed; readback will show the partial result.';

                continue;
            }

            if (in_array($field, AdvancedEditFields::META_SETTINGS, true) || $field === 'delivery_schedule') {
                $notes[] = 'Changing bidding, pacing, delivery windows or the conversion event can reset learning and change how quickly the budget is spent.';

                continue;
            }
            if (in_array($field, ['conversion_rules', 'conversion_goals'], true)) {
                $notes[] = $field === 'conversion_goals'
                    ? 'Conversion goals change bidding and learning. Campaign overrides stop inheriting account defaults; custom goals can include secondary actions. Category/origin updates and goal configuration use separate calls and can partially apply. Review fresh readback before retrying.'
                    : 'Conversion rules change attribution and optimization. Associations are added before old ones are removed, using separate API calls; a failure can leave a partial change. Review the fresh readback before retrying.';

                continue;
            }
            if ($field === 'status') {
                array_push($notes, ...$this->statusConfirmations($entity, (string) ($change['after'] ?? '')));

                continue;
            }

            if ($field === 'bid_strategy') {
                array_push($notes, ...$this->strategyConfirmations($entity, $change, $changes));

                continue;
            }

            if ($field === 'optimization_goal') {
                array_push($notes, ...$this->goalConfirmations($entity, $change, $changes));

                continue;
            }

            if ((self::CATEGORY[$field] ?? null) === 'spend') {
                $notes[] = $this->spendConfirmation($entity, $field, $change);

                continue;
            }

            if ($field === 'frequency_max' || ($field === 'frequency_days' && ! isset($changes['frequency_max']))) {
                $notes[] = sprintf(
                    'Each person will see these ads at most %s. A tighter cap reaches fewer people for the same budget and may leave some of it unspent.',
                    self::frequencyPhrase($entity, $changes),
                );

                continue;
            }

            if (($field === 'target_cpa' || $field === 'target_roas') && ! isset($changes['bid_strategy'])
                && (blank($change['before']) || blank($change['after']))) {
                $notes[] = sprintf(
                    '%s Google bids differently with a target than without one, so delivery goes back into learning for a few days.',
                    blank($change['after']) ? 'The target is removed.' : 'A target is added.',
                );

                continue;
            }

            if (! self::isMoney($field) || ! is_numeric($change['after'] ?? null)) {
                continue;
            }

            $after = (float) $change['after'];
            $before = is_numeric($change['before'] ?? null) ? (float) $change['before'] : null;
            $label = ManagerFormat::field($field);

            if ($before !== null && $before > 0) {
                $percent = ($after - $before) / $before * 100;

                if (abs($percent) > $percentLimit) {
                    $notes[] = sprintf(
                        '%s moves by %s%.0f%% (%s to %s %s). A change this large can put delivery back into learning, and spend may be uneven for a few days.',
                        $label, $percent > 0 ? '+' : '', $percent,
                        self::money($before, $currency), self::money($after, $currency), $currency,
                    );
                } elseif (self::isBid($field)) {
                    $notes[] = sprintf(
                        '%s changes from %s to %s %s. Any bid change can put delivery back into learning for a few days.',
                        $label, self::money($before, $currency), self::money($after, $currency), $currency,
                    );
                }
            }

            if (self::isBudget($field)) {
                $perDay = in_array($field, self::LIFETIME, true) ? $after / max(1, (int) $this->runDays($entity)) : $after;

                if ($perDay > $loud) {
                    $notes[] = sprintf(
                        '%s works out at %s %s a day, more than the %s a day above which amounts are read back before being set.',
                        $label, self::money($perDay, $currency), $currency, self::money($loud, $currency),
                    );
                }
            }
        }

        return $notes;
    }

    /**
     * Every action this object could have, with why it cannot be done now, or
     * null when it can.
     *
     * @return array<string, string|null>
     */
    public function actions(CampaignPlatformEntity $entity): array
    {
        return [
            CampaignEntityEdit::Duplicate => $this->actionRefusal($entity, CampaignEntityEdit::Duplicate),
            CampaignEntityEdit::Delete => $this->actionRefusal($entity, CampaignEntityEdit::Delete),
        ];
    }

    public function actionRefusal(CampaignPlatformEntity $entity, string $action): ?string
    {
        $platform = ManagerFormat::platform($entity->platform);
        $type = strtolower(ManagerFormat::type($entity->entity_type));

        if (! $this->platformEnabled($entity->platform)) {
            return 'Editing from the campaign manager is not switched on for this platform.';
        }

        if ($entity->removed_at !== null || in_array(strtoupper((string) $entity->status), self::GOING, true)) {
            return sprintf('This %s is already deleted, or being deleted, on %s.', $type, $platform);
        }

        if (! in_array($action, self::ACTIONS[$entity->platform][$entity->entity_type] ?? [], true)) {
            return match (true) {
                $action === CampaignEntityEdit::Duplicate && $entity->platform === 'linkedin' => 'Copy campaigns or sponsored creatives individually; a shared campaign group is not reconstructed.',
                $action === CampaignEntityEdit::Duplicate && $entity->entity_type === 'campaign' => sprintf('%s\'s API has no way to copy a whole campaign. Copy it in %s, then import the copy here.', $platform, $platform),
                default => sprintf('A %s cannot be %s from the campaign manager.', $type, $action === CampaignEntityEdit::Delete ? 'deleted' : 'copied'),
            };
        }

        if (! in_array($action, (array) config('campaign-manager.edit_categories', []), true)) {
            return sprintf('%s is not switched on for the campaign manager.', $action === CampaignEntityEdit::Delete ? 'Deleting' : 'Duplicating');
        }

        if ($action === CampaignEntityEdit::Duplicate && blank($entity->parent_external_id) && $entity->entity_type === 'ad') {
            return sprintf('%s did not say which %s this ad is in, so there is nowhere to put a copy.', $platform, $entity->platform === 'google' ? 'ad group' : 'ad set');
        }
        if ($action === CampaignEntityEdit::Duplicate && $entity->platform === 'google' && $entity->entity_type === 'campaign'
            && (! in_array(data_get($entity->settings, 'channel_type'), ['SEARCH', 'DISPLAY', 'PERFORMANCE_MAX'], true)
                || ! is_array(data_get($entity->settings, 'conversion_goals')) || filled(data_get($entity->settings, 'bidding_portfolio')))) {
            return 'Google campaign reconstruction needs a supported standard campaign, completely read conversion goals and non-portfolio bidding.';
        }
        if ($action === CampaignEntityEdit::Duplicate && $entity->platform === 'linkedin' && $entity->entity_type === 'campaign'
            && ! is_array(data_get($entity->settings, 'conversion_rules'))) {
            return 'Read this campaign\'s conversion associations completely before copying it.';
        }
        if ($action === CampaignEntityEdit::Duplicate && $entity->platform === 'linkedin' && $entity->entity_type === 'creative'
            && (! is_array(data_get($entity->settings, 'content')) || count(data_get($entity->settings, 'content')) !== 1)) {
            return 'Read one complete native creative content type before reconstructing this creative.';
        }

        if ($action === CampaignEntityEdit::Delete && $entity->platform === 'linkedin' && ($held = $this->children($entity)) > 0) {
            return sprintf('This %s still holds %d %s. LinkedIn only deletes an empty one, so delete those first.', $type, $held, Str::plural($entity->entity_type === 'campaign' ? 'ad' : 'campaign', $held));
        }

        return null;
    }

    /** What the review step says will happen, in plain words. */
    public function actionSummary(CampaignPlatformEntity $entity, string $action): string
    {
        $platform = ManagerFormat::platform($entity->platform);
        $type = strtolower(ManagerFormat::type($entity->entity_type));
        if ($entity->platform === 'linkedin' && $action === CampaignEntityEdit::Duplicate) {
            return $entity->entity_type === 'campaign'
                ? 'Reconstruct this campaign and its sponsored creatives as new DRAFT objects in the same campaign group, preserving native settings and conversion associations. Existing sponsored content is reused, not edited or published. The original stays unchanged; nothing starts spending.'
                : 'Create a new DRAFT sponsored creative in the same campaign using the existing sponsored content and lead form. The original creative and post remain unchanged; nothing starts spending.';
        }
        if ($entity->platform === 'google' && $action === CampaignEntityEdit::Duplicate && $entity->entity_type === 'campaign') {
            return 'Reconstruct this supported Google campaign with an independent budget, native settings, conversion goals, criteria and paused children. Existing assets and shared exclusion sets are referenced, not modified. Unsupported formats or settings refuse the copy; nothing starts spending.';
        }
        if ($entity->platform === 'google' && $action === CampaignEntityEdit::Duplicate && $entity->entity_type === 'asset_group') {
            return 'Reconstruct this asset group as PAUSED with its URLs, existing assets, audience signals and search themes. Shared assets are not modified. Retail/listing-group configurations are refused; nothing starts spending.';
        }

        if ($action === CampaignEntityEdit::Duplicate && $entity->entity_type === 'campaign') {
            $adSets = $this->children($entity);

            return sprintf('%s makes a copy of this whole campaign, with copies of its %d %s and their ads. Everything is created paused, so nothing spends until it is turned on. The copy is added to the campaign manager as a campaign of its own.',
                $platform, $adSets, Str::plural(strtolower(ManagerFormat::type($entity->platform === 'google' ? 'ad_group' : 'ad_set')), $adSets));
        }

        if ($action === CampaignEntityEdit::Duplicate) {
            return sprintf('%s makes a copy of this %s under the same %s%s. The copy is created paused, so it does not spend until it is turned on.',
                $platform, $type, strtolower(ManagerFormat::type((string) ($entity->parent_type ?: 'campaign'))),
                match ($entity->entity_type) {
                    'ad_set' => ', with copies of its ads',
                    'ad_group' => ', with its keywords and copies of its ads',
                    default => '',
                });
        }

        return match (true) {
            $entity->platform === 'linkedin' => sprintf('LinkedIn removes a %s that never ran. Anything that has run is marked for deletion instead, and cannot be restarted after that.', $type),
            $entity->entity_type === 'campaign' => sprintf('%s deletes this campaign and everything in it.', $platform),
            $entity->entity_type === 'ad_set' => 'Meta deletes this ad set and its ads.',
            $entity->entity_type === 'ad_group' => 'Google removes this ad group with its ads and keywords.',
            default => sprintf('%s deletes this %s.', $platform, $type),
        };
    }

    /**
     * What has to be acknowledged before a delete or a duplicate is sent.
     *
     * @param  array{spend?: float, impressions?: int, currency?: string, conversion_event?: string}  $delivery  read when it was proposed
     * @return list<string>
     */
    public function actionConfirmations(CampaignPlatformEntity $entity, string $action, array $delivery = []): array
    {
        if ($entity->platform === 'linkedin' && $action === CampaignEntityEdit::Duplicate) {
            return ['The new objects remain DRAFT. They have new delivery history and learning, but reuse the sponsored post and its engagement. A past start is moved to now; an expired end date prevents copying. No shared group, original campaign or post is changed.'];
        }
        if ($entity->platform === 'google' && $action === CampaignEntityEdit::Duplicate) {
            return ['The new campaign, ad groups, ads and asset groups remain PAUSED. Copies start with new delivery history and learning. Existing assets are reused without modifying them. A past start moves forward; an expired end prevents copying. Unsupported formats are refused rather than silently omitted.'];
        }
        if ($action === CampaignEntityEdit::Duplicate && isset($delivery['conversion_event'])) {
            return ['A new paused ad set and copies of its ads are created with the selected conversion event. The original ad set is not edited, paused or deleted. The copy starts with new learning and no performance history.'];
        }
        if ($action !== CampaignEntityEdit::Delete) {
            return [];
        }

        $platform = ManagerFormat::platform($entity->platform);
        $type = strtolower(ManagerFormat::type($entity->entity_type));
        $notes = [sprintf('Deleting cannot be undone: %s does not restore a deleted %s. Pausing it instead stops it and keeps it restartable.', $platform, $type)];

        if (($delivery['spend'] ?? 0) > 0 || ($delivery['impressions'] ?? 0) > 0) {
            $notes[] = sprintf('It has delivered: %s %s spent and %s impressions over its life. Its past results stay in %s reporting.',
                self::money((float) $delivery['spend'], $currency = $delivery['currency'] ?? self::currency($entity)), $currency,
                number_format((int) ($delivery['impressions'] ?? 0)), $platform);
        }

        if (in_array(strtoupper((string) $entity->status), self::LIVE, true)) {
            $notes[] = sprintf('This %s is on, so anything it is delivering now stops.', $type);
        }

        if ($entity->entity_type === 'campaign' && $entity->platform !== 'linkedin') {
            $notes[] = 'Everything under it is deleted too, and it leaves the campaign manager.';
        }

        return $notes;
    }

    public function eventCopyRefusal(CampaignPlatformEntity $entity): ?string
    {
        return match (true) {
            $entity->platform !== 'meta' || $entity->entity_type !== 'ad_set' => 'A conversion-event copy is only available for Meta ad sets.',
            $this->actionRefusal($entity, CampaignEntityEdit::Duplicate) !== null => $this->actionRefusal($entity, CampaignEntityEdit::Duplicate),
            ! $this->categoryEnabled('conversion_event') => 'Conversion-event controls are not switched on for the campaign manager.',
            blank(data_get($entity->settings, 'promoted_object.pixel_id')) => 'A conversion-event copy needs an existing website pixel.',
            strtoupper((string) data_get($entity->settings, 'optimization_goal')) === 'VALUE' => 'Value optimization requires Purchase; there is no alternative conversion event.',
            data_get($entity->settings, 'budget_schedules') === null => 'Meta did not report complete budget schedules, so they cannot safely be reproduced on a copy.',
            default => null,
        };
    }

    /** Objects the last read found directly under this one. */
    private function children(CampaignPlatformEntity $entity): int
    {
        return CampaignPlatformEntity::query()
            ->where('campaign_id', $entity->campaign_id)
            ->where('parent_external_id', $entity->external_id)
            ->whereNull('removed_at')
            ->count();
    }

    /** What the user should know before a change to this object is sent. */
    public function warning(CampaignPlatformEntity $entity): ?string
    {
        return match (true) {
            $entity->platform === 'linkedin' && $entity->entity_type === 'campaign_group' => 'A campaign group can hold other campaigns, including ones not managed here. They will all show the new group name.',
            $entity->entity_type === 'campaign' => 'Reports and automated rules that match campaigns by name will see the new name from now on.',
            default => null,
        };
    }

    /** A line under one field explaining what the number means on this platform. */
    public function hint(CampaignPlatformEntity $entity, string $field): ?string
    {
        if (AdvancedEditFields::handles($field)) {
            return AdvancedEditFields::hint($field);
        }

        $days = in_array($field, self::LIFETIME, true) ? $this->runDays($entity) : null;

        return match (true) {
            $entity->platform === 'meta' && $entity->entity_type === 'campaign' && self::isBudget($field) => 'Shared across every ad set in the campaign (Advantage campaign budget).',
            $entity->platform === 'google' && $field === 'daily_budget' => 'Google may spend up to twice this on a busy day and evens it out over the month.',
            $entity->platform === 'google' && $field === 'cpc_bid' => 'Only used when the campaign bids with manual CPC; automated strategies ignore it.',
            $field === 'bid_strategy' => match (true) {
                $entity->platform === 'meta' && $entity->entity_type === 'campaign' => 'Applies to every ad set, because the campaign holds the budget.',
                $entity->platform === 'meta' => 'How Meta bids in auctions for this ad set.',
                $entity->platform === 'google' => 'Applies to every ad group in the campaign.',
                default => sprintf('The choices are the ones LinkedIn allows for the %s objective.', strtolower(ManagerFormat::readable((string) data_get($entity->settings, 'objectiveType')))),
            },
            $field === 'spend_cap' => 'A limit on everything the campaign ever spends, across all its ad sets. Meta stops it once reached. Leave it empty for no limit.',
            str_contains($field, 'min_spend_target') => 'Meta tries to spend at least this on the ad set, out of the campaign budget. Leave it empty for none.',
            str_ends_with($field, '_spend_cap') => 'Meta spends no more than this on the ad set, out of the campaign budget. Leave it empty for none.',
            $field === 'frequency_max' => 'The most times one person sees these ads in the period below.',
            $field === 'frequency_days' => 'The period, in days, the cap above counts over.',
            $field === 'countries' => 'Two-letter country codes, separated by commas, for example US, CA, GB.',
            $field === 'age_min', $field === 'age_max' => sprintf('From %d to %d; %d means %d and older.', self::META_AGE_MIN, self::META_AGE_MAX, self::META_AGE_MAX, self::META_AGE_MAX),
            $field === 'publisher_platforms' => 'Leave all unticked to let Meta choose (Advantage+ placements). Positions already picked on a platform that stays are kept.',
            $field === 'optimization_goal' => 'The result Meta shows the ads to get. The choices are the ones the campaign objective and destination allow.',
            $field === 'target_cpa' => 'Optional, used by Maximize conversions. Leave it empty for no target.',
            $field === 'target_roas' => 'Optional, used by Maximize conversion value. 4 means four times the spend back in conversion value (400%). Leave it empty for no target.',
            $entity->platform === 'meta' && $field === 'bid_amount' && $this->pairsWithStrategy($entity, $field) => 'Used by cost per result goal and bid cap; highest volume ignores it.',
            $entity->platform === 'meta' && $field === 'bid_amount' => sprintf('Used as the %s.', strtolower(Str::headline(strtolower((string) data_get($entity->settings, 'bid_strategy'))))),
            $entity->platform === 'linkedin' && $field === 'unit_cost' => sprintf('The bid for each %s.', strtolower((string) (data_get($entity->settings, 'costType') ?: 'result'))),
            $field === 'status' && $entity->platform === 'google' => 'Only this object changes; anything above or below it keeps its own status.',
            $field === 'status' => 'Only this object changes. It delivers only while everything above it is on too.',
            self::isSchedule($field) => sprintf(
                'Delivery %s at this time, in %s as %s reports it.%s',
                $field === 'start_time' ? 'begins' : 'stops',
                self::zoneLabel($entity), ManagerFormat::platform($entity->platform),
                $this->holdsLifetime($entity) !== null ? ' The total budget is spread over the new length.' : '',
            ),
            $days !== null => sprintf('The total to spend over the %d day run.', $days),
            default => null,
        };
    }

    public function writer(string $platform): EntityWriter
    {
        if (! isset(self::WRITERS[$platform])) {
            throw new EditRefused(sprintf('The campaign manager cannot change %s campaigns.', ucfirst($platform)));
        }

        return $this->container->make(self::WRITERS[$platform]);
    }

    /** The stored value of one editable field; money as a float in major units. */
    public static function current(CampaignPlatformEntity $entity, string $field): mixed
    {
        if (AdvancedEditFields::handles($field)) {
            return AdvancedEditFields::current($entity, $field);
        }

        if ($field === 'name') {
            return $entity->name;
        }

        if ($field === 'status') {
            return $entity->status !== null ? strtoupper($entity->status) : null;
        }

        $value = data_get($entity->settings, self::PATHS[$entity->platform][$field] ?? $field);

        if (self::isTargeting($field)) {
            return self::normalize($entity, $field, $value);
        }

        return self::isMoney($field) ? (is_numeric($value) ? (float) $value : null) : $value;
    }

    /**
     * A submitted value in the form the platform stores it, so it compares
     * with what is read back: money as a float; an end as Meta's ISO string
     * with offset or LinkedIn's epoch milliseconds.
     */
    public static function normalize(CampaignPlatformEntity $entity, string $field, mixed $value): mixed
    {
        if (AdvancedEditFields::handles($field)) {
            $normalized = AdvancedEditFields::normalize($field, $value);

            return $field === 'network_settings' && is_array($normalized)
                ? Canonical::sort([...(array) data_get($entity->settings, 'network_settings'), ...$normalized])
                : $normalized;
        }

        if (self::isMoney($field)) {
            return is_numeric($value) ? (float) $value : null;
        }

        if ($field === 'target_roas') {
            return is_numeric($value) ? round((float) $value, 4) : null;
        }

        if ($field === 'bid_strategy' || $field === 'optimization_goal') {
            return is_string($value) ? strtoupper($value) : $value;
        }

        if ((self::CATEGORY[$field] ?? null) === 'frequency' || $field === 'age_min' || $field === 'age_max') {
            return is_numeric($value) ? (int) $value : null;
        }

        if ($field === 'genders') {
            return match (true) {
                in_array($value, ['all', 'men', 'women'], true) => $value,
                is_array($value) && array_map('intval', $value) === [1] => 'men',
                is_array($value) && array_map('intval', $value) === [2] => 'women',
                default => 'all',
            };
        }

        if ($field === 'countries' || $field === 'publisher_platforms') {
            $list = is_array($value) ? $value : preg_split('/[\s,]+/', (string) $value);
            $list = array_map(fn (mixed $item): string => trim((string) $item), $list);
            $list = array_map($field === 'countries' ? 'strtoupper' : 'strtolower', array_filter($list, fn (string $item): bool => $item !== ''));
            $list = array_values(array_unique($list));
            sort($list);

            return $list;
        }

        if (! self::isSchedule($field) || ($moment = self::momentIn($entity, $value)) === null) {
            return $value;
        }

        return $entity->platform === 'linkedin'
            ? $moment->getTimestampMs()
            : $moment->format('Y-m-d\TH:i:sO');
    }

    /** A schedule value as the date-time input shows it, in the platform's zone. */
    public static function inputMoment(CampaignPlatformEntity $entity, mixed $value): ?string
    {
        return self::momentIn($entity, $value)?->format('Y-m-d\TH:i');
    }

    /** A schedule value for reading: "Nov 13, 2026 8:07 AM (UTC)". */
    public static function showMoment(CampaignPlatformEntity $entity, mixed $value): string
    {
        $moment = self::momentIn($entity, $value);

        return $moment === null
            ? (filled($value) ? (string) $value : 'No end date')
            : $moment->format('M j, Y g:i A').' ('.self::zoneLabel($entity).')';
    }

    /**
     * How far an end moves, for the review pill: "+7 days", "-5 hours".
     *
     * @return array{label: string, direction: int}|null
     */
    public static function shift(mixed $before, mixed $after): ?array
    {
        $from = self::moment($before);
        $to = self::moment($after);

        if ($to === null) {
            return null;
        }

        if ($from === null) {
            return ['label' => 'New end', 'direction' => 0];
        }

        $hours = (int) round($from->diffInHours($to));
        [$amount, $unit] = abs($hours) >= 48 ? [(int) round($hours / 24), 'day'] : [$hours, 'hour'];

        return [
            'label' => $amount === 0 ? 'Same day' : sprintf('%s%d %s', $amount > 0 ? '+' : '-', abs($amount), Str::plural($unit, abs($amount))),
            'direction' => $amount <=> 0,
        ];
    }

    /** Whether two values of a field are the same once the platform has rounded them. */
    public static function same(CampaignPlatformEntity $entity, string $field, mixed $a, mixed $b): bool
    {
        if (AdvancedEditFields::handles($field)) {
            if ($field === 'budget_schedules') {
                $withoutIds = fn (mixed $rows): array => array_map(
                    function (array $row): array {
                        unset($row['id']);

                        return $row;
                    },
                    AdvancedEditFields::normalize($field, $rows),
                );

                return $withoutIds($a) === $withoutIds($b);
            }

            return AdvancedEditFields::normalize($field, $a) === AdvancedEditFields::normalize($field, $b);
        }

        if (self::isSchedule($field)) {
            $first = self::moment($a);
            $second = self::moment($b);

            return $first === null || $second === null
                ? blank($a) && blank($b)
                : $first->getTimestamp() === $second->getTimestamp();
        }

        if ((self::CATEGORY[$field] ?? null) === 'frequency') {
            return (is_numeric($a) ? (int) $a : null) === (is_numeric($b) ? (int) $b : null);
        }

        if (self::isTargeting($field)) {
            return self::normalize($entity, $field, $a) === self::normalize($entity, $field, $b);
        }

        if ($field === 'target_roas' && is_numeric($a) && is_numeric($b)) {
            return abs((float) $a - (float) $b) < 0.00005;
        }

        if (! self::isMoney($field) || ! is_numeric($a) || ! is_numeric($b)) {
            return $a === $b;
        }

        $currency = self::currency($entity);

        return CurrencyMinorUnits::toMinor((float) $a, $currency) === CurrencyMinorUnits::toMinor((float) $b, $currency);
    }

    /** The currency the platform reports this object's money in. */
    public static function currency(CampaignPlatformEntity $entity): string
    {
        if ($entity->platform === 'linkedin') {
            foreach (['dailyBudget', 'totalBudget', 'unitCost'] as $key) {
                if (filled($code = data_get($entity->settings, $key.'.currencyCode'))) {
                    return strtoupper((string) $code);
                }
            }
        }

        return strtoupper((string) ($entity->campaign?->currency ?: 'USD'));
    }

    /** The numeric id of the Google budget resource this campaign spends from. */
    public static function googleBudgetId(CampaignPlatformEntity $entity): ?string
    {
        return preg_match('~/campaignBudgets/(\d+)$~', (string) data_get($entity->settings, 'budget_resource'), $match) === 1
            ? $match[1]
            : null;
    }

    /**
     * Whether the drift row is the read-back of a change made from here, so it
     * can be shown as ours rather than as someone working in the platform UI.
     */
    public static function matchesDrift(CampaignEntityEdit $edit, CampaignPlatformDrift $drift): bool
    {
        if ($edit->action === CampaignEntityEdit::Duplicate) {
            return $drift->kind === CampaignPlatformDrift::Added
                && $drift->campaign_platform_entity_id === ($edit->details['copy_entity_id'] ?? null);
        }

        if ($edit->campaign_platform_entity_id !== $drift->campaign_platform_entity_id || $edit->entity === null) {
            return false;
        }

        if ($edit->action === CampaignEntityEdit::Delete) {
            return $drift->kind === CampaignPlatformDrift::Removed || $drift->field === 'status';
        }

        foreach ($edit->changes as $field => $change) {
            $path = in_array($field, ['name', 'status'], true) ? $field : 'settings.'.(AdvancedEditFields::handles($field)
                ? AdvancedEditFields::path($field)
                : (self::PATHS[$edit->platform][$field] ?? $field));
            $top = implode('.', array_slice(explode('.', $path), 0, 2));

            if ($drift->field !== $top) {
                continue;
            }

            $after = $path === $top ? $drift->after : data_get($drift->after, Str::after($path, $top.'.'));
            if ($field === 'roas_floor' && is_numeric($after)) {
                $after = (float) $after / 10000;
            }

            if (self::same($edit->entity, $field, $after, $change['after'])) {
                return true;
            }
        }

        $strategy = $edit->changes['bid_strategy']['after'] ?? null;

        // The platform clears an amount the new strategy does not read (Meta
        // drops the bid on a move to highest volume): that is this change too.
        if (is_string($strategy) && blank($drift->after)) {
            $reads = self::strategyAmount($edit->entity, $strategy)['field'] ?? null;

            foreach (self::strategyAmounts($edit->entity) as $field) {
                $path = 'settings.'.(self::PATHS[$edit->platform][$field] ?? $field);

                if ($field !== $reads && $drift->field === implode('.', array_slice(explode('.', $path), 0, 2))) {
                    return true;
                }
            }
        }

        return false;
    }

    public static function money(float $amount, string $currency): string
    {
        return number_format($amount, CurrencyMinorUnits::decimals($currency), '.', ',');
    }

    /** Days from the start to the end of the run, or null when it has no end. */
    public function runDays(CampaignPlatformEntity $entity): ?int
    {
        return $this->runDaysUntil($entity, self::moment(self::endOf($entity)));
    }

    /** Days from the start of the run to the given end. */
    private function runDaysUntil(CampaignPlatformEntity $entity, ?CarbonImmutable $end, ?CarbonImmutable $start = null): ?int
    {
        if ($end === null) {
            return null;
        }

        $start ??= self::moment(self::startOf($entity)) ?? CarbonImmutable::now();

        return max(1, (int) ceil($start->diffInDays($end)));
    }

    /**
     * The run's start and end with one end of it moved.
     *
     * @return array{0: ?CarbonImmutable, 1: ?CarbonImmutable}
     */
    private function runWith(CampaignPlatformEntity $entity, string $field, ?CarbonImmutable $moment): array
    {
        $start = self::moment(self::startOf($entity));
        $end = self::moment(self::endOf($entity));

        return $field === 'start_time' ? [$moment, $end] : [$start, $moment];
    }

    private static function startOf(CampaignPlatformEntity $entity): mixed
    {
        return match ($entity->platform) {
            'meta', 'google' => data_get($entity->settings, 'start_time'),
            'linkedin' => data_get($entity->settings, 'runSchedule.start'),
            default => null,
        };
    }

    private static function endOf(CampaignPlatformEntity $entity): mixed
    {
        return match ($entity->platform) {
            'meta' => data_get($entity->settings, $entity->entity_type === 'campaign' ? 'stop_time' : 'end_time'),
            'google' => data_get($entity->settings, 'end_time'),
            'linkedin' => data_get($entity->settings, 'runSchedule.end'),
            default => null,
        };
    }

    /** The lifetime budget field this object spends from, if it has one. */
    private function holdsLifetime(CampaignPlatformEntity $entity): ?string
    {
        foreach (self::LIFETIME as $field) {
            if (in_array($field, self::FIELDS[$entity->platform][$entity->entity_type] ?? [], true) && self::holds($entity, $field)) {
                return $field;
            }
        }

        return null;
    }

    private function statusRefusal(CampaignPlatformEntity $entity): ?string
    {
        $current = self::current($entity, 'status');
        $platform = ManagerFormat::platform($entity->platform);
        $type = strtolower(ManagerFormat::type($entity->entity_type));

        return match (true) {
            $current === null => sprintf('%s did not report a status for this %s.', $platform, $type),
            $current === 'ARCHIVED' => sprintf('This %s is archived on %s, and archived objects are not restarted from here.', $type, $platform),
            ! array_key_exists($current, self::statusOptions($entity)) => sprintf('%s reports this %s as %s, which is not changed from here.', $platform, $type, strtolower(str_replace('_', ' ', $current))),
            $entity->platform === 'google' && $entity->entity_type === 'ad' && blank($entity->parent_external_id) => 'Google did not report which ad group this ad is in, so it cannot be addressed.',
            default => null,
        };
    }

    /** @return list<string> */
    private function statusConfirmations(CampaignPlatformEntity $entity, string $after): array
    {
        $type = strtolower(ManagerFormat::type($entity->entity_type));

        if ($after === 'ARCHIVED') {
            return [sprintf(
                'Archiving stops this %s for good: %s',
                $type,
                $entity->platform === 'meta'
                    ? 'Meta only lets an archived object be deleted afterwards, never restarted.'
                    : 'it is not restarted from the campaign manager.',
            )];
        }

        if (! in_array($after, self::LIVE, true)) {
            return [];
        }

        $notes = [$entity->entity_type === 'campaign'
            ? 'Turning the campaign on starts spending on everything under it that is on.'
            : sprintf('Turning this %s on lets it spend as soon as everything above it is on too.', $type)];

        $since = $this->pausedSince($entity);

        if ($since !== null && $since->lte(CarbonImmutable::now()->subDays(self::STALE_PAUSE_DAYS))) {
            $notes[] = sprintf(
                'It has been paused since %s (%d days). Restarting after %d or more days puts delivery back into learning.',
                $since->format('M j, Y'), (int) $since->diffInDays(CarbonImmutable::now()), self::STALE_PAUSE_DAYS,
            );
        }

        return $notes;
    }

    /**
     * When this object was last seen to stop delivering: the read that first
     * found it paused, or the first read at all when it was already paused then.
     */
    private function pausedSince(CampaignPlatformEntity $entity): ?CarbonImmutable
    {
        $drift = CampaignPlatformDrift::query()
            ->where('campaign_platform_entity_id', $entity->id)
            ->where('field', 'status')
            ->latest('detected_at')
            ->latest('id')
            ->first();

        $at = $drift?->detected_at ?? $entity->first_seen_at;

        return $at === null ? null : CarbonImmutable::parse($at);
    }

    private function scheduleRefusal(CampaignPlatformEntity $entity, string $field): ?string
    {
        $current = self::current($entity, $field);
        $moment = self::moment($current);
        $end = self::moment(self::endOf($entity));
        $platform = ManagerFormat::platform($entity->platform);

        if (filled($current) && $moment === null) {
            return sprintf('%s reported a %s this product cannot read, so it is not changed from here.', $platform, $field === 'start_time' ? 'start' : 'end');
        }

        if ($end !== null && $end->isPast()) {
            return 'This run has already ended; restarting it is not done from here.';
        }

        if ($field === 'start_time') {
            return match (true) {
                $moment === null => sprintf('%s did not report a start for this %s.', $platform, strtolower(ManagerFormat::type($entity->entity_type))),
                $moment->lt(CarbonImmutable::now()->addMinutes(self::MIN_LEAD_MINUTES)) => sprintf('This %s has already started, and %s does not move a start that has passed.', strtolower(ManagerFormat::type($entity->entity_type)), $platform),
                default => null,
            };
        }

        if ($entity->platform === 'google' && self::googleZone($entity) === null) {
            return 'Google did not report the account\'s time zone, which its run dates are set in, so they are changed in Google Ads.';
        }

        if ($entity->platform === 'linkedin' && self::moment(self::startOf($entity)) === null) {
            return 'LinkedIn did not report when this campaign starts, and its schedule is sent whole, so the end is not changed from here.';
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $proposed
     * @return list<mixed>
     */
    private function scheduleRules(CampaignPlatformEntity $entity, string $field, array $proposed): array
    {
        return [
            'required',
            function (string $attribute, mixed $value, Closure $fail) use ($entity, $field, $proposed): void {
                $moment = self::momentIn($entity, $value);

                if ($moment === null) {
                    $fail('Enter a date and time.');

                    return;
                }

                if ($moment->lt(CarbonImmutable::now()->addMinutes(self::MIN_LEAD_MINUTES))) {
                    $fail(sprintf('Pick a time at least %d minutes from now.', self::MIN_LEAD_MINUTES));

                    return;
                }

                [$start, $end] = $this->runWith($entity, $field, $moment);
                $other = $field === 'start_time' ? 'end_time' : 'start_time';

                if (filled($proposed[$other] ?? null) && ($moved = self::momentIn($entity, $proposed[$other])) !== null) {
                    $field === 'start_time' ? $end = $moved : $start = $moved;
                }

                if ($start !== null && $end !== null && $end->lte($start->addHour())) {
                    $fail($field === 'start_time'
                        ? sprintf('The start has to be more than an hour before the end (%s).', self::showMoment($entity, $end))
                        : sprintf('The end has to be more than an hour after the start (%s).', self::showMoment($entity, $start)));

                    return;
                }

                if (($lifetime = $this->holdsLifetime($entity)) !== null
                    && ($problem = $this->limitProblem($entity, $lifetime, (float) self::current($entity, $lifetime), $this->runDaysUntil($entity, $end, $start)))) {
                    $fail(sprintf('With this %s, the total budget would not fit: ', $field === 'start_time' ? 'start' : 'end').lcfirst($problem));
                }
            },
        ];
    }

    /**
     * One note for the run as a whole, however many of its ends move.
     *
     * @param  array<string, array{before: mixed, after: mixed}>  $changes  start_time and/or end_time
     * @return list<string>
     */
    private function scheduleConfirmations(CampaignPlatformEntity $entity, array $changes, float $loud): array
    {
        $lifetime = $this->holdsLifetime($entity);
        $moment = fn (string $field, string $side, Closure $stored): ?CarbonImmutable => array_key_exists($field, $changes)
            ? self::moment($changes[$field][$side] ?? null)
            : self::moment($stored($entity));
        $newEnd = $moment('end_time', 'after', self::endOf(...));

        if ($lifetime === null || $newEnd === null) {
            return [];
        }

        $currency = self::currency($entity);
        $total = (float) self::current($entity, $lifetime);
        $newDays = (int) $this->runDaysUntil($entity, $newEnd, $moment('start_time', 'after', self::startOf(...)));
        $oldDays = $this->runDaysUntil($entity, $moment('end_time', 'before', self::endOf(...)), $moment('start_time', 'before', self::startOf(...)));
        $perDay = $total / max(1, $newDays);

        $notes = [sprintf(
            'The %s %s total budget will be spread over %d %s%s: about %s %s a day%s. Delivery re-paces, and may go back into learning.',
            self::money($total, $currency), $currency, $newDays, Str::plural('day', $newDays),
            $oldDays === null ? '' : sprintf(' instead of %d', $oldDays),
            self::money($perDay, $currency), $currency,
            $oldDays === null ? '' : sprintf(' instead of %s', self::money($total / max(1, $oldDays), $currency)),
        )];

        if ($perDay > $loud) {
            $notes[] = sprintf(
                'That is more than the %s %s a day above which amounts are read back before being set.',
                self::money($loud, $currency), $currency,
            );
        }

        return $notes;
    }

    /**
     * The zone the platform reports this object's times in. Meta sends an
     * offset with each time; Google runs on the account's named zone, which
     * also carries its daylight saving; LinkedIn sends epoch milliseconds,
     * read as UTC.
     */
    private static function zone(CampaignPlatformEntity $entity): CarbonTimeZone
    {
        if ($entity->platform === 'google' && ($named = self::googleZone($entity)) !== null) {
            return $named;
        }

        if ($entity->platform === 'meta') {
            foreach ([self::endOf($entity), self::startOf($entity)] as $reported) {
                if (is_string($reported) && preg_match('/([+-]\d{2}:?\d{2}|Z)$/', $reported) === 1 && ($moment = self::moment($reported))) {
                    return $moment->getTimezone();
                }
            }
        }

        return new CarbonTimeZone('UTC');
    }

    /** The Google account's time zone, when Google reported one this can use. */
    private static function googleZone(CampaignPlatformEntity $entity): ?CarbonTimeZone
    {
        $name = data_get($entity->settings, 'time_zone');

        if (! is_string($name) || ! in_array($name, timezone_identifiers_list(), true)) {
            return null;
        }

        return new CarbonTimeZone($name);
    }

    private static function zoneLabel(CampaignPlatformEntity $entity): string
    {
        if ($entity->platform === 'google' && ($named = self::googleZone($entity)) !== null) {
            return $named->getName();
        }

        $offset = self::zone($entity)->toOffsetName();

        return $offset === '+00:00' ? 'UTC' : 'UTC'.$offset;
    }

    /** A schedule value, whatever form it arrives in, as a moment in the platform's zone. */
    private static function momentIn(CampaignPlatformEntity $entity, mixed $value): ?CarbonImmutable
    {
        $zone = self::zone($entity);

        try {
            return match (true) {
                is_string($value) && preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/', $value) === 1 => CarbonImmutable::parse($value, $zone),
                // Only exact forms: Carbon would read "next week" as a date.
                is_int($value), is_string($value) && ctype_digit($value),
                is_string($value) && preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([+-]\d{2}:?\d{2}|Z)$/', $value) === 1 => self::moment($value)?->setTimezone($zone),
                default => null,
            };
        } catch (Throwable) {
            return null;
        }
    }

    /** Why a spending limit cannot be changed here, or null when it can. */
    private function spendRefusal(CampaignPlatformEntity $entity, string $field): ?string
    {
        if ($field === 'spend_cap') {
            return null;
        }

        $parent = self::parentSettings($entity);
        $held = collect(self::SPEND_LIMITS)->keys()->first(fn (string $budget): bool => is_numeric($parent[$budget] ?? null) && (float) $parent[$budget] > 0);

        return match (true) {
            $held === null => 'Ad set spend limits only apply when the campaign holds the budget (Advantage campaign budget).',
            ! in_array($field, self::SPEND_LIMITS[$held], true) => sprintf('The campaign budget is %s, so the %s limits are the ones used.', $held === 'daily_budget' ? 'daily' : 'a total', $held === 'daily_budget' ? 'daily' : 'total'),
            default => null,
        };
    }

    /**
     * @param  array<string, mixed>  $proposed
     * @return list<mixed>
     */
    private function spendRules(CampaignPlatformEntity $entity, string $field, array $proposed): array
    {
        // An ad set limit has no documented way back to "none", so one that is
        // set is changed rather than cleared; the campaign cap can be removed.
        return [
            ...$this->moneyRules($entity, $field, required: $field !== 'spend_cap' && self::holds($entity, $field)),
            function (string $attribute, mixed $value, Closure $fail) use ($entity, $field, $proposed): void {
                if (is_numeric($value) && ($problem = $this->spendProblem($entity, $field, (float) $value, $proposed)) !== null) {
                    $fail($problem);
                }
            },
        ];
    }

    /** @param  array<string, mixed>  $proposed */
    private function spendProblem(CampaignPlatformEntity $entity, string $field, float $amount, array $proposed): ?string
    {
        $currency = self::currency($entity);

        if ($field === 'spend_cap') {
            $floor = self::META_MIN_SPEND_CAP_USD * (BudgetCeiling::conversionRate($entity->campaign) ?? 1.0);

            return $amount < $floor
                ? sprintf('Meta needs a campaign spending limit of at least %s %s.', self::money($floor, $currency), $currency)
                : null;
        }

        $budgetField = collect(self::SPEND_LIMITS)->search(fn (array $limits): bool => in_array($field, $limits, true));
        [$minField, $capField] = self::SPEND_LIMITS[$budgetField];
        $budget = (float) (self::parentSettings($entity)[$budgetField] ?? 0);
        $value = fn (string $other): ?float => is_numeric($given = array_key_exists($other, $proposed) ? $proposed[$other] : self::current($entity, $other)) && (float) $given > 0 ? (float) $given : null;
        $min = $field === $minField ? $amount : $value($minField);
        $cap = $field === $capField ? $amount : $value($capField);

        return match (true) {
            $field === $minField && $budget > 0 && $amount > $budget => sprintf('The minimum cannot be more than the campaign budget of %s %s.', self::money($budget, $currency), $currency),
            $min !== null && $cap !== null && $min > $cap => $field === $minField
                ? sprintf('The minimum has to be at most the limit (%s %s).', self::money($cap, $currency), $currency)
                : sprintf('The limit has to be at least the minimum (%s %s).', self::money($min, $currency), $currency),
            default => null,
        };
    }

    /** @param  array{before: mixed, after: mixed}  $change */
    private function spendConfirmation(CampaignPlatformEntity $entity, string $field, array $change): string
    {
        $currency = self::currency($entity);
        $amount = is_numeric($change['after']) ? self::money((float) $change['after'], $currency).' '.$currency : null;

        return match (true) {
            $field === 'spend_cap' && $amount === null => 'The campaign will have no spending limit: it spends until its budget or end date stops it.',
            $field === 'spend_cap' => sprintf('Meta stops every ad set in the campaign once it has spent %s in total, counting what it has spent already.', $amount),
            str_contains($field, 'min_spend_target') => sprintf('Meta will try to spend at least %s on this ad set even where results cost more, which leaves less of the campaign budget for the others.', $amount),
            default => sprintf('Meta will spend no more than %s on this ad set, even where it finds cheaper results, and moves the rest to the other ad sets.', $amount),
        };
    }

    /** Why this part of an ad set's targeting cannot be changed here, or null when it can. */
    private function targetingRefusal(CampaignPlatformEntity $entity, string $field): ?string
    {
        $targeting = data_get($entity->settings, 'targeting');

        if (! is_array($targeting)) {
            return 'Meta did not report this ad set\'s targeting.';
        }

        $places = array_diff(array_keys((array) ($targeting['geo_locations'] ?? [])), ['countries', 'location_types']);

        return match (true) {
            $field === 'countries' && (self::current($entity, 'countries') === [] || $places !== []) => 'This ad set targets regions, cities or places rather than whole countries, so its locations are changed in Ads Manager.',
            in_array($field, ['age_min', 'age_max', 'genders'], true) && (int) data_get($targeting, 'targeting_automation.advantage_audience') === 1 => 'Advantage+ audience is on, so age and gender are only suggestions to Meta and are changed in Ads Manager.',
            in_array($field, ['age_min', 'age_max'], true) && self::current($entity, $field) === null => 'Meta did not report this ad set\'s age range.',
            default => null,
        };
    }

    /**
     * @param  array<string, mixed>  $proposed
     * @return list<mixed>
     */
    private function targetingRules(CampaignPlatformEntity $entity, string $field, array $proposed): array
    {
        return match ($field) {
            'countries' => ['required', function (string $attribute, mixed $value, Closure $fail) use ($entity): void {
                $codes = self::normalize($entity, 'countries', $value);
                $bad = array_filter($codes, fn (string $code): bool => preg_match('/^[A-Z]{2}$/', $code) !== 1);

                if ($codes === []) {
                    $fail('Name at least one country.');
                } elseif ($bad !== []) {
                    $fail(sprintf('%s is not a two-letter country code.', implode(', ', $bad)));
                }
            }],
            'age_min', 'age_max' => ['required', 'integer', 'between:'.self::META_AGE_MIN.','.self::META_AGE_MAX,
                function (string $attribute, mixed $value, Closure $fail) use ($entity, $field, $proposed): void {
                    $other = $field === 'age_min' ? 'age_max' : 'age_min';
                    $pair = [$field => (int) $value, $other => (int) (array_key_exists($other, $proposed) ? $proposed[$other] : self::current($entity, $other))];

                    if (is_numeric($value) && $pair['age_min'] > $pair['age_max']) {
                        $fail('The youngest age has to be at or below the oldest.');
                    }
                }],
            'genders' => ['required', 'string', Rule::in(array_keys(self::META_GENDERS))],
            default => ['nullable', 'array', function (string $attribute, mixed $value, Closure $fail) use ($entity): void {
                $platforms = self::normalize($entity, 'publisher_platforms', $value);

                if (($unknown = array_diff($platforms, array_keys(self::META_PLATFORMS))) !== []) {
                    $fail(sprintf('%s is not a placement offered here.', implode(', ', $unknown)));
                } elseif ($platforms !== [] && ! in_array('facebook', $platforms, true) && array_intersect($platforms, ['audience_network', 'messenger']) !== []) {
                    $fail('Audience Network and Messenger only run alongside Facebook.');
                }
            }],
        };
    }

    /**
     * @param  array<string, array{before: mixed, after: mixed}>  $changes
     * @return list<string>
     */
    private function targetingConfirmations(array $changes): array
    {
        $notes = ['Changing who sees the ads, or where, sends delivery back into learning; its results so far may not hold for the new audience.'];

        if (isset($changes['publisher_platforms'])) {
            $before = (array) $changes['publisher_platforms']['before'];
            $after = (array) $changes['publisher_platforms']['after'];

            $notes[] = match (true) {
                $after === [] => 'Meta will choose where the ads show, across all its platforms and positions (Advantage+ placements).',
                $before === [] => 'Meta will show the ads only on the platforms ticked, on every position there.',
                default => 'Positions picked on platforms that are dropped go with them; a platform that is added shows the ads on every position there.',
            };

            if (in_array('instagram', array_diff($after ?: array_keys(self::META_PLATFORMS), $before ?: array_keys(self::META_PLATFORMS)), true)) {
                $notes[] = 'On Instagram the ads post as the Instagram account linked to the Page; Meta rejects ones that cannot show there.';
            }
        }

        return $notes;
    }

    /** Why the frequency cap cannot be changed on this ad set, or null when it can. */
    private function frequencyRefusal(CampaignPlatformEntity $entity): ?string
    {
        $specs = data_get($entity->settings, 'frequency_control_specs');

        return match (true) {
            strtoupper((string) data_get($entity->settings, 'optimization_goal')) !== 'REACH' => 'Meta only takes a frequency cap on an ad set optimising for reach.',
            is_array($specs) && (count($specs) > 1 || strtoupper((string) data_get($specs, '0.event', 'IMPRESSIONS')) !== 'IMPRESSIONS') => 'This ad set has frequency rules beyond one impression cap, so they are changed in Ads Manager.',
            default => null,
        };
    }

    /**
     * Both halves of the cap are set together: neither means anything alone.
     *
     * @param  array<string, mixed>  $proposed
     * @return list<mixed>
     */
    private function frequencyRules(CampaignPlatformEntity $entity, string $field, array $proposed): array
    {
        $other = $field === 'frequency_max' ? 'frequency_days' : 'frequency_max';
        $required = filled(self::current($entity, $field)) || filled($proposed[$other] ?? null);

        return [
            $required ? 'required' : 'nullable', 'integer', 'between:1,'.self::FREQUENCY_MAX,
            function (string $attribute, mixed $value, Closure $fail) use ($entity, $other, $proposed): void {
                if (filled($value) && blank(array_key_exists($other, $proposed) ? $proposed[$other] : self::current($entity, $other))) {
                    $fail($other === 'frequency_days' ? 'Also say over how many days.' : 'Also say how many times.');
                }
            },
        ];
    }

    /** @param  array<string, array{before: mixed, after: mixed}>  $changes */
    private static function frequencyPhrase(CampaignPlatformEntity $entity, array $changes): string
    {
        $max = (int) ($changes['frequency_max']['after'] ?? self::current($entity, 'frequency_max'));
        $days = (int) ($changes['frequency_days']['after'] ?? self::current($entity, 'frequency_days'));

        return sprintf('%d %s every %d %s', $max, Str::plural('time', $max), $days, Str::plural('day', $days));
    }

    /** Why the performance goal cannot be changed on this ad set, or null when it can. */
    private function goalRefusal(CampaignPlatformEntity $entity): ?string
    {
        $billing = strtoupper((string) data_get($entity->settings, 'billing_event'));
        $objective = self::metaObjective($entity);

        return match (true) {
            blank(data_get($entity->settings, 'optimization_goal')) => 'Meta did not report a performance goal for this ad set.',
            $objective === null => 'The campaign\'s objective has not been read, so the goals it allows are not known here.',
            ! isset(self::META_GOALS[$objective]) => sprintf('Goals for the %s objective are changed in Ads Manager.', strtolower(ManagerFormat::readable(Str::after($objective, 'OUTCOME_')))),
            count(self::goalOptions($entity)) < 2 => sprintf('Ads sent to %s have goals tied to setup done in Ads Manager, so they are changed there.', strtolower(ManagerFormat::readable(self::destination($entity) ?: 'this destination'))),
            $billing !== '' && $billing !== 'IMPRESSIONS' => sprintf('This ad set is charged per %s, which ties it to its goal. Change both together in Ads Manager.', strtolower(ManagerFormat::readable(Str::singular($billing)))),
            default => null,
        };
    }

    /**
     * @param  array{before: mixed, after: mixed}  $change
     * @param  array<string, array{before: mixed, after: mixed}>  $changes
     * @return list<string>
     */
    private function goalConfirmations(CampaignPlatformEntity $entity, array $change, array $changes): array
    {
        $notes = [sprintf(
            'Meta will show the ads to get %s instead of %s. The ad set goes back into learning, and results before and after are counted differently, so they do not compare.',
            strtolower(self::goalLabel((string) $change['after'])), strtolower(self::goalLabel((string) $change['before'])),
        )];

        $strategy = strtoupper((string) ($changes['bid_strategy']['after'] ?? data_get($entity->settings, 'bid_strategy')));
        $bid = $changes['bid_amount']['after'] ?? self::current($entity, 'bid_amount');

        if (in_array($strategy, self::META_BID_STRATEGIES, true) && is_numeric($bid)) {
            $currency = self::currency($entity);
            $notes[] = sprintf(
                'The %s of %s %s will apply to each %s from now on. Check it still makes sense for that result.',
                strtolower(self::strategyLabel('meta', $strategy)), self::money((float) $bid, $currency), $currency,
                strtolower(Str::singular(self::goalLabel((string) $change['after']))),
            );
        }

        return $notes;
    }

    /** @return list<mixed> */
    /** Why the bid strategy cannot be changed on this object, or null when it can. */
    private function strategyRefusal(CampaignPlatformEntity $entity): ?string
    {
        if (! in_array('bid_strategy', self::FIELDS[$entity->platform][$entity->entity_type] ?? [], true)) {
            return 'This field cannot be changed from the campaign manager.';
        }

        $current = strtoupper((string) self::current($entity, 'bid_strategy'));
        $platform = ManagerFormat::platform($entity->platform);
        $holdsBudget = self::holds($entity, 'daily_budget') || self::holds($entity, 'lifetime_budget');
        $channel = strtoupper((string) data_get($entity->settings, 'channel_type'));
        $objective = strtoupper((string) data_get($entity->settings, 'objectiveType'));

        return match (true) {
            $entity->platform === 'meta' && $entity->entity_type === 'ad_set' && ! $holdsBudget => 'The campaign holds the budget (Advantage campaign budget), so the bid strategy is set on the campaign.',
            $entity->platform === 'meta' && $entity->entity_type === 'campaign' && ! $holdsBudget => 'Each ad set holds its own budget, so each ad set has its own bid strategy.',
            $entity->platform === 'meta' && $current === 'LOWEST_COST_WITH_MIN_ROAS' => 'This uses a ROAS goal, which is set up with value optimisation in Ads Manager, so it is not changed from here.',
            $entity->platform === 'google' && filled(data_get($entity->settings, 'bidding_portfolio')) => 'This campaign bids with a portfolio strategy shared with other campaigns, so it is changed in Google Ads.',
            $entity->platform === 'google' && ! isset(self::GOOGLE_CHANNEL_STRATEGIES[$channel]) => sprintf('Bid strategies are changed here for Search, Display and Performance Max campaigns, not %s ones.', strtolower(ManagerFormat::readable($channel ?: 'UNKNOWN'))),
            $entity->platform === 'linkedin' && ! isset(self::LINKEDIN_STRATEGIES[$objective]) => 'LinkedIn did not report an objective whose bid strategies are known here, so it is changed in LinkedIn Campaign Manager.',
            $current === '' => sprintf('%s did not report a bid strategy at the last read.', $platform),
            default => null,
        };
    }

    /** Whether this amount is offered alongside an editable bid strategy that reads it. */
    private function pairsWithStrategy(CampaignPlatformEntity $entity, string $field): bool
    {
        return in_array($field, self::strategyAmounts($entity), true)
            && in_array('bid_strategy', self::FIELDS[$entity->platform][$entity->entity_type] ?? [], true)
            && $this->categoryEnabled('bid_strategy')
            && $this->strategyRefusal($entity) === null;
    }

    /**
     * Why this strategy cannot be sent with the rest of the change: it needs
     * an amount that is missing, or, for a Meta campaign budget, a bid on
     * every ad set.
     *
     * @param  array<string, mixed>  $proposed
     */
    private function strategyProblem(CampaignPlatformEntity $entity, string $strategy, array $proposed): ?string
    {
        if ($entity->platform === 'meta' && $strategy !== 'LOWEST_COST_WITH_BID_CAP') {
            try {
                $pacing = isset($proposed['pacing_type'])
                    ? AdvancedEditFields::normalize('pacing_type', $proposed['pacing_type'])
                    : data_get($entity->settings, 'pacing_type', []);
            } catch (JsonException) {
                return 'Enter valid JSON for delivery pacing before changing strategy.';
            }
            if (in_array('no_pacing', (array) $pacing, true)) {
                return 'Accelerated pacing needs a bid cap. Change pacing to standard before switching strategy.';
            }
        }

        $amount = self::strategyAmount($entity, $strategy);
        $label = self::strategyLabel($entity->platform, $strategy);

        if ($amount === null) {
            return null;
        }

        $field = $amount['field'];

        if ($amount['required'] && in_array($field, self::FIELDS[$entity->platform][$entity->entity_type] ?? [], true)) {
            $given = array_key_exists($field, $proposed) ? $proposed[$field] : self::current($entity, $field);

            if (! is_numeric($given) || (float) $given <= 0) {
                return in_array($field, $this->editableFields($entity), true)
                    ? sprintf('%s needs a %s. Enter one below.', $label, self::amountName($field))
                    : sprintf('%s needs a %s, and bid changes are not switched on for the campaign manager.', $label, self::amountName($field));
            }
        }

        if ($entity->platform === 'meta' && $entity->entity_type === 'campaign' && $strategy !== strtoupper((string) self::current($entity, 'bid_strategy'))) {
            $missing = CampaignPlatformEntity::query()
                ->where('campaign_id', $entity->campaign_id)
                ->where('entity_type', 'ad_set')
                ->whereNull('removed_at')
                ->get()
                ->reject(fn (CampaignPlatformEntity $adSet): bool => self::holds($adSet, 'bid_amount'))
                ->count();

            if ($missing > 0) {
                return sprintf('Meta needs a bid amount on every ad set before the campaign can use %s, and %d %s none. Set them in Ads Manager first.',
                    strtolower($label), $missing, $missing === 1 ? 'ad set has' : 'ad sets have');
            }
        }

        return null;
    }

    /**
     * @param  array{before: mixed, after: mixed}  $change
     * @param  array<string, array{before: mixed, after: mixed}>  $changes
     * @return list<string>
     */
    private function strategyConfirmations(CampaignPlatformEntity $entity, array $change, array $changes): array
    {
        $platform = ManagerFormat::platform($entity->platform);
        $after = strtoupper((string) $change['after']);
        $label = self::strategyLabel($entity->platform, $after);
        $notes = [sprintf(
            'The bid strategy changes from %s to %s. %s treats this as a new setup: delivery goes back into learning, and cost per result can swing for several days.',
            self::strategyLabel($entity->platform, (string) $change['before']), $label, $platform,
        )];

        if ($entity->platform === 'meta' && $entity->entity_type === 'campaign') {
            $notes[] = 'It applies to every ad set in the campaign.';
        }

        $amount = self::strategyAmount($entity, $after);
        $value = $amount === null ? null : (array_key_exists($amount['field'], $changes) ? $changes[$amount['field']]['after'] : self::current($entity, $amount['field']));

        if ($amount === null || (! $amount['required'] && ! is_numeric($value))) {
            $notes[] = sprintf('%s has no cap, so %s bids whatever it takes to spend the budget, and cost per result can rise. The budget still limits what is spent.', $label, $platform);
        } elseif ($amount['required'] && is_numeric($value) && self::isMoney($amount['field'])) {
            $currency = self::currency($entity);
            $notes[] = sprintf('With the %s at %s %s, delivery can slow or stop when auctions cost more than that.', self::amountName($amount['field']), self::money((float) $value, $currency), $currency);
        }

        if ($entity->platform === 'google' && $after === 'MANUAL_CPC') {
            $notes[] = 'Manual CPC uses each ad group\'s max CPC from now on, so check those bids before this campaign runs.';
        }

        return $notes;
    }

    private static function amountName(string $field): string
    {
        return match ($field) {
            'bid_amount', 'unit_cost' => 'bid',
            'target_cpa' => 'target CPA',
            'target_roas' => 'target ROAS',
            default => strtolower(ManagerFormat::field($field)),
        };
    }

    private function nameRules(CampaignPlatformEntity $entity): array
    {
        return [
            'required', 'string', 'max:'.self::NAME_LIMIT[$entity->platform], 'not_regex:/[\x00-\x1F\x7F]/',
            ...$entity->platform === 'linkedin'
                ? [fn (string $attribute, mixed $value, Closure $fail) => strlen((string) $value) > 200
                    ? $fail('LinkedIn names are limited to 200 bytes, and accented letters count as more than one.')
                    : null]
                : [],
        ];
    }

    /** @return list<mixed> */
    private function moneyRules(CampaignPlatformEntity $entity, string $field, bool $required = true): array
    {
        $decimals = CurrencyMinorUnits::decimals(self::currency($entity));

        return [
            $required ? 'required' : 'nullable',
            'numeric',
            'gt:0',
            function (string $attribute, mixed $value, Closure $fail) use ($entity, $field, $decimals): void {
                if (! is_numeric($value)) {
                    return;
                }

                $pattern = $decimals === 0 ? '/^\d+$/' : '/^\d+(\.\d{1,'.$decimals.'})?$/';

                if (! preg_match($pattern, (string) $value)) {
                    $fail($decimals === 0
                        ? sprintf('Use a whole amount; %s has no smaller unit.', self::currency($entity))
                        : sprintf('Use at most %d decimal places.', $decimals));
                } elseif ($problem = $this->limitProblem($entity, $field, (float) $value)) {
                    $fail($problem);
                }
            },
        ];
    }

    /** Why this amount is outside what the platform runs or this product allows. */
    private function limitProblem(CampaignPlatformEntity $entity, string $field, float $amount, ?int $runDays = null): ?string
    {
        $campaign = $entity->campaign;
        $ceiling = BudgetCeiling::for($campaign);

        if ($ceiling === null) {
            return Str::ucfirst(BudgetCeiling::missingReason($campaign)).'.';
        }

        $currency = self::currency($entity);

        // A limit only ever holds spend back; the budget it sits under is what is checked.
        if ((self::CATEGORY[$field] ?? null) === 'spend') {
            return null;
        }

        if (! self::isBudget($field)) {
            return $amount > $ceiling
                ? sprintf('A bid above %s %s, the most this product lets a campaign spend in a day, is not accepted.', self::money($ceiling, $currency), $currency)
                : null;
        }

        $rules = $this->platforms->for((string) $entity->platform);
        $days = in_array($field, self::LIFETIME, true) ? (int) ($runDays ?? $this->runDays($entity)) : 1;
        $perDay = $amount / max(1, $days);
        $floor = $rules->minimumDailyBudget() * (BudgetCeiling::conversionRate($campaign) ?? 1.0);
        $spread = $days > 1 ? sprintf(' (%s a day over %d days)', self::money($perDay, $currency), $days) : '';

        return match (true) {
            $perDay < $floor => sprintf('%s needs at least %s %s a day%s.', $rules->name(), self::money($floor, $currency), $currency, $spread),
            $perDay > $ceiling => sprintf('That is more than the %s %s a day this product allows%s.', self::money($ceiling, $currency), $currency, $spread),
            default => null,
        };
    }

    /** Whether the platform holds a value for this money field on this object. */
    private static function holds(CampaignPlatformEntity $entity, string $field): bool
    {
        $value = self::current($entity, $field);

        return is_float($value) && $value > 0;
    }

    /** A reported time, in any form the platforms use, as a moment. */
    public static function moment(mixed $value): ?CarbonImmutable
    {
        try {
            return match (true) {
                is_int($value), is_string($value) && ctype_digit($value) => CarbonImmutable::createFromTimestampMs((int) $value),
                is_string($value) && $value !== '' => CarbonImmutable::parse($value),
                default => null,
            };
        } catch (Throwable) {
            return null;
        }
    }
}
