<?php

namespace App\Campaigns\Manager\Editing;

use App\Campaigns\BudgetCeiling;
use App\Campaigns\Manager\Canonical;
use App\Models\CampaignPlatformEntity;
use App\Support\CurrencyMinorUnits;
use Carbon\CarbonImmutable;
use Closure;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use JsonException;

final class AdvancedEditFields
{
    public const array META_TARGETING = [
        'geo_locations', 'excluded_geo_locations', 'locales', 'custom_audiences', 'excluded_custom_audiences',
        'flexible_spec', 'advantage_audience', 'targeting_relaxation_types', 'facebook_positions',
        'instagram_positions', 'audience_network_positions', 'messenger_positions', 'threads_positions',
        'device_platforms', 'user_os', 'user_device', 'excluded_user_device', 'wireless_carrier',
    ];

    public const array META_SETTINGS = ['pacing_type', 'adset_schedule', 'roas_floor', 'conversion_event', 'budget_schedules'];

    public const array GOOGLE = ['location_targets', 'excluded_locations', 'language_targets', 'device_exclusions', 'delivery_schedule'];

    public const array GOOGLE_GROUP = ['audience_criteria', 'keywords'];

    public const array GOOGLE_SETTINGS = ['frequency_caps', 'network_settings', 'geo_target_type', 'conversion_goals'];

    public const array LINKEDIN = ['targeting_criteria', 'audience_expansion', 'offsite_delivery', 'frequency_optimization', 'conversion_rules'];

    private const array FACETS = [
        'interests', 'behaviors', 'education_schools', 'education_statuses', 'education_majors',
        'work_employers', 'work_positions', 'relationship_statuses', 'life_events', 'industries',
        'income', 'family_statuses',
    ];

    public static function handles(string $field): bool
    {
        return in_array($field, [...self::META_TARGETING, ...self::META_SETTINGS, ...self::GOOGLE, ...self::GOOGLE_GROUP, ...self::GOOGLE_SETTINGS, ...self::LINKEDIN], true);
    }

    public static function structured(string $field): bool
    {
        return self::handles($field) && ! in_array($field, ['advantage_audience', 'audience_expansion', 'offsite_delivery', 'roas_floor', 'conversion_event'], true);
    }

    public static function current(CampaignPlatformEntity $entity, string $field): mixed
    {
        $value = data_get($entity->settings, self::path($field));
        if ($field === 'roas_floor') {
            return is_numeric($value) ? (float) $value / 10000 : null;
        }

        return self::normalize($field, $value);
    }

    public static function path(string $field): string
    {
        return match (true) {
            $field === 'advantage_audience' => 'targeting.targeting_automation.advantage_audience',
            in_array($field, self::META_TARGETING, true) => 'targeting.'.$field,
            $field === 'roas_floor' => 'bid_constraints.roas_average_floor',
            $field === 'conversion_event' => 'promoted_object.custom_event_type',
            $field === 'targeting_criteria' => 'targetingCriteria',
            $field === 'audience_expansion' => 'audienceExpansionEnabled',
            $field === 'offsite_delivery' => 'offsiteDeliveryEnabled',
            $field === 'frequency_optimization' => 'optimizationPreference.frequencyOptimizationPreference',
            default => $field,
        };
    }

    public static function normalize(string $field, mixed $value): mixed
    {
        if (in_array($field, ['conversion_rules', 'conversion_goals', 'network_settings', 'geo_target_type', 'keywords'], true) && $value === null) {
            return null;
        }
        if (in_array($field, ['advantage_audience', 'audience_expansion', 'offsite_delivery'], true)) {
            return (int) $value;
        }

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

        $decoded = self::structured($field) ? self::decode($value) : $value;
        if ($field === 'network_settings' && is_array($decoded)) {
            $decoded = array_map(fn (mixed $flag): bool => (bool) $flag, $decoded);
        }
        if ($field === 'keywords' && is_array($decoded)) {
            $decoded = array_map(fn (array $keyword): array => [...$keyword, 'text' => mb_strtolower(trim($keyword['text'])), 'negative' => (bool) $keyword['negative']], $decoded);
        }
        if ($field === 'frequency_optimization' && is_array($decoded)
            && is_numeric($decoded['frequency'] ?? null) && is_numeric($decoded['timeSpan']['duration'] ?? null)) {
            $decoded['frequency'] = (int) $decoded['frequency'];
            $decoded['timeSpan']['duration'] = (int) $decoded['timeSpan']['duration'];
        }
        if ($field === 'locales' && is_array($decoded)) {
            $decoded = array_map('intval', $decoded);
        }
        if ($field === 'adset_schedule' && is_array($decoded)) {
            $decoded = array_map(fn (array $row): array => [
                ...$row,
                'days' => array_map('intval', $row['days'] ?? []),
                'timezone_type' => $row['timezone_type'] ?? 'USER',
            ], $decoded);
        }
        if ($field === 'audience_criteria' && is_array($decoded)) {
            $decoded = array_map(fn (array $row): array => [...$row, 'negative' => (bool) ($row['negative'] ?? false)], $decoded);
        }
        if ($field === 'budget_schedules' && is_array($decoded)) {
            foreach ($decoded as &$schedule) {
                if (! is_array($schedule)) {
                    continue;
                }
                foreach (['time_start', 'time_end'] as $time) {
                    if (isset($schedule[$time]) && is_string($schedule[$time]) && ! ctype_digit($schedule[$time])) {
                        $schedule[$time] = CarbonImmutable::parse($schedule[$time])->getTimestamp();
                    }
                }
            }
            unset($schedule);
        }

        return self::structured($field) ? self::canonical($decoded ?? []) : $decoded;
    }

    private static function decode(mixed $value): mixed
    {
        return is_string($value) && trim($value) !== ''
            ? json_decode($value, true, 32, JSON_THROW_ON_ERROR)
            : ($value === '' ? [] : $value);
    }

    /** Targeting lists are sets; names returned alongside IDs are display-only. */
    private static function canonical(mixed $value): mixed
    {
        if (! is_array($value)) {
            return $value;
        }

        if (isset($value['id'])) {
            $value['id'] = (string) $value['id'];
            unset($value['name']);
        }
        if (isset($value['key']) && is_scalar($value['key'])) {
            $value['key'] = (string) $value['key'];
            unset($value['name']);
        }
        foreach (['latitude', 'longitude', 'radius'] as $number) {
            if (isset($value[$number]) && is_numeric($value[$number])) {
                $value[$number] = (float) $value[$number];
            }
        }
        foreach (['start_minute', 'end_minute', 'startHour', 'endHour', 'time_start', 'time_end', 'budget_value', 'cap', 'timeLength'] as $number) {
            if (isset($value[$number]) && is_numeric($value[$number])) {
                $value[$number] = (int) $value[$number];
            }
        }

        $value = array_map(self::canonical(...), $value);

        if (array_is_list($value)) {
            usort($value, fn (mixed $a, mixed $b): int => strcmp(json_encode($a), json_encode($b)));
        }

        return Canonical::sort($value);
    }

    public static function refusal(CampaignPlatformEntity $entity, string $field): ?string
    {
        if ($entity->platform === 'meta') {
            return match (true) {
                in_array($field, self::META_TARGETING, true) && ! is_array(data_get($entity->settings, 'targeting')) => 'Meta did not report this ad set\'s targeting.',
                $field === 'adset_schedule' && (float) data_get($entity->settings, 'lifetime_budget', 0) <= 0 => 'Dayparting needs an ad set lifetime budget. Daily and lifetime budgets cannot be switched after launch.',
                $field === 'conversion_event' && blank(data_get($entity->settings, 'promoted_object.pixel_id')) => 'A website conversion event needs the pixel already attached to this ad set. Its pixel, app and destination stay locked.',
                $field === 'roas_floor' && strtoupper((string) data_get($entity->settings, 'optimization_goal')) !== 'VALUE' => 'A ROAS goal needs value optimization.',
                $field === 'budget_schedules' && ! is_array(data_get($entity->settings, 'budget_schedules')) => 'Meta budget schedules have not been read completely yet.',
                $field === 'budget_schedules' && (float) data_get($entity->settings, 'daily_budget', 0) <= 0 => 'Budget boosts need an ad set daily budget. Campaign-held and lifetime budgets are not switched here.',
                default => null,
            };
        }

        if ($entity->platform === 'google') {
            if ($field === 'conversion_goals') {
                return ! is_array(data_get($entity->settings, 'conversion_goals'))
                    ? 'Google conversion goals could not be read. '.(string) data_get($entity->settings, 'conversion_goals_error')
                    : null;
            }
            if (in_array($field, ['network_settings', 'geo_target_type'], true)) {
                return ! in_array(data_get($entity->settings, 'channel_type'), ['SEARCH', 'DISPLAY'], true)
                    ? 'These controls apply to Search and Display campaigns.'
                    : (! is_array(data_get($entity->settings, $field)) ? 'Google did not report this native campaign setting.' : null);
            }
            if ($field === 'keywords') {
                return data_get($entity->settings, 'type') !== 'SEARCH_STANDARD' || ! is_array(data_get($entity->settings, 'keywords'))
                    ? 'Complete keywords can be edited on standard Search ad groups only.'
                    : null;
            }
            if ($field === 'frequency_caps') {
                return in_array(data_get($entity->settings, 'channel_type'), ['DISPLAY', 'VIDEO'], true)
                    ? null
                    : 'Google frequency caps apply to Display and Video campaigns, not this campaign type.';
            }

            if ($field === 'audience_criteria') {
                return ! is_array(data_get($entity->settings, 'manager_audience_criteria'))
                    ? 'Google ad group audiences have not been read completely yet.'
                    : null;
            }

            return ! is_array(data_get($entity->settings, 'manager_criteria'))
                ? 'Google targeting has not been read completely yet. Refresh the campaign first.'
                : (! in_array(data_get($entity->settings, 'channel_type'), ['SEARCH', 'DISPLAY'], true)
                    ? 'These targeting controls apply to Search and Display campaigns; other campaign types use different targeting APIs.'
                    : null);
        }

        if ($field === 'conversion_rules') {
            return ! is_array(data_get($entity->settings, 'conversion_rules'))
                ? 'LinkedIn conversion associations could not be read. '.(string) data_get($entity->settings, 'conversion_rules_error')
                : null;
        }
        if ($field === 'frequency_optimization') {
            if (array_diff(array_keys((array) data_get($entity->settings, 'optimizationPreference', [])), ['frequencyOptimizationPreference']) !== []) {
                return 'LinkedIn returned a different optimization preference. It cannot safely be replaced with a frequency cap.';
            }

            return data_get($entity->settings, 'objectiveType') !== 'BRAND_AWARENESS'
                ? 'LinkedIn frequency optimization applies only to Brand Awareness campaigns. Availability on non-CTV campaigns depends on LinkedIn rollout.'
                : null;
        }
        if ($field === 'offsite_delivery') {
            return ! is_bool(data_get($entity->settings, 'offsiteDeliveryEnabled'))
                ? 'LinkedIn did not report this campaign\'s Audience Network setting.'
                : null;
        }

        return ! is_array(data_get($entity->settings, 'targetingCriteria'))
            ? 'LinkedIn did not report this campaign\'s targeting criteria.'
            : null;
    }

    /** @param array<string, mixed> $proposed */
    public static function rule(CampaignPlatformEntity $entity, string $field, array $proposed): Closure
    {
        return function (string $attribute, mixed $value, Closure $fail) use ($entity, $field, $proposed): void {
            try {
                $decoded = self::structured($field) ? self::decode($value) : $value;
                $problem = self::problem($entity, $field, $decoded, $proposed);
            } catch (JsonException) {
                $fail('Enter valid JSON, with quoted keys and no trailing commas.');

                return;
            }

            if ($problem) {
                $fail($problem);
            }
        };
    }

    /** @param array<string, mixed> $proposed */
    private static function problem(CampaignPlatformEntity $entity, string $field, mixed $value, array $proposed): ?string
    {
        if ($field === 'conversion_rules' && count($proposed) > 1) {
            return 'Review conversion-rule associations separately from other campaign changes.';
        }
        if ($field === 'conversion_goals' && count($proposed) > 1) {
            return 'Review Google conversion goals separately from other campaign changes.';
        }
        if (self::structured($field) && ! is_array($value)) {
            return 'Enter a JSON array or object, not a scalar or null.';
        }
        if ($field === 'offsite_delivery' && ! (bool) $value && data_get($entity->settings, 'connectedTelevisionOnly') === true) {
            return 'Connected TV campaigns require LinkedIn Audience Network delivery.';
        }

        $rules = match ($field) {
            'conversion_goals' => [
                'value' => ['array:level,goals,custom_goal'],
                'value.level' => ['required', 'in:CUSTOMER,CAMPAIGN'],
                'value.goals' => ['sometimes', 'array', 'list', 'max:100'],
                'value.goals.*' => ['array:category,origin'],
                'value.goals.*.category' => ['required', 'string', 'regex:/^[A-Z_]+$/D'],
                'value.goals.*.origin' => ['required', 'string', 'regex:/^[A-Z_]+$/D'],
                'value.custom_goal' => ['sometimes', 'string', 'regex:/^customers\/[0-9]+\/customConversionGoals\/[0-9]+$/D'],
            ],
            'network_settings' => [
                'value' => ['array:targetGoogleSearch,targetSearchNetwork,targetContentNetwork,targetPartnerSearchNetwork'],
                'value.targetGoogleSearch' => ['sometimes', 'boolean'],
                'value.targetSearchNetwork' => ['sometimes', 'boolean'],
                'value.targetContentNetwork' => ['sometimes', 'boolean'],
                'value.targetPartnerSearchNetwork' => ['sometimes', 'boolean'],
            ],
            'geo_target_type' => [
                'value' => ['array:positiveGeoTargetType,negativeGeoTargetType'],
                'value.positiveGeoTargetType' => ['required', 'in:PRESENCE,PRESENCE_OR_INTEREST,SEARCH_INTEREST'],
                'value.negativeGeoTargetType' => ['required', 'in:PRESENCE,PRESENCE_OR_INTEREST'],
            ],
            'keywords' => [
                'value' => ['array', 'list', 'max:1000'],
                'value.*' => ['array:text,match_type,negative'],
                'value.*.text' => ['required', 'string', 'max:80'],
                'value.*.match_type' => ['required', 'in:EXACT,PHRASE,BROAD'],
                'value.*.negative' => ['required', 'boolean'],
            ],
            'conversion_rules' => [
                'value' => ['array', 'list', 'max:100'],
                'value.*' => ['string', 'distinct', 'regex:/^urn:lla:llaPartnerConversion:[0-9]+$/D'],
            ],
            'roas_floor' => ['value' => ['nullable', 'numeric', 'gt:0', 'max:1000', 'decimal:0,4']],
            'advantage_audience', 'audience_expansion', 'offsite_delivery' => ['value' => ['required', 'integer', 'in:0,1']],
            'frequency_optimization' => $value === [] ? ['value' => ['array', 'size:0']] : [
                'value' => ['array:optimizationType,frequency,timeSpan'],
                'value.optimizationType' => ['required', 'in:MAX_FREQUENCY'],
                'value.frequency' => ['required', 'integer', 'between:3,30'],
                'value.timeSpan' => ['required', 'array:duration,unit'],
                'value.timeSpan.duration' => ['required', 'integer', 'in:7'],
                'value.timeSpan.unit' => ['required', 'in:DAY'],
            ],
            'conversion_event' => ['value' => ['required', 'string', Rule::in(array_keys(EditCapabilities::options($entity, 'conversion_event')))]],
            'locales' => ['value' => ['array', 'list', 'max:100'], 'value.*' => ['integer', 'min:1', 'distinct']],
            'custom_audiences', 'excluded_custom_audiences' => [
                'value' => ['array', 'list', 'max:100'], 'value.*' => ['array:id,name'],
                'value.*.id' => ['required', 'string', 'regex:/^[0-9]+$/D'],
                'value.*.name' => ['sometimes', 'string', 'max:250'],
            ],
            'pacing_type' => ['value' => ['array', 'list', 'min:1', 'max:2'], 'value.*' => ['string', 'distinct', 'in:standard,no_pacing,day_parting']],
            'device_platforms' => ['value' => ['array', 'list', 'max:2'], 'value.*' => ['string', 'distinct', 'in:mobile,desktop']],
            'targeting_relaxation_types' => ['value' => ['array:custom_audience,lookalike'], 'value.*' => ['integer', 'in:0,1']],
            'geo_locations', 'excluded_geo_locations' => self::geoRules($field === 'geo_locations'),
            'adset_schedule' => [
                'value' => ['array', 'list', 'max:168'], 'value.*' => ['array:days,start_minute,end_minute,timezone_type'],
                'value.*.days' => ['required', 'array', 'list', 'min:1', 'max:7'],
                'value.*.days.*' => ['integer', 'between:0,6', 'distinct'],
                'value.*.start_minute' => ['required', 'integer', 'between:0,1439', 'multiple_of:15'],
                'value.*.end_minute' => ['required', 'integer', 'between:1,1440', 'multiple_of:15'],
                'value.*.timezone_type' => ['sometimes', 'string', 'in:USER,ADVERTISER'],
            ],
            'location_targets', 'excluded_locations' => ['value' => ['array', 'list', 'max:500'], 'value.*' => ['string', 'distinct', 'regex:/^geoTargetConstants\/[0-9]+$/D']],
            'language_targets' => ['value' => ['array', 'list', 'max:100'], 'value.*' => ['string', 'distinct', 'regex:/^languageConstants\/[0-9]+$/D']],
            'device_exclusions' => ['value' => ['array', 'list', 'max:4'], 'value.*' => ['string', 'distinct', 'in:MOBILE,DESKTOP,TABLET,CONNECTED_TV']],
            'delivery_schedule' => [
                'value' => ['array', 'list', 'max:42'], 'value.*' => ['array:dayOfWeek,startHour,startMinute,endHour,endMinute'],
                'value.*.dayOfWeek' => ['required', 'in:MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY'],
                'value.*.startHour' => ['required', 'integer', 'between:0,23'],
                'value.*.endHour' => ['required', 'integer', 'between:0,24'],
                'value.*.startMinute' => ['required', 'in:ZERO,FIFTEEN,THIRTY,FORTY_FIVE'],
                'value.*.endMinute' => ['required', 'in:ZERO,FIFTEEN,THIRTY,FORTY_FIVE'],
            ],
            'targeting_criteria' => [
                'value' => ['required', 'array:include,exclude'],
                'value.include' => ['required', 'array:and'],
                'value.include.and' => ['required', 'array', 'list', 'min:1', 'max:20'],
                'value.include.and.*' => ['array:or'],
                'value.include.and.*.or' => ['required', 'array', 'min:1'],
                'value.exclude' => ['sometimes', 'array:or'],
                'value.exclude.or' => ['sometimes', 'array', 'min:1'],
            ],
            'flexible_spec' => ['value' => ['array', 'list', 'max:20'], 'value.*' => ['array:'.implode(',', self::FACETS), 'min:1']],
            'audience_criteria' => [
                'value' => ['array', 'list', 'max:500'],
                'value.*' => ['array:type,negative,ageRange,gender,userList,userInterest,customAudience,combinedAudience'],
                'value.*.type' => ['required', 'in:AGE_RANGE,GENDER,USER_LIST,USER_INTEREST,CUSTOM_AUDIENCE,COMBINED_AUDIENCE'],
                'value.*.negative' => ['sometimes', 'boolean'],
            ],
            'frequency_caps' => [
                'value' => ['array', 'list', 'max:20'],
                'value.*' => ['array:key,cap'],
                'value.*.cap' => ['required', 'integer', 'between:1,1000'],
                'value.*.key' => ['required', 'array:level,eventType,timeUnit,timeLength'],
                'value.*.key.level' => ['required', 'in:CAMPAIGN,AD_GROUP,AD_GROUP_AD'],
                'value.*.key.eventType' => ['required', 'in:IMPRESSION,VIDEO_VIEW'],
                'value.*.key.timeUnit' => ['required', 'in:DAY,WEEK,MONTH'],
                'value.*.key.timeLength' => ['required', 'integer', 'between:1,30'],
            ],
            'budget_schedules' => [
                'value' => ['array', 'list', 'max:100'],
                'value.*' => ['array:id,budget_value,budget_value_type,time_start,time_end'],
                'value.*.id' => ['sometimes', 'string', 'regex:/^[0-9]+$/D', 'distinct'],
                'value.*.budget_value' => ['required', 'integer', 'min:1'],
                'value.*.budget_value_type' => ['required', 'in:ABSOLUTE,MULTIPLIER'],
                'value.*.time_start' => ['required', 'integer', 'min:1', 'multiple_of:900'],
                'value.*.time_end' => ['required', 'integer', 'min:1', 'multiple_of:900'],
            ],
            default => ['value' => ['array', 'list', 'max:100'], 'value.*' => ['string', 'max:100', 'distinct', 'regex:/^[a-zA-Z0-9 _.,+():\/-]+$/D']],
        };
        $check = Validator::make(['value' => $value], $rules);

        if ($check->fails()) {
            return $check->errors()->first();
        }
        if ($field === 'conversion_goals') {
            if ($value['level'] === 'CAMPAIGN' && ! array_key_exists('goals', $value)) {
                return 'Supply the complete campaign goal selection, including an empty goals list when only a custom goal is used.';
            }
            if ($value['level'] === 'CUSTOMER' && array_diff(array_keys($value), ['level']) !== []) {
                return 'Account-default goals must not include campaign overrides.';
            }
            $known = (array) data_get($entity->settings, 'manager_conversion_goals', []);
            $keys = [];
            foreach ($value['goals'] ?? [] as $goal) {
                $key = $goal['category'].'~'.$goal['origin'];
                if (isset($keys[$key]) || ! in_array($key, $known, true)) {
                    return 'Select distinct category/origin pairs reported for this Google campaign.';
                }
                $keys[$key] = true;
            }
            if (isset($value['custom_goal']) && ! str_starts_with($value['custom_goal'], 'customers/'.preg_replace('/\D/', '', (string) $entity->campaign->ad_account_id).'/')) {
                return 'Choose a custom conversion goal belonging to this account.';
            }
        }
        if ($field === 'network_settings') {
            if ($value === [] || array_diff(array_keys($value), array_keys((array) data_get($entity->settings, 'network_settings'))) !== []) {
                return 'Change only network settings Google reported for this campaign.';
            }
            if (data_get($entity->settings, 'channel_type') === 'SEARCH'
                && (($value['targetGoogleSearch'] ?? data_get($entity->settings, 'network_settings.targetGoogleSearch')) !== true)) {
                return 'Search campaigns must retain Google Search delivery.';
            }
        }
        if ($field === 'keywords') {
            $keys = [];
            foreach ($value as $keyword) {
                $key = mb_strtolower(trim($keyword['text'])).'|'.$keyword['match_type'].'|'.(int) $keyword['negative'];
                if (isset($keys[$key])) {
                    return 'Choose distinct keyword text, match type and exclusion combinations.';
                }
                $keys[$key] = true;
            }
        }

        if ($field === 'frequency_caps') {
            $keys = [];
            foreach ($value as $cap) {
                $key = json_encode(self::canonical($cap['key']));
                if (isset($keys[$key])) {
                    return 'Only one frequency cap is allowed for each level, event and time window.';
                }
                if (data_get($entity->settings, 'channel_type') === 'DISPLAY' && $cap['key']['eventType'] !== 'IMPRESSION') {
                    return 'Display campaigns accept impression frequency caps only.';
                }
                $keys[$key] = true;
            }
        }

        if ($field === 'budget_schedules') {
            $known = array_column((array) data_get($entity->settings, 'budget_schedules'), 'id');
            $windows = [];
            foreach ($value as $schedule) {
                if (isset($schedule['id']) && ! in_array($schedule['id'], $known, true)) {
                    return 'A budget schedule ID must belong to this ad set.';
                }
                if ($schedule['time_start'] < now()->addHour()->getTimestamp() || $schedule['time_end'] - $schedule['time_start'] < 10800) {
                    return 'Budget boosts must start at least an hour ahead and last at least three hours.';
                }
                foreach ($windows as [$start, $end]) {
                    if ($schedule['time_start'] < $end && $schedule['time_end'] > $start) {
                        return 'Budget boosts must not overlap.';
                    }
                }
                $windows[] = [$schedule['time_start'], $schedule['time_end']];
            }
            if ($problem = self::budgetLimitProblem($entity, $value, (float) ($proposed['daily_budget'] ?? data_get($entity->settings, 'daily_budget', 0)))) {
                return $problem;
            }
        }

        if ($field === 'flexible_spec') {
            foreach ($value as $group) {
                foreach ($group as $facet => $items) {
                    if (! is_array($items) || ! array_is_list($items) || $items === []) {
                        return 'Each audience facet needs a nonempty list of IDs.';
                    }

                    foreach ($items as $item) {
                        if (in_array($facet, ['education_statuses', 'relationship_statuses'], true)) {
                            if (! is_int($item) || $item < 1 || $item > 13) {
                                return 'Education and relationship statuses must use Meta numeric status codes.';
                            }

                            continue;
                        }

                        if (! is_array($item) || array_diff(array_keys($item), ['id', 'name']) !== []
                            || ! preg_match('/^[0-9]+$/D', (string) ($item['id'] ?? ''))) {
                            return 'Each detailed audience must be an object with a numeric id and optional name.';
                        }
                    }
                }
            }
        }

        if ($field === 'audience_criteria') {
            $account = preg_replace('/\D/', '', (string) $entity->campaign->ad_account_id);
            foreach ($value as $criterion) {
                [$key, $leaf, $pattern] = match ($criterion['type']) {
                    'AGE_RANGE' => ['ageRange', 'type', '/^AGE_RANGE_(18_24|25_34|35_44|45_54|55_64|65_UP|UNDETERMINED)$/D'],
                    'GENDER' => ['gender', 'type', '/^(MALE|FEMALE|UNDETERMINED)$/D'],
                    'USER_LIST' => ['userList', 'userList', '/^customers\/'.$account.'\/userLists\/[0-9]+$/D'],
                    'USER_INTEREST' => ['userInterest', 'userInterestCategory', '/^userInterests\/[0-9]+$/D'],
                    'CUSTOM_AUDIENCE' => ['customAudience', 'customAudience', '/^customers\/'.$account.'\/customAudiences\/[0-9]+$/D'],
                    'COMBINED_AUDIENCE' => ['combinedAudience', 'combinedAudience', '/^customers\/'.$account.'\/combinedAudiences\/[0-9]+$/D'],
                };
                if (array_diff(array_keys($criterion), ['type', 'negative', $key]) !== []
                    || ! is_array($criterion[$key] ?? null) || array_keys($criterion[$key]) !== [$leaf]
                    || ! is_string($criterion[$key][$leaf]) || ! preg_match($pattern, $criterion[$key][$leaf])) {
                    return 'Use the native criterion block for its type and audience resources from this Google account.';
                }
            }
        }

        if ($field === 'targeting_criteria') {
            $location = false;
            $groups = [...$value['include']['and'], ...(isset($value['exclude']) ? [$value['exclude']] : [])];
            foreach ($groups as $index => $group) {
                foreach ($group['or'] as $facet => $urns) {
                    if (! preg_match('/^urn:li:adTargetingFacet:[a-zA-Z]+$/D', $facet)
                        || ! is_array($urns) || ! array_is_list($urns) || $urns === [] || count($urns) > 500) {
                        return 'Each LinkedIn facet needs a nonempty list of targeting URNs.';
                    }
                    foreach ($urns as $urn) {
                        if (! is_string($urn) || ! preg_match('/^urn:li:[a-zA-Z]+:[a-zA-Z0-9_-]+$/D', $urn)) {
                            return 'Use LinkedIn targeting URNs, not names or IDs from another platform.';
                        }
                    }
                    $location = $location || ($index < count($value['include']['and']) && in_array($facet, ['urn:li:adTargetingFacet:locations', 'urn:li:adTargetingFacet:locationsV2'], true));
                }
            }

            return $location ? null : 'LinkedIn targeting must include a location facet.';
        }

        if ($field === 'conversion_event' && strtoupper((string) ($proposed['optimization_goal'] ?? data_get($entity->settings, 'optimization_goal'))) === 'VALUE' && $value !== 'PURCHASE') {
            return 'Value optimization needs the Purchase conversion event.';
        }

        if ($field === 'roas_floor' && ($proposed['bid_strategy'] ?? EditCapabilities::current($entity, 'bid_strategy')) !== 'LOWEST_COST_WITH_MIN_ROAS') {
            return 'Select the ROAS goal bid strategy before setting a minimum ROAS.';
        }

        if ($field === 'geo_locations' && array_key_exists('countries', $proposed)) {
            $countries = EditCapabilities::normalize($entity, 'countries', $proposed['countries']);
            if ($countries !== EditCapabilities::current($entity, 'countries') && $countries !== (self::normalize('geo_locations', $value)['countries'] ?? [])) {
                return 'Change countries or advanced included locations, not conflicting selections in both.';
            }
        }

        if ($field === 'pacing_type') {
            if (in_array('no_pacing', $value, true) && ($proposed['bid_strategy'] ?? EditCapabilities::current($entity, 'bid_strategy')) !== 'LOWEST_COST_WITH_BID_CAP') {
                return 'Accelerated pacing needs a bid cap.';
            }

            if (in_array('standard', $value, true) && in_array('no_pacing', $value, true)) {
                return 'Choose standard or accelerated pacing, not both.';
            }
            $schedule = array_key_exists('adset_schedule', $proposed) ? self::decode($proposed['adset_schedule']) : self::current($entity, 'adset_schedule');
            if (in_array('day_parting', $value, true) && ((float) data_get($entity->settings, 'lifetime_budget', 0) <= 0 || ! is_array($schedule) || $schedule === [])) {
                return 'Dayparting needs a lifetime budget and at least one delivery window.';
            }
        }

        if ($field === 'adset_schedule' || $field === 'delivery_schedule') {
            if ($field === 'adset_schedule' && $value !== [] && array_key_exists('pacing_type', $proposed)
                && ! in_array('day_parting', (array) self::decode($proposed['pacing_type']), true)) {
                return 'Delivery windows require day_parting in delivery pacing. Leave pacing unchanged to add it automatically.';
            }
            $windows = [];
            $minutes = ['ZERO' => 0, 'FIFTEEN' => 15, 'THIRTY' => 30, 'FORTY_FIVE' => 45];
            foreach ($value as $window) {
                $start = $field === 'adset_schedule' ? $window['start_minute'] : $window['startHour'] * 60 + $minutes[$window['startMinute']];
                $end = $field === 'adset_schedule' ? $window['end_minute'] : $window['endHour'] * 60 + $minutes[$window['endMinute']];
                if ($start >= $end || $end > 1440) {
                    return 'Every delivery window must end after it starts, no later than midnight.';
                }
                foreach ($window['days'] ?? [$window['dayOfWeek']] as $day) {
                    foreach ($windows[$day] ?? [] as [$from, $to]) {
                        if ($start < $to && $end > $from) {
                            return 'Delivery windows on the same day must not overlap.';
                        }
                    }
                    $windows[$day][] = [$start, $end];
                }
            }
        }

        if (str_ends_with($field, '_positions') && $value !== []) {
            $platform = substr($field, 0, -strlen('_positions'));
            $platforms = $proposed['publisher_platforms'] ?? EditCapabilities::current($entity, 'publisher_platforms');
            if (! is_array($platforms) || ! in_array($platform, $platforms, true)) {
                return 'Select this publisher platform before choosing its positions.';
            }
        }

        if ($field === 'geo_locations' && array_diff(array_keys($value), ['location_types']) === []) {
            return 'Choose at least one included country, region, city, zip or custom location.';
        }

        return null;
    }

    /** @param list<array<string, mixed>> $schedules */
    public static function budgetLimitProblem(CampaignPlatformEntity $entity, array $schedules, float $daily): ?string
    {
        $ceiling = BudgetCeiling::for($entity->campaign);
        if ($ceiling === null) {
            return BudgetCeiling::missingReason($entity->campaign);
        }
        foreach ($schedules as $schedule) {
            if ((int) ($schedule['time_end'] ?? 0) <= now()->getTimestamp()) {
                continue;
            }
            $boosted = $schedule['budget_value_type'] === 'ABSOLUTE'
                ? $daily + CurrencyMinorUnits::toMajor($schedule['budget_value'], EditCapabilities::currency($entity))
                : $daily * (1 + $schedule['budget_value'] / 100);
            if ($boosted > $ceiling) {
                return sprintf('A scheduled budget boost exceeds the daily budget ceiling of %s.', $ceiling);
            }
        }

        return null;
    }

    /** @return array<string, list<string>> */
    private static function geoRules(bool $required): array
    {
        return [
            'value' => [$required ? 'required' : 'present', 'array:countries,country_groups,regions,cities,zips,custom_locations,geo_markets,location_types'],
            'value.countries' => ['sometimes', 'array', 'list', 'min:1', 'max:250'],
            'value.countries.*' => ['string', 'regex:/^[A-Z]{2}$/D', 'distinct'],
            'value.country_groups' => ['sometimes', 'array', 'list', 'min:1'],
            'value.country_groups.*' => ['string', 'regex:/^[a-zA-Z0-9_]+$/D', 'max:30'],
            'value.location_types' => ['sometimes', 'array', 'list', 'min:1', 'max:4'],
            'value.location_types.*' => ['in:home,recent,travel_in,frequently_in', 'distinct'],
            'value.regions' => ['sometimes', 'array', 'list', 'min:1', 'max:500'],
            'value.regions.*' => ['array:key,name'],
            'value.regions.*.key' => ['required', 'string', 'regex:/^[0-9]+$/D'],
            'value.cities' => ['sometimes', 'array', 'list', 'min:1', 'max:500'],
            'value.cities.*' => ['array:key,name,radius,distance_unit'],
            'value.cities.*.key' => ['required', 'string', 'regex:/^[0-9]+$/D'],
            'value.cities.*.radius' => ['sometimes', 'numeric', 'between:1,80'],
            'value.cities.*.distance_unit' => ['required_with:value.cities.*.radius', 'in:mile,kilometer'],
            'value.zips' => ['sometimes', 'array', 'list', 'min:1', 'max:500'],
            'value.zips.*' => ['array:key,name'],
            'value.zips.*.key' => ['required', 'string', 'regex:/^[a-zA-Z0-9: _-]+$/D', 'max:50'],
            'value.geo_markets' => ['sometimes', 'array', 'list', 'min:1', 'max:500'],
            'value.geo_markets.*' => ['array:key,name'],
            'value.geo_markets.*.key' => ['required', 'string', 'regex:/^[0-9]+$/D'],
            'value.custom_locations' => ['sometimes', 'array', 'list', 'min:1', 'max:100'],
            'value.custom_locations.*' => ['array:latitude,longitude,radius,distance_unit,address'],
            'value.custom_locations.*.latitude' => ['required', 'numeric', 'between:-90,90'],
            'value.custom_locations.*.longitude' => ['required', 'numeric', 'between:-180,180'],
            'value.custom_locations.*.radius' => ['required', 'numeric', 'between:1,80'],
            'value.custom_locations.*.distance_unit' => ['required', 'in:mile,kilometer'],
        ];
    }

    public static function hint(string $field): string
    {
        return match ($field) {
            'geo_locations' => 'JSON object, e.g. {"countries":["US"],"location_types":["home","recent"]}. Replaces included geography only.',
            'excluded_geo_locations' => 'JSON object, e.g. {"countries":["CA"]}. Use {} to remove geographic exclusions.',
            'custom_audiences', 'excluded_custom_audiences' => 'JSON list of audience IDs, e.g. [{"id":"123456789"}]. Lookalikes use their saved audience IDs too. [] removes this selection.',
            'flexible_spec' => 'JSON AND-groups containing OR facets, e.g. [{"interests":[{"id":"6003096812932"}]}]. [] removes detailed targeting.',
            'targeting_criteria' => 'LinkedIn native include.and / exclude.or JSON, using urn:li:adTargetingFacet:* keys and targeting URNs. Include a locations facet.',
            'conversion_rules' => 'Load enabled conversion rules from this account, then select those to associate. Deselecting all removes the campaign associations, not the conversion rules. Review this change separately.',
            'conversion_goals' => 'Use {"level":"CUSTOMER"} for account defaults, or {"level":"CAMPAIGN","goals":[{"category":"PURCHASE","origin":"WEBSITE"}]}. Goals select category AND origin, not individual actions. Optional custom_goal must be an existing enabled customers/ID/customConversionGoals/ID. Review separately; changing goals stops inheriting future account changes.',
            'network_settings' => 'Native network booleans, e.g. {"targetGoogleSearch":true,"targetSearchNetwork":false}. Only reported fields can change; omitted networks remain unchanged.',
            'geo_target_type' => 'Native geographic intent, e.g. {"positiveGeoTargetType":"PRESENCE","negativeGeoTargetType":"PRESENCE"}. PRESENCE_OR_INTEREST includes interest in the location; locations themselves remain unchanged.',
            'keywords' => 'Search keywords, e.g. [{"text":"car insurance","match_type":"PHRASE","negative":false}]. [] removes all keywords. Unchanged criteria retain their IDs; match-type changes remove and recreate the criterion.',
            'frequency_optimization' => 'Brand Awareness only. {"optimizationType":"MAX_FREQUENCY","frequency":3,"timeSpan":{"duration":7,"unit":"DAY"}}. Frequency must be 3-30 over 7 days. [] restores automatic frequency optimization. LinkedIn may restrict this feature to eligible accounts/formats.',
            'offsite_delivery' => 'Allow delivery on LinkedIn Audience Network. Native offsite exclusions are preserved. Connected TV campaigns require this to remain on.',
            'roas_floor' => 'Minimum return on ad spend: 4 means 400%. Used only by the ROAS goal strategy with value optimization.',
            'conversion_event' => 'Changes the website conversion event only. The existing pixel, app, page and destination are preserved.',
            'pacing_type' => 'JSON list: ["standard"], ["no_pacing"] (bid cap only), or add "day_parting" with a lifetime budget and delivery windows.',
            'adset_schedule' => 'JSON list, e.g. [{"days":[1,2,3,4,5],"start_minute":540,"end_minute":1020,"timezone_type":"ADVERTISER"}]. Days are 0 (Sunday) to 6. Times use 15-minute steps.',
            'delivery_schedule' => 'JSON list, e.g. [{"dayOfWeek":"MONDAY","startHour":9,"startMinute":"ZERO","endHour":17,"endMinute":"ZERO"}]. [] runs all day, every day, in the account time zone.',
            'location_targets', 'excluded_locations' => 'JSON list of geoTargetConstants/ID resources, e.g. ["geoTargetConstants/2840"]. Included and excluded places are changed separately.',
            'language_targets' => 'JSON list of languageConstants/ID resources, e.g. ["languageConstants/1000"]. [] allows all languages.',
            'device_exclusions' => 'JSON list of devices to exclude: MOBILE, DESKTOP, TABLET, CONNECTED_TV. [] removes these exclusions.',
            'advantage_audience', 'audience_expansion' => '0 = off, 1 = on. Expansion allows the platform to reach beyond audience suggestions.',
            'targeting_relaxation_types' => 'JSON object, e.g. {"custom_audience":0,"lookalike":1}. 0 disables and 1 enables expansion.',
            'locales' => 'JSON list of Meta numeric locale IDs, e.g. [6]. [] allows all languages.',
            'budget_schedules' => 'JSON list of future budget boosts: budget_value (minor currency units for ABSOLUTE, percentage increase for MULTIPLIER), budget_value_type, time_start/time_end (Unix seconds on 15-minute boundaries, divisible by 900), optional existing id. Start at least an hour ahead; duration at least three hours. [] removes schedules.',
            'audience_criteria' => 'Google demographic and audience criteria, e.g. [{"type":"GENDER","gender":{"type":"FEMALE"},"negative":false}]. Supports AGE_RANGE, USER_LIST, USER_INTEREST, CUSTOM_AUDIENCE and COMBINED_AUDIENCE. Preserves targeting vs observation mode. Keywords are not changed.',
            'frequency_caps' => 'Google Display/Video frequency caps, e.g. [{"key":{"level":"CAMPAIGN","eventType":"IMPRESSION","timeUnit":"DAY","timeLength":1},"cap":3}]. [] removes caps.',
            default => 'JSON list of platform-native values. [] clears this selection. Other targeting settings are preserved.',
        };
    }
}
