<?php

namespace App\Campaigns\Meta;

use App\Campaigns\Objectives;
use App\Models\Campaign;
use App\Models\CampaignAdSet;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use App\Support\CurrencyMinorUnits;
use Carbon\Carbon;
use Throwable;

/**
 * Rules for changing an ad set that is already on Meta.
 *
 * Draft creation is not this class's job. It reads the live ad set and the
 * live campaign, refuses the combinations Meta will not accept, and names the
 * edits that can reset learning. A missing live figure is not invented.
 */
final class AdSetEditGuard
{
    /** Fields Meta will not change once the ad set exists. */
    public const LOCKED = [
        'optimization_goal',
        'destination_type',
        'billing_event',
        'attribution_spec',
        'is_dynamic_creative',
    ];

    public function __construct(private readonly Meta $meta) {}

    /**
     * @param  array<string, mixed>  $given  fields this edit will send
     * @param  array<string, mixed>  $requested  the raw arguments, including fields this edit must not send
     * @return array{ok: true, warnings: list<string>}|array{ok: false, error: string, locked: array<string, mixed>}
     */
    public function review(Campaign $campaign, string $adSetId, ?CampaignAdSet $row, array $given, array $requested = []): array
    {
        $locked = array_values(array_intersect(array_keys(array_filter(
            $requested,
            static fn (mixed $value): bool => $value !== null && $value !== '',
        )), self::LOCKED));

        $live = $this->adSet($campaign, $adSetId);
        $liveCampaign = $this->campaign($campaign);

        if ($locked !== []) {
            return [
                'ok' => false,
                'error' => $this->lockedError($locked, $live),
                'locked' => $this->lockedValues($locked, $live),
            ];
        }

        if ($refusal = $this->scheduleRefusal($campaign, $row, $given, $live)) {
            return ['ok' => false, 'error' => $refusal, 'locked' => []];
        }

        if ($refusal = $this->budgetRefusal($campaign, $row, $given, $live, $liveCampaign)) {
            return ['ok' => false, 'error' => $refusal, 'locked' => []];
        }

        if ($refusal = $this->startRefusal($given, $live)) {
            return ['ok' => false, 'error' => $refusal, 'locked' => []];
        }

        if ($refusal = $this->bidRefusal($given, $liveCampaign)) {
            return ['ok' => false, 'error' => $refusal, 'locked' => []];
        }

        if ($refusal = $this->spendCapRefusal($campaign, $given, $live, $liveCampaign)) {
            return ['ok' => false, 'error' => $refusal, 'locked' => []];
        }

        if ($refusal = $this->roasRefusal($campaign, $given, $live, $liveCampaign)) {
            return ['ok' => false, 'error' => $refusal, 'locked' => []];
        }

        if ($refusal = $this->pacingRefusal($campaign, $row, $given, $live, $liveCampaign)) {
            return ['ok' => false, 'error' => $refusal, 'locked' => []];
        }

        if ($refusal = $this->audienceRefusal($campaign, $given, $live, $liveCampaign)) {
            return ['ok' => false, 'error' => $refusal, 'locked' => []];
        }

        if ($refusal = $this->optimizationRefusal($campaign, $given, $live, $liveCampaign)) {
            return ['ok' => false, 'error' => $refusal, 'locked' => []];
        }

        return [
            'ok' => true,
            'warnings' => $this->warnings($campaign, $row, $given, $live),
        ];
    }

    /**
     * The optimization fields to post, after the same checks review() makes.
     *
     * @param  array<string, mixed>  $given
     * @return array<string, mixed>
     */
    public function optimizationFields(Campaign $campaign, string $adSetId, array $given): array
    {
        $live = $this->adSet($campaign, $adSetId);
        $liveCampaign = $this->campaign($campaign);

        if ($refusal = $this->optimizationRefusal($campaign, $given, $live, $liveCampaign)) {
            throw new MetaException($refusal);
        }

        return $this->optimizationPayload($given, $live);
    }

    /**
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     * @param  array<string, mixed>  $liveCampaign
     */
    private function optimizationRefusal(Campaign $campaign, array $given, array $live, array $liveCampaign): ?string
    {
        if (array_intersect(array_keys($given), ['conversion_event', 'frequency_control_specs', 'value_rule_set_id', 'value_rules_applied']) === []) {
            return null;
        }

        if (array_key_exists('conversion_event', $given)) {
            $event = strtoupper(trim((string) $given['conversion_event']));

            if (preg_match('/^[A-Z0-9_]+$/', $event) !== 1) {
                return 'The conversion event has to be one of Meta\'s event names, such as PURCHASE.';
            }

            $objective = array_key_exists('objective', $liveCampaign) && filled($liveCampaign['objective'])
                ? (string) $liveCampaign['objective']
                : (string) $campaign->objective;

            if (! Objectives::acceptsEventType($objective, $event)) {
                return 'This campaign cannot optimize toward '.$event.'.';
            }

            $promoted = $live['promoted_object'] ?? null;

            if (! is_array($promoted) || $promoted === []) {
                return 'The current promoted object could not be read, so the conversion event was not changed.';
            }

            if (! filled($promoted['pixel_id'] ?? null) && ! filled($promoted['custom_conversion_id'] ?? null)) {
                return 'This ad set is not optimizing toward a pixel event, so the conversion event cannot be changed.';
            }
        }

        if (array_key_exists('frequency_control_specs', $given)) {
            $goal = strtoupper((string) ($live['optimization_goal'] ?? ''));

            if ($goal === '') {
                return 'The optimization goal could not be read, so the frequency cap was not changed.';
            }

            if ($goal !== 'REACH') {
                return 'A frequency cap is only available when the ad set optimizes for reach.';
            }

            if ($given['frequency_control_specs'] !== [] && ($problem = $this->frequencyProblem($given['frequency_control_specs'])) !== null) {
                return $problem;
            }
        }

        $detach = array_key_exists('value_rules_applied', $given) && ! $this->valueRuleOn($given['value_rules_applied']);
        $attach = array_key_exists('value_rule_set_id', $given);

        if ($detach && $attach) {
            return 'Detach the value rule or set a new one, not both.';
        }

        if (array_key_exists('value_rules_applied', $given) && $given['value_rules_applied'] !== null && $this->valueRuleOn($given['value_rules_applied']) === null) {
            return 'Say whether the value rule is applied or not.';
        }

        if (array_key_exists('value_rules_applied', $given) && $this->valueRuleOn($given['value_rules_applied']) === true && ! $attach) {
            return 'Setting a value rule on needs the value rule set id.';
        }

        if ($attach) {
            if (preg_match('/^[0-9]+$/', (string) $given['value_rule_set_id']) !== 1) {
                return 'A value rule has to be the id of a value rule set on this ad account.';
            }

            if (! in_array($this->bidStrategy($campaign, $given, $live, $liveCampaign), ['LOWEST_COST_WITHOUT_CAP', 'COST_CAP'], true)) {
                return 'A value rule is only available with highest volume or cost cap.';
            }
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     * @return array<string, mixed>
     */
    private function optimizationPayload(array $given, array $live): array
    {
        $fields = [];

        if (array_key_exists('conversion_event', $given)) {
            $promoted = is_array($live['promoted_object'] ?? null) ? $live['promoted_object'] : [];
            unset($promoted['custom_conversion_id'], $promoted['custom_event_str']);
            $promoted['custom_event_type'] = strtoupper(trim((string) $given['conversion_event']));
            $fields['promoted_object'] = json_encode($promoted, JSON_THROW_ON_ERROR);
        }

        if (array_key_exists('frequency_control_specs', $given)) {
            $fields['frequency_control_specs'] = json_encode(
                $this->frequencySpecs($given['frequency_control_specs']),
                JSON_THROW_ON_ERROR,
            );
        }

        if (array_key_exists('value_rule_set_id', $given)) {
            $fields['value_rule_set_id'] = (string) $given['value_rule_set_id'];
            $fields['value_rules_applied'] = 'true';
        } elseif (array_key_exists('value_rules_applied', $given) && $this->valueRuleOn($given['value_rules_applied']) === false) {
            $fields['value_rules_applied'] = 'false';
        }

        return $fields;
    }

    private function frequencyProblem(mixed $specs): ?string
    {
        if (! is_array($specs) || count($specs) !== 1 || ! is_array($specs[0] ?? null)) {
            return 'Send one frequency cap, with the event, the number of days, and the maximum frequency.';
        }

        $spec = $specs[0];
        $event = strtoupper((string) ($spec['event'] ?? 'IMPRESSIONS'));
        $days = $spec['interval_days'] ?? null;
        $times = $spec['max_frequency'] ?? null;
        $whole = static fn (mixed $value): bool => is_numeric($value) && (float) $value === (float) (int) $value;

        if ($event !== 'IMPRESSIONS' || ! $whole($days) || (int) $days < 1 || (int) $days > 90 || ! $whole($times) || (int) $times < 1) {
            return 'A reach frequency cap counts impressions, over 1 to 90 days, at least once.';
        }

        return null;
    }

    /** @return list<array{event: string, interval_days: int, max_frequency: int}> */
    private function frequencySpecs(mixed $specs): array
    {
        if (! is_array($specs) || $specs === []) {
            return [];
        }

        $spec = is_array($specs[0] ?? null) ? $specs[0] : [];

        return [[
            'event' => 'IMPRESSIONS',
            'interval_days' => (int) ($spec['interval_days'] ?? 0),
            'max_frequency' => (int) ($spec['max_frequency'] ?? 0),
        ]];
    }

    private function valueRuleOn(mixed $value): ?bool
    {
        if (in_array($value, [true, 1, '1', 'true'], true)) {
            return true;
        }

        if (in_array($value, [false, 0, '0', 'false'], true)) {
            return false;
        }

        return null;
    }

    /**
     * @return array<string, mixed>
     */
    private function adSet(Campaign $campaign, string $adSetId): array
    {
        try {
            $live = $this->meta->on($campaign->id, null)->readAdSet($adSetId, $campaign->ad_account_id);
        } catch (MetaException) {
            return [];
        }

        return is_array($live) ? $live : [];
    }

    /**
     * @return array<string, mixed>
     */
    private function campaign(Campaign $campaign): array
    {
        if (! filled($campaign->external_campaign_id)) {
            return [];
        }

        try {
            return $this->meta->on($campaign->id, null)->campaign(
                (string) $campaign->external_campaign_id,
                $campaign->ad_account_id,
                fresh: true,
            );
        } catch (MetaException) {
            return [];
        }
    }

    /**
     * @param  list<string>  $fields
     * @param  array<string, mixed>  $live
     */
    private function lockedError(array $fields, array $live): string
    {
        $parts = array_map(function (string $field) use ($live): string {
            $value = $live[$field] ?? null;
            $shown = is_scalar($value) && $value !== ''
                ? (string) $value
                : (is_array($value) ? json_encode($value) : null);

            return $shown === null || $shown === '' || $shown === 'null'
                ? $field.' cannot be changed after the ad set is created'
                : $field.' cannot be changed after the ad set is created. It is '.$shown;
        }, $fields);

        return implode(' ', $parts).'.';
    }

    /**
     * @param  list<string>  $fields
     * @param  array<string, mixed>  $live
     * @return array<string, mixed>
     */
    private function lockedValues(array $fields, array $live): array
    {
        $values = [];

        foreach ($fields as $field) {
            $values[$field] = $live[$field] ?? null;
        }

        return $values;
    }

    /**
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     * @param  array<string, mixed>  $liveCampaign
     */
    private function budgetRefusal(Campaign $campaign, ?CampaignAdSet $row, array $given, array $live, array $liveCampaign): ?string
    {
        if (! array_key_exists('budget', $given)) {
            return null;
        }

        if ($campaign->usesCampaignBudget() || $this->budgetMode($liveCampaign) !== null) {
            return 'This campaign holds the budget itself, so an ad set has none to change. Change the campaign budget instead, or split it across the ad sets first.';
        }

        $liveMode = $this->budgetMode($live);
        $intended = $this->intendedMode($campaign, $row);

        if ($liveMode !== null && $intended !== $liveMode) {
            return 'This ad set uses a '.$liveMode.' budget. The budget type cannot be changed after launch.';
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     */
    private function startRefusal(array $given, array $live): ?string
    {
        if (! array_key_exists('starts_at', $given) || ! is_string($live['start_time'] ?? null) || $live['start_time'] === '') {
            return null;
        }

        try {
            $started = Carbon::parse($live['start_time'])->lte(now());
        } catch (Throwable) {
            return null;
        }

        return $started
            ? 'The start time cannot be changed. This ad set has already started.'
            : null;
    }

    /**
     * A strategy Meta holds on the campaign blocks the ad set.
     *
     * A value stored only on the local campaign has not been published, so it
     * does not count. Meta omits the field when the campaign has no strategy.
     *
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $liveCampaign
     */
    private function bidRefusal(array $given, array $liveCampaign): ?string
    {
        if (! array_key_exists('bid_strategy', $given)) {
            return null;
        }

        $strategy = $liveCampaign['bid_strategy'] ?? null;

        if (! filled($strategy)) {
            return null;
        }

        return 'This campaign already has the bid strategy '.$strategy.', so the ad set cannot carry a different one. Change the campaign bid strategy instead.';
    }

    /**
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     * @return list<string>
     */
    private function warnings(Campaign $campaign, ?CampaignAdSet $row, array $given, array $live): array
    {
        $warnings = [];

        if (array_key_exists('budget', $given) && $this->budgetMovesEnough($campaign, $row, $given, $live)) {
            $warnings[] = 'Changing the budget by more than 20% can reset learning on this ad set.';
        }

        if (array_key_exists('bid_strategy', $given) || array_key_exists('bid_amount', $given) || array_key_exists('roas_average_floor', $given)) {
            $warnings[] = 'Changing the bid can reset learning on this ad set.';
        }

        if (array_key_exists('pacing_type', $given) || array_key_exists('adset_schedule', $given)) {
            $warnings[] = 'Changing the pacing or the hours this ad set runs can reset learning on this ad set.';
        }

        if (is_array($given['targeting'] ?? null) && $given['targeting'] !== []) {
            $keys = array_keys($given['targeting']);
            $placements = array_intersect($keys, [...self::PLACEMENT_FIELDS, 'advantage_placements']);
            $devices = array_intersect($keys, self::DEVICE_FIELDS);

            if (array_diff($keys, self::PLACEMENT_FIELDS, ['advantage_placements'], self::DEVICE_FIELDS) !== []) {
                $warnings[] = 'Changing the audience can reset learning on this ad set.';
            }

            if ($placements !== []) {
                $warnings[] = 'Changing the placements can reset learning on this ad set.';
            }

            if ($devices !== []) {
                $warnings[] = 'Changing the device targeting can reset learning on this ad set.';
            }
        }

        if (array_intersect(array_keys($given), ['conversion_event', 'frequency_control_specs', 'value_rule_set_id', 'value_rules_applied']) !== []) {
            $warnings[] = 'Changing the optimization can reset learning on this ad set.';
        }

        if ($this->spendCapMovesEnough($campaign, $given, $live)) {
            $warnings[] = 'Changing a spend limit by more than 20% can reset learning on this ad set.';
        }

        return $warnings;
    }

    /**
     * Spend limits belong to an ad set only while the campaign holds the money.
     *
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     * @param  array<string, mixed>  $liveCampaign
     */
    private function spendCapRefusal(Campaign $campaign, array $given, array $live, array $liveCampaign): ?string
    {
        $caps = array_intersect_key($given, array_flip([
            'daily_min_spend_target', 'daily_spend_cap', 'lifetime_min_spend_target', 'lifetime_spend_cap',
        ]));

        if ($caps === []) {
            return null;
        }

        if (! $this->campaignHoldsBudget($campaign, $liveCampaign)) {
            return 'Spend limits are only for an ad set whose campaign holds the budget. This ad set has its own budget.';
        }

        if ($this->budgetMode($live) !== null) {
            return 'This ad set has its own budget, so spend limits cannot be set on it.';
        }

        foreach ([['daily_min_spend_target', 'daily_spend_cap'], ['lifetime_min_spend_target', 'lifetime_spend_cap']] as [$minField, $capField]) {
            $min = $this->limit($given, $live, $minField, $campaign->currency);
            $cap = $this->limit($given, $live, $capField, $campaign->currency);

            if ($min !== null && $cap !== null && $min > $cap) {
                return 'The minimum spend cannot be higher than the spend cap.';
            }
        }

        return null;
    }

    /**
     * A schedule replaces the whole list, and it cannot ride along with a budget-type switch.
     *
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     */
    private function scheduleRefusal(Campaign $campaign, ?CampaignAdSet $row, array $given, array $live): ?string
    {
        if (! array_key_exists('budget_schedule_specs', $given) || ! array_key_exists('budget', $given)) {
            return null;
        }

        $liveMode = $this->budgetMode($live);

        if ($liveMode !== null && $this->intendedMode($campaign, $row) !== $liveMode) {
            return 'A budget schedule cannot be saved in the same change as a switch between daily and lifetime budget.';
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     */
    private function spendCapMovesEnough(Campaign $campaign, array $given, array $live): bool
    {
        foreach (['daily_min_spend_target', 'daily_spend_cap', 'lifetime_min_spend_target', 'lifetime_spend_cap'] as $field) {
            if (! array_key_exists($field, $given) || ! is_numeric($given[$field])) {
                continue;
            }

            if (! $this->moneyPresent($live[$field] ?? null)) {
                continue;
            }

            $current = CurrencyMinorUnits::toMajor((int) $live[$field], $campaign->currency);

            if ($current > 0 && abs(((float) $given[$field]) - $current) / $current > 0.20) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     */
    private function limit(array $given, array $live, string $field, ?string $currency): ?float
    {
        if (array_key_exists($field, $given) && is_numeric($given[$field])) {
            return (float) $given[$field];
        }

        if ($this->moneyPresent($live[$field] ?? null)) {
            return CurrencyMinorUnits::toMajor((int) $live[$field], $currency);
        }

        return null;
    }

    /**
     * A ROAS goal belongs only to the minimum-ROAS bid strategy.
     *
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     * @param  array<string, mixed>  $liveCampaign
     */
    private function roasRefusal(Campaign $campaign, array $given, array $live, array $liveCampaign): ?string
    {
        if (! array_key_exists('roas_average_floor', $given)) {
            return null;
        }

        if (! is_numeric($given['roas_average_floor']) || (float) $given['roas_average_floor'] <= 0) {
            return 'The ROAS goal has to be a number greater than zero.';
        }

        if ($this->bidStrategy($campaign, $given, $live, $liveCampaign) !== 'LOWEST_COST_WITH_MIN_ROAS') {
            return 'A ROAS goal is only available when the bid strategy is lowest cost with a minimum ROAS (LOWEST_COST_WITH_MIN_ROAS).';
        }

        return null;
    }

    /**
     * Accelerated pacing needs a bid cap. Dayparting needs a lifetime budget and day parting.
     *
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     * @param  array<string, mixed>  $liveCampaign
     */
    private function pacingRefusal(Campaign $campaign, ?CampaignAdSet $row, array $given, array $live, array $liveCampaign): ?string
    {
        $pacing = $this->pacingName($given['pacing_type'] ?? null);
        $schedule = array_key_exists('adset_schedule', $given) ? $this->dayParts($given['adset_schedule']) : null;

        if ($pacing === null && $schedule === null) {
            return null;
        }

        if ($pacing !== null && ! in_array($pacing, ['standard', 'no_pacing', 'day_parting'], true)) {
            return 'Pacing must be standard, no_pacing, or day_parting.';
        }

        if ($pacing === 'no_pacing' && $this->bidStrategy($campaign, $given, $live, $liveCampaign) !== 'LOWEST_COST_WITH_BID_CAP') {
            return 'Accelerated pacing is only available with a bid cap (LOWEST_COST_WITH_BID_CAP).';
        }

        if ($schedule !== null && $schedule !== []) {
            if (! $this->adSetHasLifetimeBudget($campaign, $row, $live, $liveCampaign)) {
                return 'Dayparting is only available on an ad set with its own lifetime budget.';
            }

            if ($invalid = $this->invalidDayPart($schedule)) {
                return $invalid;
            }

            if ($pacing !== null && $pacing !== 'day_parting') {
                return 'Dayparting needs pacing set to day parting, and it cannot be combined with accelerated pacing.';
            }
        }

        if ($pacing === 'day_parting' && ($schedule === null || $schedule === []) && ! $this->hasLiveSchedule($live)) {
            return 'Day parting needs a schedule of the hours the ad set can run.';
        }

        if (in_array($pacing, ['standard', 'no_pacing'], true) && $schedule === null && $this->hasLiveSchedule($live)) {
            return 'Clear the dayparting schedule in the same change before switching off day parting.';
        }

        return null;
    }

    /**
     * The strategy that will be in force after this edit.
     *
     * A strategy sent in this request wins. Otherwise the live campaign strategy
     * wins over the ad set. A strategy stored only on the local campaign does not.
     *
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     * @param  array<string, mixed>  $liveCampaign
     */
    private function bidStrategy(Campaign $campaign, array $given, array $live, array $liveCampaign): ?string
    {
        if (filled($given['bid_strategy'] ?? null)) {
            return (string) $given['bid_strategy'];
        }

        if (array_key_exists('bid_strategy', $liveCampaign) && filled($liveCampaign['bid_strategy'])) {
            return (string) $liveCampaign['bid_strategy'];
        }

        if (filled($live['bid_strategy'] ?? null)) {
            return (string) $live['bid_strategy'];
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $live
     * @param  array<string, mixed>  $liveCampaign
     */
    private function adSetHasLifetimeBudget(Campaign $campaign, ?CampaignAdSet $row, array $live, array $liveCampaign): bool
    {
        $mode = $this->budgetMode($live);

        if ($mode === 'lifetime') {
            return true;
        }

        if ($mode === 'daily' || $this->campaignHoldsBudget($campaign, $liveCampaign)) {
            return false;
        }

        return ($row?->budget_mode ?: $campaign->budgetMode()) === 'lifetime';
    }

    /**
     * @param  list<array<string, mixed>>  $schedule
     */
    private function invalidDayPart(array $schedule): ?string
    {
        foreach ($schedule as $block) {
            $days = array_filter((array) ($block['days'] ?? []), static fn (mixed $day): bool => is_numeric($day) && (int) $day >= 0 && (int) $day <= 6);
            $start = $block['start_minute'] ?? null;
            $end = $block['end_minute'] ?? null;
            $timezone = (string) ($block['timezone_type'] ?? 'ADVERTISER');
            $valid = $days !== []
                && is_numeric($start) && is_numeric($end)
                && (int) $start >= 0 && (int) $end <= 1440 && (int) $start < (int) $end
                && in_array($timezone, ['USER', 'ADVERTISER'], true);

            if (! $valid) {
                return 'Each daypart needs days from 0 (Sunday) to 6 (Saturday), and a start minute before the end minute, between 0 and 1440.';
            }
        }

        return null;
    }

    /** @param  array<string, mixed>  $live */
    private function hasLiveSchedule(array $live): bool
    {
        return is_array($live['adset_schedule'] ?? null) && $live['adset_schedule'] !== [];
    }

    private function pacingName(mixed $value): ?string
    {
        if (is_array($value)) {
            $value = $value[0] ?? null;
        }

        if (! is_string($value) && ! is_numeric($value)) {
            return null;
        }

        $name = strtolower(trim((string) $value));

        return $name === '' ? null : $name;
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function dayParts(mixed $specs): array
    {
        if (is_string($specs)) {
            $decoded = json_decode($specs, true);
            $specs = is_array($decoded) ? $decoded : [];
        }

        if (! is_array($specs)) {
            return [];
        }

        return array_values(array_filter($specs, static fn (mixed $spec): bool => is_array($spec)));
    }

    /** Audience keys this edit may change. */
    private const AUDIENCE_FIELDS = [
        'geo_locations', 'excluded_geo_locations', 'age_min', 'age_max', 'genders', 'locales',
        'custom_audiences', 'excluded_custom_audiences', 'flexible_spec', 'exclusions',
        'advantage_audience', 'targeting_relaxation_types',
    ];

    /** Placement keys. Advantage+ is the absence of these keys. */
    private const PLACEMENT_FIELDS = [
        'publisher_platforms', 'facebook_positions', 'instagram_positions',
        'audience_network_positions', 'messenger_positions', 'threads_positions',
    ];

    /** Positions Meta still accepts. A retired position refuses the whole ad set. */
    private const PLACEMENT_POSITIONS = [
        'facebook' => ['feed', 'story', 'facebook_reels', 'marketplace', 'search'],
        'instagram' => ['stream', 'story', 'reels'],
        'messenger' => ['messenger_home', 'story'],
        'audience_network' => ['classic', 'rewarded_video'],
        'threads' => ['threads_stream'],
    ];

    /** Device keys. An empty list clears that limit. */
    private const DEVICE_FIELDS = [
        'device_platforms', 'user_os', 'user_device', 'excluded_user_device', 'wireless_carrier',
    ];

    private const RESTRICTED_CATEGORIES = ['HOUSING', 'EMPLOYMENT', 'CREDIT', 'FINANCIAL_PRODUCTS_SERVICES'];

    /**
     * The full targeting spec to post, with only the audience keys replaced.
     *
     * @return array<string, mixed>
     */
    public function mergedAudience(Campaign $campaign, string $adSetId, mixed $patch): array
    {
        $decoded = $this->audiencePatch($patch);

        if (! is_array($decoded) || $decoded === []) {
            throw new MetaException('The audience has to be sent as its fields, such as age, gender, or location.');
        }

        $live = $this->adSet($campaign, $adSetId);
        $liveCampaign = $this->campaign($campaign);

        $ready = null;

        if ($refusal = $this->audienceRefusal($campaign, ['targeting' => $decoded], $live, $liveCampaign, $ready)) {
            throw new MetaException($refusal);
        }

        return $this->applyAudience($live['targeting'], $ready ?? $decoded);
    }

    /**
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     * @param  array<string, mixed>  $liveCampaign
     */
    private function audienceRefusal(Campaign $campaign, array $given, array $live, array $liveCampaign, ?array &$ready = null): ?string
    {
        if (! array_key_exists('targeting', $given) || $given['targeting'] === []) {
            return null;
        }

        $patch = $this->audiencePatch($given['targeting']);

        if ($patch === null) {
            return 'The audience has to be sent as its fields, such as age, gender, or location.';
        }

        if ($unknown = array_diff(array_keys($patch), [...self::AUDIENCE_FIELDS, ...self::PLACEMENT_FIELDS, ...self::DEVICE_FIELDS, 'advantage_placements'])) {
            return 'That targeting field cannot be changed here. Leave out '.implode(', ', $unknown).'.';
        }

        if ($placements = $this->placementShape($patch)) {
            return $placements;
        }

        if ($devices = $this->deviceShape($patch)) {
            return $devices;
        }

        if ($locales = $this->resolveLocales($campaign, $patch)) {
            return $locales;
        }

        if ($shape = $this->audienceShape($patch)) {
            return $shape;
        }

        $ready = $patch;

        $current = $live['targeting'] ?? null;

        if (! is_array($current) || $current === []) {
            return 'The current audience could not be read, so nothing was changed.';
        }

        $merged = $this->applyAudience($current, $patch);

        if ($placements = $this->placementResult($patch, $merged)) {
            return $placements;
        }

        if ($devices = $this->deviceResult($patch, $merged)) {
            return $devices;
        }

        if (($merged['age_min'] ?? 18) > ($merged['age_max'] ?? 65)) {
            return 'The minimum age cannot be higher than the maximum age.';
        }

        return $this->specialCategoryRefusal($this->specialCategories($campaign, $liveCampaign), $merged);
    }

    /**
     * Turn a language name into the locale Meta stores. A number is already a locale.
     *
     * Several matches are returned to the user instead of a guess. An empty list is
     * left alone so the language restriction can be cleared.
     *
     * @param  array<string, mixed>  $patch
     */
    private function resolveLocales(Campaign $campaign, array &$patch): ?string
    {
        if (! array_key_exists('locales', $patch) || $patch['locales'] === []) {
            return null;
        }

        if (! is_array($patch['locales'])) {
            return 'Name a language, or pass a locale number from search_ad_locales.';
        }

        $locales = [];

        foreach ($patch['locales'] as $locale) {
            if (is_int($locale) || (is_string($locale) && preg_match('/^\d+$/', $locale) === 1)) {
                $number = (int) $locale;

                if ($number < 1) {
                    return 'A language locale has to be a number from search_ad_locales.';
                }

                $locales[] = $number;

                continue;
            }

            if (! is_string($locale) || trim($locale) === '') {
                return 'Name a language, or pass a locale number from search_ad_locales.';
            }

            try {
                $matches = $this->meta->on($campaign->id, null)->adLocales((string) $campaign->ad_account_id, trim($locale));
            } catch (MetaException) {
                return 'Meta\'s language list could not be read, so nothing was changed.';
            } catch (\InvalidArgumentException) {
                return 'Name a language to search for.';
            }

            $exact = array_values(array_filter(
                $matches,
                static fn (array $row): bool => strcasecmp($row['name'], trim($locale)) === 0,
            ));
            $chosen = count($exact) === 1 ? $exact : (count($matches) === 1 ? $matches : []);

            if (count($chosen) !== 1) {
                return $this->localeChoices(trim($locale), $matches);
            }

            $locales[] = $chosen[0]['locale'];
        }

        $patch['locales'] = array_values(array_unique($locales));

        return null;
    }

    /**
     * @param  list<array{locale: int, name: string}>  $matches
     */
    private function localeChoices(string $query, array $matches): string
    {
        if ($matches === []) {
            return 'Meta has no language matching "'.$query.'". Nothing was changed.';
        }

        $choices = array_map(
            static fn (array $row): string => $row['name'].' is '.$row['locale'],
            $matches,
        );

        return 'Ask the user which language they mean, then send that locale. '.implode('. ', $choices).'. Nothing was changed.';
    }

    /**
     * @return array<string, mixed>|null
     */
    private function audiencePatch(mixed $patch): ?array
    {
        if (is_string($patch)) {
            $decoded = json_decode($patch, true);
            $patch = is_array($decoded) ? $decoded : null;
        }

        return is_array($patch) ? $patch : null;
    }

    /**
     * @param  array<string, mixed>  $patch
     */
    private function audienceShape(array $patch): ?string
    {
        foreach (['age_min', 'age_max'] as $field) {
            if (! array_key_exists($field, $patch)) {
                continue;
            }

            $age = $patch[$field];
            $whole = is_numeric($age) && (float) $age === (float) (int) $age;

            if (! $whole || (int) $age < 18 || (int) $age > 65) {
                return 'Age has to be a whole number from 18 to 65.';
            }
        }

        if (array_key_exists('genders', $patch) && $patch['genders'] !== [] && $this->genders($patch['genders']) === null) {
            return 'Gender is 1 for male and 2 for female. Leave it empty to reach everyone.';
        }

        if (array_key_exists('advantage_audience', $patch) && ! in_array($patch['advantage_audience'], [0, 1, '0', '1'], true)) {
            return 'Advantage+ audience is 0 to keep the audience as set, or 1 to let Meta expand it.';
        }

        if (array_key_exists('geo_locations', $patch) && ! $this->locationPresent($patch['geo_locations'])) {
            return 'A location is required. Name a country, region, city, or ZIP.';
        }

        if (array_key_exists('geo_locations', $patch) && $this->badLocationType($patch['geo_locations'])) {
            return 'Location type is home, recent, or travel.';
        }

        if (array_key_exists('excluded_geo_locations', $patch) && $patch['excluded_geo_locations'] !== [] && $this->badLocationType($patch['excluded_geo_locations'])) {
            return 'Location type is home, recent, or travel.';
        }

        if ($this->badAudiences($patch, 'custom_audiences') || $this->badAudiences($patch, 'excluded_custom_audiences')) {
            return 'Each custom audience needs an id from this ad account.';
        }

        if (array_key_exists('targeting_relaxation_types', $patch) && $patch['targeting_relaxation_types'] !== [] && $this->relaxation($patch['targeting_relaxation_types']) === null) {
            return 'Audience expansion is 0 or 1 for lookalike and custom_audience.';
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $current
     * @param  array<string, mixed>  $patch
     * @return array<string, mixed>
     */
    private function applyAudience(array $current, array $patch): array
    {
        $merged = $current;

        foreach (['genders', 'locales', 'custom_audiences', 'excluded_custom_audiences', 'flexible_spec', 'exclusions', 'excluded_geo_locations'] as $field) {
            if (! array_key_exists($field, $patch)) {
                continue;
            }

            if ($patch[$field] === [] || $patch[$field] === null) {
                unset($merged[$field]);

                continue;
            }

            $merged[$field] = match ($field) {
                'genders' => $this->genders($patch[$field]),
                'custom_audiences', 'excluded_custom_audiences' => $this->audiences($patch[$field]),
                'locales' => array_values(array_map(static fn (mixed $locale): int => (int) $locale, (array) $patch[$field])),
                default => $patch[$field],
            };
        }

        foreach (['age_min', 'age_max'] as $field) {
            if (array_key_exists($field, $patch)) {
                $merged[$field] = (int) $patch[$field];
            }
        }

        if (array_key_exists('geo_locations', $patch)) {
            $merged['geo_locations'] = $patch['geo_locations'];
        }

        if (array_key_exists('advantage_audience', $patch)) {
            $automation = is_array($merged['targeting_automation'] ?? null) ? $merged['targeting_automation'] : [];
            $automation['advantage_audience'] = (int) $patch['advantage_audience'];
            $merged['targeting_automation'] = $automation;
        }

        if (array_key_exists('targeting_relaxation_types', $patch)) {
            if ($patch['targeting_relaxation_types'] === []) {
                unset($merged['targeting_relaxation_types']);
            } else {
                $merged['targeting_relaxation_types'] = $this->relaxation($patch['targeting_relaxation_types']);
            }
        }

        return $this->applyDevices($this->applyPlacements($merged, $patch), $patch);
    }

    /**
     * @param  array<string, mixed>  $patch
     */
    private function deviceShape(array $patch): ?string
    {
        if (array_intersect(array_keys($patch), self::DEVICE_FIELDS) === []) {
            return null;
        }

        if (array_key_exists('device_platforms', $patch)) {
            foreach ((array) $patch['device_platforms'] as $platform) {
                if (! is_string($platform) || ! in_array(strtolower($platform), ['mobile', 'desktop'], true)) {
                    return 'A device platform is mobile or desktop.';
                }
            }
        }

        if (array_key_exists('user_os', $patch)) {
            foreach ((array) $patch['user_os'] as $system) {
                if (! is_string($system) || preg_match('/^(?:iOS|Android)(?:_ver_\d+(?:\.\d+){0,2}_(?:and_above|to_\d+(?:\.\d+){0,2}))?$/', $system) !== 1) {
                    return 'An operating system is iOS or Android, with an optional version such as iOS_ver_14.0_and_above.';
                }
            }
        }

        foreach (['user_device', 'excluded_user_device'] as $field) {
            if (! array_key_exists($field, $patch)) {
                continue;
            }

            foreach ((array) $patch[$field] as $name) {
                if (! is_string($name) || preg_match('/^[A-Za-z0-9][A-Za-z0-9 _.-]{0,79}$/', $name) !== 1) {
                    return 'A device name has to be the name Meta uses, such as iPhone or iPad.';
                }
            }
        }

        if (array_key_exists('wireless_carrier', $patch)) {
            foreach ((array) $patch['wireless_carrier'] as $carrier) {
                if (! is_string($carrier) || ! in_array(strtolower(str_replace(['-', ' '], '', $carrier)), ['wifi'], true)) {
                    return 'Wi-Fi is the only carrier limit. Use Wifi, or an empty list to clear it.';
                }
            }
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $patch
     * @param  array<string, mixed>  $merged
     */
    private function deviceResult(array $patch, array $merged): ?string
    {
        if (array_intersect(array_keys($patch), self::DEVICE_FIELDS) === []) {
            return null;
        }

        $included = is_array($merged['user_device'] ?? null) ? $merged['user_device'] : [];
        $excluded = is_array($merged['excluded_user_device'] ?? null) ? $merged['excluded_user_device'] : [];

        if (array_intersect($included, $excluded) !== []) {
            return 'A device cannot be both included and excluded.';
        }

        $platforms = $merged['device_platforms'] ?? null;
        $desktopOnly = is_array($platforms) && $platforms === ['desktop'];

        if (! $desktopOnly) {
            return null;
        }

        foreach (['user_os', 'user_device', 'excluded_user_device', 'wireless_carrier'] as $field) {
            if (is_array($merged[$field] ?? null) && $merged[$field] !== []) {
                return 'Operating system, device model, and Wi-Fi only apply when mobile is included.';
            }
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $merged
     * @param  array<string, mixed>  $patch
     * @return array<string, mixed>
     */
    private function applyDevices(array $merged, array $patch): array
    {
        if (array_key_exists('device_platforms', $patch)) {
            if ($patch['device_platforms'] === []) {
                unset($merged['device_platforms']);
            } else {
                $merged['device_platforms'] = array_values(array_unique(array_map(
                    static fn (mixed $platform): string => strtolower((string) $platform),
                    (array) $patch['device_platforms'],
                )));
            }
        }

        foreach (['user_os', 'user_device', 'excluded_user_device'] as $field) {
            if (! array_key_exists($field, $patch)) {
                continue;
            }

            if ($patch[$field] === []) {
                unset($merged[$field]);

                continue;
            }

            $merged[$field] = array_values(array_unique(array_map(strval(...), (array) $patch[$field])));
        }

        if (array_key_exists('wireless_carrier', $patch)) {
            if ($patch['wireless_carrier'] === []) {
                unset($merged['wireless_carrier']);
            } else {
                $merged['wireless_carrier'] = ['Wifi'];
            }
        }

        return $merged;
    }

    /**
     * @param  array<string, mixed>  $patch
     */
    private function placementShape(array $patch): ?string
    {
        $manual = array_intersect(array_keys($patch), self::PLACEMENT_FIELDS);
        $named = array_key_exists('advantage_placements', $patch);

        if (! $named && $manual === []) {
            return null;
        }

        if ($named && ! in_array($patch['advantage_placements'], [true, false, 1, 0, '1', '0'], true)) {
            return 'Advantage+ placements is true or false.';
        }

        $advantage = $named && in_array($patch['advantage_placements'], [true, 1, '1'], true);

        if ($advantage && $this->placementFieldsFilled($patch)) {
            return 'Choose Advantage+ placements or name the platforms, not both.';
        }

        if (array_key_exists('publisher_platforms', $patch)) {
            foreach ((array) $patch['publisher_platforms'] as $platform) {
                if (! is_string($platform) || ! array_key_exists($platform, self::PLACEMENT_POSITIONS)) {
                    return 'A platform is facebook, instagram, audience_network, messenger, or threads.';
                }
            }
        }

        foreach (self::PLACEMENT_POSITIONS as $platform => $allowed) {
            $field = $this->positionField($platform);

            if (! array_key_exists($field, $patch)) {
                continue;
            }

            foreach ((array) $patch[$field] as $position) {
                if (! is_string($position) || ! in_array($position, $allowed, true)) {
                    return $position.' is not a '.$platform.' position that can be selected.';
                }
            }
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $patch
     * @param  array<string, mixed>  $merged
     */
    private function placementResult(array $patch, array $merged): ?string
    {
        $advantage = in_array($patch['advantage_placements'] ?? false, [true, 1, '1'], true)
            || (array_key_exists('publisher_platforms', $patch) && $patch['publisher_platforms'] === []);

        if ($advantage || array_intersect(array_keys($patch), self::PLACEMENT_FIELDS) === []) {
            return null;
        }

        $platforms = $merged['publisher_platforms'] ?? null;

        if (! is_array($platforms) || $platforms === []) {
            return 'Name the platforms, or switch on Advantage+ placements.';
        }

        foreach ($platforms as $platform) {
            $positions = $merged[$this->positionField((string) $platform)] ?? null;

            if (! is_array($positions) || $positions === []) {
                return 'Each selected platform needs at least one position.';
            }
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $merged
     * @param  array<string, mixed>  $patch
     * @return array<string, mixed>
     */
    private function applyPlacements(array $merged, array $patch): array
    {
        $advantage = in_array($patch['advantage_placements'] ?? false, [true, 1, '1'], true)
            || (array_key_exists('publisher_platforms', $patch) && $patch['publisher_platforms'] === []);

        if ($advantage) {
            foreach (self::PLACEMENT_FIELDS as $field) {
                unset($merged[$field]);
            }

            return $merged;
        }

        if (array_intersect(array_keys($patch), self::PLACEMENT_FIELDS) === []) {
            return $merged;
        }

        if (array_key_exists('publisher_platforms', $patch)) {
            $platforms = array_values(array_unique(array_map(strval(...), (array) $patch['publisher_platforms'])));
            $merged['publisher_platforms'] = $platforms;

            foreach (array_keys(self::PLACEMENT_POSITIONS) as $platform) {
                if (! in_array($platform, $platforms, true)) {
                    unset($merged[$this->positionField($platform)]);
                }
            }
        }

        foreach (array_keys(self::PLACEMENT_POSITIONS) as $platform) {
            $field = $this->positionField($platform);

            if (! array_key_exists($field, $patch) || $patch[$field] === []) {
                continue;
            }

            $merged[$field] = array_values(array_unique(array_map(strval(...), (array) $patch[$field])));
        }

        $platforms = is_array($merged['publisher_platforms'] ?? null) ? $merged['publisher_platforms'] : [];

        if (in_array('threads', $platforms, true)) {
            if (! in_array('instagram', $platforms, true)) {
                $platforms[] = 'instagram';
                $merged['publisher_platforms'] = array_values($platforms);
            }

            $instagram = is_array($merged['instagram_positions'] ?? null) ? $merged['instagram_positions'] : [];

            if (! in_array('stream', $instagram, true)) {
                $instagram[] = 'stream';
                $merged['instagram_positions'] = array_values($instagram);
            }
        }

        return $merged;
    }

    /** @param  array<string, mixed>  $patch */
    private function placementFieldsFilled(array $patch): bool
    {
        foreach (self::PLACEMENT_FIELDS as $field) {
            if (array_key_exists($field, $patch) && $patch[$field] !== []) {
                return true;
            }
        }

        return false;
    }

    private function positionField(string $platform): string
    {
        return $platform === 'audience_network' ? 'audience_network_positions' : $platform.'_positions';
    }

    /**
     * @param  list<string>  $categories
     * @param  array<string, mixed>  $merged
     */
    private function specialCategoryRefusal(array $categories, array $merged): ?string
    {
        $restricted = array_values(array_intersect($categories, self::RESTRICTED_CATEGORIES));

        if ($restricted === []) {
            return null;
        }

        $named = implode(', ', $restricted);
        $minimum = (int) ($merged['age_min'] ?? 18);
        $maximum = (int) ($merged['age_max'] ?? 65);

        if ($minimum > 18 || $maximum < 65) {
            return 'This campaign is in the '.$named.' category, so the age cannot be narrowed. It has to stay 18 to 65.';
        }

        if (is_array($merged['genders'] ?? null) && $merged['genders'] !== []) {
            return 'This campaign is in the '.$named.' category, so a gender cannot be set.';
        }

        $locations = array_filter([
            $merged['geo_locations'] ?? null,
            $merged['excluded_geo_locations'] ?? null,
        ], static fn (mixed $geo): bool => is_array($geo));

        foreach ($locations as $geo) {
            if (is_array($geo['zips'] ?? null) && $geo['zips'] !== []) {
                return 'This campaign is in the '.$named.' category, so ZIP codes cannot be used.';
            }
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $liveCampaign
     * @return list<string>
     */
    private function specialCategories(Campaign $campaign, array $liveCampaign): array
    {
        $categories = array_key_exists('special_ad_categories', $liveCampaign)
            ? (array) $liveCampaign['special_ad_categories']
            : (array) ($campaign->special_ad_categories ?? []);

        return array_values(array_filter(
            $categories,
            static fn (mixed $category): bool => is_string($category) && $category !== '' && $category !== 'NONE',
        ));
    }

    private function locationPresent(mixed $geo): bool
    {
        if (! is_array($geo)) {
            return false;
        }

        foreach (['countries', 'regions', 'cities', 'zips', 'geo_markets', 'custom_locations', 'country_groups'] as $field) {
            if (is_array($geo[$field] ?? null) && $geo[$field] !== []) {
                return true;
            }
        }

        return false;
    }

    private function badLocationType(mixed $geo): bool
    {
        if (! is_array($geo) || ! array_key_exists('location_types', $geo)) {
            return false;
        }

        foreach ((array) $geo['location_types'] as $type) {
            if (! in_array($type, ['home', 'recent', 'travel'], true)) {
                return true;
            }
        }

        return false;
    }

    /** @return list<int>|null */
    private function genders(mixed $value): ?array
    {
        if (! is_array($value)) {
            return null;
        }

        $genders = [];

        foreach ($value as $gender) {
            if (! is_numeric($gender) || ! in_array((int) $gender, [1, 2], true)) {
                return null;
            }

            $genders[] = (int) $gender;
        }

        return array_values(array_unique($genders));
    }

    /**
     * @param  array<string, mixed>  $patch
     */
    private function badAudiences(array $patch, string $field): bool
    {
        if (! array_key_exists($field, $patch) || $patch[$field] === []) {
            return false;
        }

        $audiences = $this->audiences($patch[$field]);

        return $audiences === [] || collect($audiences)->contains(
            static fn (array $audience): bool => ! filled($audience['id'] ?? null),
        );
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function audiences(mixed $value): array
    {
        if (! is_array($value)) {
            return [];
        }

        $audiences = [];

        foreach ($value as $audience) {
            if (is_string($audience) || is_numeric($audience)) {
                $audiences[] = ['id' => (string) $audience];

                continue;
            }

            if (is_array($audience)) {
                $audiences[] = filled($audience['id'] ?? null)
                    ? ['id' => (string) $audience['id']] + $audience
                    : $audience;
            }
        }

        return $audiences;
    }

    /**
     * @return array<string, int>|null
     */
    private function relaxation(mixed $value): ?array
    {
        if (! is_array($value)) {
            return null;
        }

        $relaxed = [];

        foreach ($value as $field => $setting) {
            if (! in_array($field, ['lookalike', 'custom_audience'], true) || ! in_array($setting, [0, 1, '0', '1'], true)) {
                return null;
            }

            $relaxed[$field] = (int) $setting;
        }

        return $relaxed === [] ? null : $relaxed;
    }

    /**
     * @param  array<string, mixed>  $liveCampaign
     */
    private function campaignHoldsBudget(Campaign $campaign, array $liveCampaign): bool
    {
        return $campaign->usesCampaignBudget() || $this->budgetMode($liveCampaign) !== null;
    }

    /**
     * @param  array<string, mixed>  $given
     * @param  array<string, mixed>  $live
     */
    private function budgetMovesEnough(Campaign $campaign, ?CampaignAdSet $row, array $given, array $live): bool
    {
        $current = $this->currentBudget($campaign, $row, $live);
        $next = (float) $given['budget'];

        if ($current === null || $current <= 0) {
            return false;
        }

        return abs($next - $current) / $current > 0.20;
    }

    /**
     * @param  array<string, mixed>  $live
     */
    private function currentBudget(Campaign $campaign, ?CampaignAdSet $row, array $live): ?float
    {
        $mode = $this->budgetMode($live) ?? $this->intendedMode($campaign, $row);
        $minor = $mode === 'lifetime' ? ($live['lifetime_budget'] ?? null) : ($live['daily_budget'] ?? null);

        if ($this->moneyPresent($minor)) {
            return CurrencyMinorUnits::toMajor((int) $minor, $campaign->currency);
        }

        $local = $row?->budget;

        return $local === null ? null : (float) $local;
    }

    /**
     * @param  array<string, mixed>  $object
     */
    private function budgetMode(array $object): ?string
    {
        $daily = $this->moneyPresent($object['daily_budget'] ?? null);
        $lifetime = $this->moneyPresent($object['lifetime_budget'] ?? null);

        if ($daily === $lifetime) {
            return null;
        }

        return $daily ? 'daily' : 'lifetime';
    }

    private function intendedMode(Campaign $campaign, ?CampaignAdSet $row): string
    {
        return $row?->budget_mode ?: $campaign->budgetMode();
    }

    private function moneyPresent(mixed $value): bool
    {
        return is_numeric($value) && (int) $value > 0;
    }
}
