<?php

namespace App\Campaigns\Targeting;

use App\Models\Brief;
use App\Models\Campaign;
use App\Models\CampaignAdSet;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\TargetingSet;
use Illuminate\Support\Facades\DB;
use RuntimeException;

class TargetingSelections
{
    /** @return list<string> */
    public function countries(Campaign $campaign): array
    {
        $set = $campaign->targetingSet()->first();

        if ($set === null) {
            return array_values((array) ($campaign->locations['countries'] ?? []));
        }

        if ($set->mode === 'clear') {
            return [];
        }

        if ($set->mode === 'inherit') {
            return $this->briefCountries($campaign->brief);
        }

        return $set->locations()
            ->where('kind', 'country')
            ->where('operation', 'include')
            ->orderBy('id')
            ->pluck('country_code')
            ->filter()
            ->values()
            ->all();
    }

    /** @param list<string> $codes */
    public function saveCampaignCountries(Campaign $campaign, array $codes, ?int $expectedRevision = null): TargetingSet
    {
        if ($campaign->isPublished()) {
            throw new RuntimeException('Location targeting cannot be changed on a published campaign. Create a new campaign for a different audience.');
        }

        return DB::transaction(function () use ($campaign, $codes, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== null && $expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $set ??= TargetingSet::query()->create([
                'campaign_id' => $campaign->getKey(),
                'platform' => $campaign->platform,
                'mode' => 'override',
                'revision' => 0,
                'schema_version' => 1,
            ]);

            $previousCountries = $this->countries($campaign);

            // Saving the same countries again is not a change, and bumping the
            // revision invalidated the geography options already on screen.
            if (! $set->wasRecentlyCreated && $set->mode === 'override' && $previousCountries === array_values($codes)) {
                return $set;
            }

            $this->replaceCountries($set, $codes);
            $options = (array) ($set->options ?? []);
            if ($previousCountries !== array_values($codes)) {
                unset($options['geography_scope']);

                // A country means the whole country until narrower places are requested.
                $hasNarrowerPlaces = $set->locations()->whereIn('kind', ['city', 'region', 'postal', 'dma', 'radius'])
                    ->where('operation', 'include')->exists();
                if ($codes !== [] && ! $hasNarrowerPlaces && $this->sharedPlaceIntents($campaign) === []) {
                    $options['geography_scope'] = 'whole';
                }
            }
            $set->update(['mode' => 'override', 'revision' => $set->revision + 1, 'options' => $options]);
            $campaign->update(['locations' => array_replace((array) $campaign->locations, ['countries' => $codes])]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function hasChosenGeographyScope(Campaign $campaign): bool
    {
        $set = $campaign->targetingSet()->first();

        if ($set === null) {
            return false;
        }

        return ($set->options['geography_scope'] ?? null) === 'whole'
            || $set->locations()->whereIn('kind', ['city', 'region', 'postal', 'dma', 'radius'])
                ->where('operation', 'include')->whereIn('country_code', $this->countries($campaign))->exists();
    }

    public function hasCompletedGeographyScope(Campaign $campaign): bool
    {
        $set = $campaign->targetingSet()->first();

        if ($set === null) {
            return false;
        }

        return ($set->options['place_intent_mode'] ?? null) === 'clear'
            || $set->locations()->whereIn('kind', ['city', 'region', 'postal', 'dma', 'radius'])
                ->where('operation', 'include')->whereIn('country_code', $this->countries($campaign))->exists();
    }

    public function chooseWholeCountries(Campaign $campaign, ?int $expectedRevision = null): TargetingSet
    {
        if ($campaign->isPublished() || ! in_array($campaign->platform, ['meta', 'google', 'linkedin'], true)) {
            throw new RuntimeException('Whole-country selection is available for draft campaigns only.');
        }

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

        if ($countries === []) {
            throw new RuntimeException('Choose at least one country first.');
        }

        return DB::transaction(function () use ($campaign, $countries, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== null && $expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $set ??= TargetingSet::query()->create([
                'campaign_id' => $campaign->getKey(),
                'platform' => $campaign->platform,
                'mode' => 'override',
                'revision' => 0,
                'schema_version' => 1,
            ]);

            if ($set->wasRecentlyCreated || $set->mode !== 'override') {
                $this->replaceCountries($set, $countries);
            }

            $set->locations()->whereIn('kind', ['city', 'region', 'postal', 'dma', 'radius'])
                ->where('operation', 'include')->delete();

            $options = (array) ($set->options ?? []);
            $options['geography_scope'] = 'whole';
            $options['place_intent_mode'] = 'clear';
            $options['resolved_shared_places'] = [];
            $set->update(['mode' => 'override', 'revision' => $set->revision + 1, 'options' => $options]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function addCampaignLocation(Campaign $campaign, PlatformLocation $mapping, ?int $expectedRevision = null, ?int $sharedPlaceId = null): TargetingSet
    {
        if ($campaign->isPublished()) {
            throw new RuntimeException('Location targeting cannot be changed on a published campaign. Create a new campaign for a different audience.');
        }

        $location = $mapping->location;
        $countries = $this->countries($campaign);

        if ($mapping->platform !== $campaign->platform
            || ! in_array($location->type, ['city', 'region', 'postal'], true)
            || blank($mapping->external_id)
            || $mapping->status !== 'verified'
            || $mapping->verified_at === null
            || $mapping->verified_at->lt(now()->subDays(30))
            || ! in_array($location->country_code, $countries, true)) {
            throw new RuntimeException('Choose a verified city, region or postal code within this campaign’s selected countries.');
        }

        return DB::transaction(function () use ($campaign, $mapping, $location, $countries, $expectedRevision, $sharedPlaceId): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== null && $expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $set ??= TargetingSet::query()->create([
                'campaign_id' => $campaign->getKey(),
                'platform' => $campaign->platform,
                'mode' => 'override',
                'revision' => 0,
                'schema_version' => 1,
            ]);

            if ($set->wasRecentlyCreated || $set->mode !== 'override') {
                $this->replaceCountries($set, $countries);
            }

            $options = (array) ($set->options ?? []);
            $placeMode = (string) ($options['place_intent_mode'] ?? 'inherit');

            if ($placeMode === 'clear') {
                throw new RuntimeException('This campaign targets whole countries. Choose different places before adding a city or state.');
            }

            if ($sharedPlaceId !== null && $placeMode !== 'inherit') {
                throw new RuntimeException('Switch this campaign to inherited places before resolving a shared place.');
            }

            if ($campaign->platform === 'google' && $set->locations()->where('location_id', $location->getKey())
                ->where('operation', 'exclude')->exists()) {
                throw new RuntimeException('A Google place cannot be both included and excluded. Remove its exclusion first.');
            }

            $resolvedPlaceId = $placeMode === 'inherit'
                ? $this->rememberSharedPlace($campaign, $mapping, $sharedPlaceId)
                : null;

            $set->locations()->updateOrCreate(
                ['location_id' => $location->getKey(), 'operation' => 'include'],
                [
                    'platform_location_id' => $mapping->getKey(),
                    'kind' => $location->type,
                    'display_label' => $mapping->provider_name,
                    'country_code' => $location->country_code,
                ],
            );
            if ($resolvedPlaceId !== null) {
                $resolved = (array) ($options['resolved_shared_places'] ?? []);
                $resolved[$resolvedPlaceId] = $mapping->getKey();
                $options['resolved_shared_places'] = $resolved;
            }

            $set->update([
                'mode' => 'override',
                'revision' => $set->revision + 1,
                'options' => $options,
            ]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function addGoogleLocationExclusion(Campaign $campaign, PlatformLocation $mapping, ?int $expectedRevision = null): TargetingSet
    {
        $location = $mapping->location;

        if ($campaign->isPublished() || $campaign->platform !== 'google'
            || ($campaign->campaign_type ?: 'search') !== 'search'
            || $location === null || ! in_array($location->type, ['city', 'region'], true)
            || $mapping->platform !== 'google'
            || ! preg_match('/^geoTargetConstants\/[0-9]+$/D', $mapping->external_id)
            || $mapping->status !== 'verified' || $mapping->verified_at === null
            || $mapping->verified_at->lt(now()->subDays(30))
            || ! in_array($location->country_code, $this->countries($campaign), true)) {
            throw new RuntimeException('Google Search exclusions require a fresh, verified city or region within a selected country.');
        }

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

        return DB::transaction(function () use ($campaign, $mapping, $location, $countries, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== null && $expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $set ??= TargetingSet::query()->create([
                'campaign_id' => $campaign->getKey(), 'platform' => 'google',
                'mode' => 'override', 'revision' => 0, 'schema_version' => 1,
            ]);

            if ($set->wasRecentlyCreated || $set->mode !== 'override') {
                $this->replaceCountries($set, $countries);
            }

            if ($set->locations()->where('location_id', $location->getKey())
                ->whereIn('operation', ['include', 'exclude'])->exists()) {
                throw new RuntimeException('This place is already selected or excluded on the campaign.');
            }

            $set->locations()->create([
                'location_id' => $location->getKey(), 'platform_location_id' => $mapping->getKey(),
                'operation' => 'exclude', 'kind' => $location->type,
                'display_label' => $mapping->provider_name, 'country_code' => $location->country_code,
            ]);
            $set->update(['mode' => 'override', 'revision' => $set->revision + 1]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function addGoogleDma(Campaign $campaign, PlatformLocation $mapping, ?int $expectedRevision = null): TargetingSet
    {
        $location = $mapping->location;

        if ($campaign->isPublished() || $campaign->platform !== 'google'
            || ($campaign->campaign_type ?: 'search') !== 'search'
            || $location === null || $location->type !== 'dma' || $location->country_code !== 'US'
            || ! in_array('US', $this->countries($campaign), true)
            || $mapping->platform !== 'google'
            || ! preg_match('/^geoTargetConstants\/[0-9]+$/D', $mapping->external_id)
            || ! preg_match('/^geoTargetConstants\/[0-9]+$/D', (string) $mapping->parent_external_id)
            || $mapping->status !== 'verified' || $mapping->verified_at === null
            || $mapping->verified_at->lt(now()->subDays(30))) {
            throw new RuntimeException('Google Search DMA targeting requires a fresh, verified US market with its provider parent.');
        }

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

        return DB::transaction(function () use ($campaign, $mapping, $location, $countries, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== null && $expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $set ??= TargetingSet::query()->create([
                'campaign_id' => $campaign->getKey(), 'platform' => 'google',
                'mode' => 'override', 'revision' => 0, 'schema_version' => 1,
            ]);

            if ($set->wasRecentlyCreated || $set->mode !== 'override') {
                $this->replaceCountries($set, $countries);
            }

            if ($set->locations()->where('location_id', $location->getKey())
                ->whereIn('operation', ['include', 'exclude'])->exists()) {
                throw new RuntimeException('This DMA market is already selected on the campaign.');
            }

            $set->locations()->create([
                'location_id' => $location->getKey(), 'platform_location_id' => $mapping->getKey(),
                'operation' => 'include', 'kind' => 'dma',
                'display_label' => $mapping->provider_name, 'country_code' => 'US',
            ]);
            $set->update(['mode' => 'override', 'revision' => $set->revision + 1]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function addPlatformDma(Campaign $campaign, PlatformLocation $mapping, ?int $expectedRevision = null): TargetingSet
    {
        $location = $mapping->location;
        $platform = (string) $campaign->platform;

        if ($campaign->isPublished() || ! in_array($platform, ['meta', 'linkedin'], true)
            || $location === null || $location->type !== 'dma' || $location->country_code !== 'US'
            || ! in_array('US', $this->countries($campaign), true)
            || $mapping->platform !== $platform
            || ! match ($platform) {
                'meta' => (bool) preg_match('/^COMSCORE_MARKET:[0-9]+$/D', $mapping->external_id),
                'linkedin' => (bool) preg_match('/^urn:li:geo:[0-9]+$/D', $mapping->external_id)
                    && (bool) preg_match('/^DMA® [0-9]+ - .+, United States$/uD', (string) $mapping->provider_name),
            }
            || $mapping->status !== 'verified' || $mapping->verified_at === null
            || $mapping->verified_at->lt(now()->subDays(30))) {
            throw new RuntimeException('Choose a fresh, verified US market from this platform before saving it.');
        }

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

        return DB::transaction(function () use ($campaign, $mapping, $location, $countries, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== null && $expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $set ??= TargetingSet::query()->create([
                'campaign_id' => $campaign->getKey(), 'platform' => $campaign->platform,
                'mode' => 'override', 'revision' => 0, 'schema_version' => 1,
            ]);

            if ($set->wasRecentlyCreated || $set->mode !== 'override') {
                $this->replaceCountries($set, $countries);
            }

            if ($set->locations()->where('location_id', $location->getKey())->exists()) {
                throw new RuntimeException('This DMA market is already selected on the campaign.');
            }

            $set->locations()->create([
                'location_id' => $location->getKey(), 'platform_location_id' => $mapping->getKey(),
                'operation' => 'include', 'kind' => 'dma',
                'display_label' => $mapping->provider_name, 'country_code' => 'US',
            ]);
            $set->update(['mode' => 'override', 'revision' => $set->revision + 1]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function addGoogleRadius(Campaign $campaign, string $countryCode, float $latitude, float $longitude, float $radius, string $unit, ?int $expectedRevision = null): TargetingSet
    {
        if ($campaign->isPublished() || $campaign->platform !== 'google'
            || ($campaign->campaign_type ?: 'search') !== 'search'
            || ! in_array($countryCode, $this->countries($campaign), true)
            || ! is_finite($latitude) || ! is_finite($longitude) || ! is_finite($radius)
            || $latitude <= -90 || $latitude >= 90 || $longitude <= -180 || $longitude >= 180
            || ! in_array($unit, ['km', 'mi'], true) || $radius < 1 || $radius > 50) {
            throw new RuntimeException('Google Search radius needs confirmed coordinates, a selected country, and a radius of 1 to 50 km or mi.');
        }

        $countries = $this->countries($campaign);
        $latitude = round($latitude, 6);
        $longitude = round($longitude, 6);
        $radius = round($radius, 2);

        return DB::transaction(function () use ($campaign, $countryCode, $latitude, $longitude, $radius, $unit, $countries, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== null && $expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $set ??= TargetingSet::query()->create([
                'campaign_id' => $campaign->getKey(), 'platform' => 'google',
                'mode' => 'override', 'revision' => 0, 'schema_version' => 1,
            ]);

            if ($set->wasRecentlyCreated || $set->mode !== 'override') {
                $this->replaceCountries($set, $countries);
            }

            if ($set->locations()->where('kind', 'radius')->where('country_code', $countryCode)
                ->where('latitude', $latitude)->where('longitude', $longitude)
                ->where('radius', $radius)->where('radius_unit', $unit)->exists()) {
                throw new RuntimeException('This radius is already selected on the campaign.');
            }

            $set->locations()->create([
                'operation' => 'include', 'kind' => 'radius', 'country_code' => $countryCode,
                'latitude' => $latitude, 'longitude' => $longitude, 'radius' => $radius,
                'radius_unit' => $unit,
                'display_label' => sprintf('Radius %.2F %s around %.6F, %.6F (%s)', $radius, $unit, $latitude, $longitude, $countryCode),
            ]);
            $set->update(['mode' => 'override', 'revision' => $set->revision + 1]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function removeGoogleRadius(Campaign $campaign, string $countryCode, int $selectionId, ?int $expectedRevision = null): TargetingSet
    {
        if ($campaign->isPublished() || $campaign->platform !== 'google') {
            throw new RuntimeException('Only Google draft campaigns can remove a radius.');
        }

        return DB::transaction(function () use ($campaign, $countryCode, $selectionId, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first()
                ?? throw new RuntimeException('This campaign has no radius to remove.');

            if ($expectedRevision !== null && $expectedRevision !== $set->revision) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $selection = $set->locations()->whereKey($selectionId)->where('country_code', $countryCode)->where('kind', 'radius')
                ->where('operation', 'include')->first()
                ?? throw new RuntimeException('This radius is not selected on the campaign.');

            $selection->delete();
            $set->update(['revision' => $set->revision + 1]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function googlePresenceMode(Campaign $campaign): string
    {
        $selected = $campaign->targetingSet()->first()?->options['google_presence'] ?? null;
        $mode = $selected ?? 'PRESENCE';

        if ($campaign->platform !== 'google' || ! in_array($mode, ['PRESENCE', 'PRESENCE_OR_INTEREST'], true)) {
            throw new RuntimeException('Google location presence preference is invalid. Review it before publishing.');
        }

        if ($selected !== null && ($campaign->campaign_type ?: 'search') !== 'search') {
            throw new RuntimeException('An explicit Google location-presence choice is available for Search campaigns only.');
        }

        return $mode;
    }

    public function setGooglePresenceMode(Campaign $campaign, string $mode, ?int $expectedRevision = null): TargetingSet
    {
        if ($campaign->isPublished() || $campaign->platform !== 'google'
            || ($campaign->campaign_type ?: 'search') !== 'search'
            || ! in_array($mode, ['PRESENCE', 'PRESENCE_OR_INTEREST'], true)) {
            throw new RuntimeException('Choose a supported Google Search location-presence option on a draft campaign.');
        }

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

        return DB::transaction(function () use ($campaign, $mode, $countries, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== null && $expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $set ??= TargetingSet::query()->create([
                'campaign_id' => $campaign->getKey(), 'platform' => 'google',
                'mode' => 'override', 'revision' => 0, 'schema_version' => 1,
            ]);

            if ($set->wasRecentlyCreated || $set->mode !== 'override') {
                $this->replaceCountries($set, $countries);
            }

            $set->update([
                'mode' => 'override', 'revision' => $set->revision + 1,
                'options' => [...(array) ($set->options ?? []), 'google_presence' => $mode],
            ]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    /** @return list<array{selection_id: int, label: string, country_code: string|null, latitude: string|null, longitude: string|null, radius: string|null, radius_unit: string|null}> */
    public function selectedGoogleRadii(Campaign $campaign): array
    {
        return $campaign->targetingSet()->first()?->locations()
            ->where('kind', 'radius')->where('operation', 'include')->orderBy('id')->get()
            ->map(fn ($selection): array => [
                'selection_id' => $selection->getKey(), 'label' => $selection->display_label,
                'country_code' => $selection->country_code, 'latitude' => $selection->latitude,
                'longitude' => $selection->longitude, 'radius' => $selection->radius,
                'radius_unit' => $selection->radius_unit,
            ])->all() ?? [];
    }

    /** @return list<array{external_id: string, label: string, country_code: string|null}> */
    public function selectedCampaignLocations(Campaign $campaign, string $countryCode, string $operation = 'include', ?string $kind = null): array
    {
        $query = $campaign->targetingSet()->first()?->locations()
            ->where('kind', '!=', 'country')
            ->where('operation', $operation)
            ->where('country_code', $countryCode);

        if ($kind !== null) {
            $query?->where('kind', $kind);
        } elseif ($query !== null) {
            $query->whereIn('kind', ['city', 'region']);
        }

        return $query?->with('platformLocation:id,external_id')
            ->orderBy('id')
            ->get()
            ->filter(fn ($selection): bool => $selection->platformLocation !== null)
            ->map(fn ($selection): array => [
                'external_id' => $selection->platformLocation->external_id,
                'label' => $selection->display_label,
                'country_code' => $selection->country_code,
            ])
            ->values()
            ->all() ?? [];
    }

    /** @return list<array{selection_id: int, mapping_id: int|null, external_id: string|null, parent_external_id: string|null, label: string, kind: string, operation: string, country_code: string|null, latitude: string|null, longitude: string|null, radius: string|null, radius_unit: string|null}> */
    public function reviewedCampaignPlaces(Campaign $campaign): array
    {
        return $campaign->targetingSet()->first()?->locations()
            ->where('kind', '!=', 'country')
            ->with('platformLocation:id,external_id,parent_external_id')
            ->orderBy('id')
            ->get()
            ->map(fn ($selection): array => [
                'selection_id' => $selection->getKey(),
                'mapping_id' => $selection->platformLocation?->getKey(),
                'external_id' => $selection->platformLocation?->external_id,
                'parent_external_id' => $selection->platformLocation?->parent_external_id,
                'label' => $selection->display_label,
                'kind' => $selection->kind,
                'operation' => $selection->operation,
                'country_code' => $selection->country_code,
                'latitude' => $selection->latitude,
                'longitude' => $selection->longitude,
                'radius' => $selection->radius,
                'radius_unit' => $selection->radius_unit,
            ])
            ->all() ?? [];
    }

    /** @return list<array{id: int, location_id: int|null, kind: string, name: string, label: string, country_code: string|null}> */
    public function sharedPlaceIntents(Campaign $campaign): array
    {
        return $campaign->brief?->targetingSet()->first()?->locations()
            ->whereIn('kind', ['city', 'region'])
            ->where('operation', 'include')
            ->with('location:id,name')
            ->orderBy('id')
            ->get()
            ->map(fn ($place): array => [
                'id' => $place->getKey(),
                'location_id' => $place->location_id,
                'kind' => $place->kind,
                'name' => $place->location?->name ?? '',
                'label' => $place->display_label,
                'country_code' => $place->country_code,
            ])
            ->all() ?? [];
    }

    /** @return list<array{id: int, location_id: int|null, kind: string, name: string, label: string, country_code: string|null}> */
    public function pendingSharedPlaces(Campaign $campaign): array
    {
        $set = $campaign->targetingSet()->first();
        $options = (array) ($set?->options ?? []);

        if (in_array($options['place_intent_mode'] ?? 'inherit', ['override', 'clear'], true)) {
            return [];
        }

        $resolved = (array) ($options['resolved_shared_places'] ?? []);
        $selected = $set?->locations()
            ->whereIn('kind', ['city', 'region'])
            ->where('operation', 'include')
            ->with('platformLocation.location')
            ->get()
            ->keyBy('platform_location_id') ?? collect();

        return array_values(array_filter($this->sharedPlaceIntents($campaign),
            function (array $place) use ($resolved, $selected): bool {
                $selection = $selected->get($resolved[$place['id']] ?? null);
                $mapping = $selection?->platformLocation;

                return $mapping === null
                    || $selection->kind !== $place['kind']
                    || $selection->country_code !== $place['country_code']
                    || mb_strtolower((string) $mapping->location?->name) !== mb_strtolower($place['name'])
                    || ! $this->sameParentLabel($place['label'], (string) $mapping->provider_name);
            },
        ));
    }

    public function setPlaceIntentMode(Campaign $campaign, string $mode, ?int $expectedRevision = null): TargetingSet
    {
        if ($campaign->isPublished()) {
            throw new RuntimeException('Location targeting cannot be changed on a published campaign.');
        }

        if (! in_array($mode, ['inherit', 'override', 'clear'], true)) {
            throw new RuntimeException('Place intent mode must be inherit, override, or clear.');
        }

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

        return DB::transaction(function () use ($campaign, $mode, $expectedRevision, $countries): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== null && $expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $set ??= TargetingSet::query()->create([
                'campaign_id' => $campaign->getKey(),
                'platform' => $campaign->platform,
                'mode' => 'override',
                'revision' => 0,
                'schema_version' => 1,
            ]);

            if ($set->wasRecentlyCreated || $set->mode !== 'override') {
                $this->replaceCountries($set, $countries);
            }

            $options = (array) ($set->options ?? []);
            $options['place_intent_mode'] = $mode;
            if ($mode === 'clear') {
                $options['geography_scope'] = 'whole';
            } else {
                unset($options['geography_scope']);
            }

            $set->locations()->whereIn('kind', ['city', 'region', 'postal'])->delete();
            $options['resolved_shared_places'] = [];

            $set->update(['mode' => 'override', 'revision' => $set->revision + 1, 'options' => $options]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function removeCampaignLocation(Campaign $campaign, string $countryCode, string $externalId, ?int $expectedRevision = null): TargetingSet
    {
        if ($campaign->isPublished()) {
            throw new RuntimeException('Location targeting cannot be changed on a published campaign. Create a new campaign for a different audience.');
        }

        return DB::transaction(function () use ($campaign, $countryCode, $externalId, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first()
                ?? throw new RuntimeException('This campaign has no selected city or region to remove.');

            if ($expectedRevision !== null && $expectedRevision !== $set->revision) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $selection = $set->locations()
                ->where('kind', '!=', 'country')
                ->where('operation', 'include')
                ->where('country_code', $countryCode)
                ->whereHas('platformLocation', fn ($query) => $query->where('platform', $campaign->platform)->where('external_id', $externalId))
                ->first() ?? throw new RuntimeException('This city or region is not selected on the campaign.');

            $selection->delete();
            $options = (array) ($set->options ?? []);
            $options['resolved_shared_places'] = array_filter(
                (array) ($options['resolved_shared_places'] ?? []),
                fn (mixed $mappingId): bool => (int) $mappingId !== (int) $selection->platform_location_id,
            );
            $set->update(['revision' => $set->revision + 1, 'options' => $options]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function removeGoogleLocationExclusion(Campaign $campaign, string $countryCode, string $externalId, ?int $expectedRevision = null): TargetingSet
    {
        if ($campaign->isPublished() || $campaign->platform !== 'google') {
            throw new RuntimeException('Only Google draft campaigns can change excluded locations.');
        }

        return DB::transaction(function () use ($campaign, $countryCode, $externalId, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first()
                ?? throw new RuntimeException('This campaign has no excluded city or region to remove.');

            if ($expectedRevision !== null && $expectedRevision !== $set->revision) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $selection = $set->locations()->whereIn('kind', ['city', 'region'])
                ->where('operation', 'exclude')->where('country_code', $countryCode)
                ->whereHas('platformLocation', fn ($query) => $query->where('platform', 'google')->where('external_id', $externalId))
                ->first() ?? throw new RuntimeException('This city or region is not excluded on the campaign.');

            $selection->delete();
            $set->update(['revision' => $set->revision + 1]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    /** @return array{countries?: list<string>, cities?: list<array{key: string}>, regions?: list<array{key: string}>, zips?: list<array{key: string}>, geo_markets?: list<array{key: string}>} */
    public function metaGeoLocations(Campaign $campaign): array
    {
        if ($campaign->platform !== 'meta') {
            throw new RuntimeException('Meta locations require a Meta campaign.');
        }

        $countries = $this->countries($campaign);
        $legacy = (array) ($campaign->locations ?? []);

        if (filled($legacy['cities'] ?? null) || filled($legacy['regions'] ?? null)) {
            throw new RuntimeException('Legacy city or region targeting must be reselected from Meta before publishing.');
        }

        if (filled($legacy['meta_geo_locations'] ?? null)) {
            throw new RuntimeException('Imported Meta location criteria must be reselected before publishing a new draft.');
        }

        $geo = [];
        $narrowedCountries = [];
        $set = $campaign->targetingSet()->first();

        if ($set !== null && $set->platform !== 'meta') {
            throw new RuntimeException('The targeting set does not belong to this Meta campaign.');
        }

        foreach ($set?->locations()->where('kind', '!=', 'country')->with('platformLocation.location')->get() ?? [] as $selection) {
            $mapping = $selection->platformLocation;

            if ($selection->operation !== 'include'
                || ! in_array($selection->kind, ['city', 'region', 'postal', 'dma'], true)
                || $selection->radius !== null
                || $mapping === null
                || $mapping->platform !== 'meta'
                || blank($mapping->external_id)
                || ($selection->kind === 'dma' && ($selection->country_code !== 'US'
                    || ! preg_match('/^COMSCORE_MARKET:[0-9]+$/D', $mapping->external_id)))
                || $mapping->status !== 'verified'
                || $mapping->verified_at === null
                || $mapping->verified_at->lt(now()->subDays(30))
                || $mapping->location_id !== $selection->location_id
                || $mapping->location->type !== $selection->kind
                || $mapping->location->country_code !== $selection->country_code
                || ! in_array($selection->country_code, $countries, true)) {
                throw new RuntimeException('A selected Meta city or region is invalid or out of date. Search and select it again before publishing.');
            }

            $geo[match ($selection->kind) {
                'city' => 'cities', 'region' => 'regions', 'postal' => 'zips', default => 'geo_markets',
            }][] = ['key' => $mapping->external_id];
            $narrowedCountries[] = $selection->country_code;
        }

        $wholeCountries = array_values(array_diff($countries, $narrowedCountries));

        if ($wholeCountries !== []) {
            $geo = ['countries' => $wholeCountries, ...$geo];
        }

        if ($geo === []) {
            throw new RuntimeException('Choose at least one country or verified Meta city or region before publishing.');
        }

        return $geo;
    }

    /** @return list<string> */
    public function linkedinDmaUrns(Campaign $campaign): array
    {
        if ($campaign->platform !== 'linkedin') {
            throw new RuntimeException('LinkedIn markets require a LinkedIn campaign.');
        }

        $countries = $this->countries($campaign);
        $set = $campaign->targetingSet()->first();

        if ($set !== null && $set->platform !== 'linkedin') {
            throw new RuntimeException('The targeting set does not belong to this LinkedIn campaign.');
        }

        $urns = [];

        foreach ($set?->locations()->where('kind', '!=', 'country')->with('platformLocation.location')->get() ?? [] as $selection) {
            $mapping = $selection->platformLocation;

            if ($selection->operation !== 'include' || $selection->kind !== 'dma'
                || $selection->country_code !== 'US' || ! in_array('US', $countries, true)
                || $mapping === null || $mapping->platform !== 'linkedin'
                || ! preg_match('/^urn:li:geo:[0-9]+$/D', $mapping->external_id)
                || ! preg_match('/^DMA® [0-9]+ - .+, United States$/uD', (string) $mapping->provider_name)
                || $mapping->status !== 'verified' || $mapping->verified_at === null
                || $mapping->verified_at->lt(now()->subDays(30))
                || $mapping->location_id !== $selection->location_id
                || $mapping->location->type !== 'dma'
                || $mapping->location->country_code !== 'US') {
                throw new RuntimeException('A selected LinkedIn DMA market is invalid or out of date. Search and select it again before publishing.');
            }

            $urns[] = $mapping->external_id;
        }

        return array_values(array_unique($urns));
    }

    /** @return array{countries: list<string>, geo_targets: list<string>, excluded_geo_targets?: list<string>, proximity_targets?: list<array{latitude: string, longitude: string, radius: string, radius_unit: string}>} */
    public function googleGeoTargets(Campaign $campaign): array
    {
        if ($campaign->platform !== 'google') {
            throw new RuntimeException('Google locations require a Google campaign.');
        }

        $countries = $this->countries($campaign);
        $legacy = (array) ($campaign->locations ?? []);

        if (filled($legacy['cities'] ?? null) || filled($legacy['regions'] ?? null)) {
            throw new RuntimeException('Legacy city or region targeting must be reselected from Google before publishing.');
        }

        if (filled($legacy['google_location_criteria'] ?? null) || filled($legacy['google_proximity_criteria'] ?? null)) {
            throw new RuntimeException('Imported Google location and radius criteria must be reselected before publishing a new draft.');
        }

        $targets = [];
        $exclusions = [];
        $proximities = [];
        $narrowedCountries = [];
        $set = $campaign->targetingSet()->first();

        if ($set !== null && $set->platform !== 'google') {
            throw new RuntimeException('The targeting set does not belong to this Google campaign.');
        }

        foreach ($set?->locations()->where('kind', '!=', 'country')->with('platformLocation.location')->get() ?? [] as $selection) {
            $mapping = $selection->platformLocation;

            if ($selection->kind === 'radius') {
                $latitude = (float) $selection->latitude;
                $longitude = (float) $selection->longitude;
                $radius = (float) $selection->radius;

                if ($selection->operation !== 'include' || ($campaign->campaign_type ?: 'search') !== 'search'
                    || $mapping !== null || $selection->location_id !== null
                    || ! in_array($selection->country_code, $countries, true)
                    || $selection->latitude === null || $selection->longitude === null || $selection->radius === null
                    || ! is_finite($latitude) || ! is_finite($longitude) || ! is_finite($radius)
                    || $latitude <= -90 || $latitude >= 90 || $longitude <= -180 || $longitude >= 180
                    || $radius < 1 || $radius > 50 || ! in_array($selection->radius_unit, ['km', 'mi'], true)) {
                    throw new RuntimeException('A selected Google radius is invalid. Review its center, country, distance, and unit before publishing.');
                }

                $proximities[] = [
                    'latitude' => sprintf('%.6F', $latitude),
                    'longitude' => sprintf('%.6F', $longitude),
                    'radius' => sprintf('%.2F', $radius),
                    'radius_unit' => $selection->radius_unit,
                ];
                $narrowedCountries[] = $selection->country_code;

                continue;
            }

            if (! in_array($selection->operation, ['include', 'exclude'], true)
                || ($selection->operation === 'exclude' && ($campaign->campaign_type ?: 'search') !== 'search')
                || ! in_array($selection->kind, ['city', 'region', 'postal', 'dma'], true)
                || ($selection->kind === 'dma' && ($selection->operation !== 'include'
                    || ($campaign->campaign_type ?: 'search') !== 'search'
                    || $selection->country_code !== 'US'
                    || ! preg_match('/^geoTargetConstants\/[0-9]+$/D', (string) $mapping?->parent_external_id)))
                || $selection->radius !== null
                || $mapping === null
                || $mapping->platform !== 'google'
                || ! preg_match('/^geoTargetConstants\/[0-9]+$/D', $mapping->external_id)
                || $mapping->status !== 'verified'
                || $mapping->verified_at === null
                || $mapping->verified_at->lt(now()->subDays(30))
                || $mapping->location_id !== $selection->location_id
                || $mapping->location->type !== $selection->kind
                || $mapping->location->country_code !== $selection->country_code
                || ! in_array($selection->country_code, $countries, true)) {
                throw new RuntimeException('A selected Google place or market is invalid or out of date. Search and select it again before publishing.');
            }

            if ($selection->operation === 'exclude') {
                $exclusions[] = $mapping->external_id;
            } else {
                $targets[] = $mapping->external_id;
                $narrowedCountries[] = $selection->country_code;
            }
        }

        if (array_intersect($targets, $exclusions) !== []) {
            throw new RuntimeException('A Google place cannot be both included and excluded.');
        }

        return [
            'countries' => array_values(array_diff($countries, $narrowedCountries)),
            'geo_targets' => array_values(array_unique($targets)),
            ...($exclusions === [] ? [] : ['excluded_geo_targets' => array_values(array_unique($exclusions))]),
            ...($proximities === [] ? [] : ['proximity_targets' => $proximities]),
        ];
    }

    /**
     * Versioned selections belong to the campaign's primary ad set. Until they
     * can be reviewed per ad set, another row cannot silently inherit only the
     * legacy JSON and omit audience exclusions or narrower geography.
     *
     * @return list<string>
     */
    public function additionalMetaAdSetProblems(CampaignAdSet $adSet): array
    {
        $campaign = $adSet->campaign;

        if ($campaign === null || $campaign->platform !== 'meta') {
            return [];
        }

        $set = $campaign->targetingSet()->first();
        $problems = [];
        $audience = (array) ($adSet->audience ?? []);
        $audienceKeys = ['meta_custom_audiences', 'meta_excluded_custom_audiences', 'custom_audiences', 'excluded_custom_audiences'];

        if (filled($audience['duplicate_of'] ?? null)) {
            return $this->incompleteDuplicateProblems($adSet, $campaign, $set, $audience, $audienceKeys);
        }

        if (filled($set?->options['meta_audiences'] ?? null)
            || filled($campaign->external_ids['meta_custom_audience_criteria'] ?? null)
            || array_filter(array_intersect_key($audience, array_flip($audienceKeys))) !== []) {
            $problems[] = 'Adding an ad set with campaign audience inclusions or exclusions is not supported yet. '
                .'Audience selections must be reviewed per ad set before this can be published.';
        }

        $locationKeys = ['cities', 'regions', 'meta_geo_locations', 'geo_locations', 'geo_markets', 'custom_locations', 'excluded_geo_locations'];
        $campaignPlaces = array_intersect_key((array) ($campaign->locations ?? []), array_flip($locationKeys));
        $adSetPlaces = array_intersect_key((array) ($adSet->locations ?? []), array_flip($locationKeys));

        if ($set?->locations()->where('kind', '!=', 'country')->exists()
            || array_filter($campaignPlaces) !== []
            || array_filter($adSetPlaces) !== []) {
            $problems[] = 'Adding an ad set with city, region, market or other place restrictions is not supported yet. '
                .'Those locations must be reselected and reviewed per ad set before publishing.';
        }

        return $problems;
    }

    /**
     * A copy may carry the original city and audiences. It may not drop them.
     *
     * @param  array<string, mixed>  $audience
     * @param  list<string>  $audienceKeys
     * @return list<string>
     */
    private function incompleteDuplicateProblems(CampaignAdSet $adSet, Campaign $campaign, ?TargetingSet $set, array $audience, array $audienceKeys): array
    {
        $sourceId = (string) $audience['duplicate_of'];
        $source = $campaign->adSets()
            ->where('id', '!=', $adSet->id)
            ->whereNotNull('external_adset_id')
            ->where(function ($query) use ($sourceId): void {
                $query->where('external_adset_id', $sourceId)->orWhere('id', $sourceId);
            })
            ->first();

        if ($source === null) {
            return ['This copy does not name an ad set in this campaign. Ask which ad set to duplicate.'];
        }

        $problems = [];
        $locationKeys = ['cities', 'regions', 'meta_geo_locations', 'geo_locations', 'geo_markets', 'custom_locations', 'excluded_geo_locations'];
        $campaignPlaces = array_intersect_key((array) ($campaign->locations ?? []), array_flip($locationKeys));
        $adSetPlaces = array_intersect_key((array) ($adSet->locations ?? []), array_flip($locationKeys));
        $geo = (array) ($adSet->locations['geo_locations'] ?? []);
        $hasPlaces = array_filter($adSetPlaces) !== []
            || array_filter(array_intersect_key($geo, array_flip(['cities', 'regions', 'zips', 'geo_markets']))) !== [];
        $needsPlaces = ($set?->locations()->where('kind', '!=', 'country')->exists() ?? false)
            || array_filter($campaignPlaces) !== [];

        if ($needsPlaces && ! $hasPlaces) {
            $problems[] = 'This copy is missing the original city, region or market. Ask the user to select that place again, then duplicate the ad set.';
        }

        $needsAudiences = filled($set?->options['meta_audiences'] ?? null)
            || filled($campaign->external_ids['meta_custom_audience_criteria'] ?? null);
        $hasAudiences = array_filter(array_intersect_key($audience, array_flip($audienceKeys))) !== [];

        if ($needsAudiences && ! $hasAudiences) {
            $problems[] = 'This copy is missing the original included or excluded audiences. Ask the user which audiences to keep, then duplicate the ad set.';
        }

        return $problems;
    }

    /** @return list<string> */
    public function locationProblems(Campaign $campaign): array
    {
        if ($campaign->isPublished()) {
            return [];
        }

        $sharedProblems = array_map(
            fn (array $place): string => sprintf(
                'Shared %s %s needs an exact %s place selection, or an explicit place override/clear.',
                $place['kind'], $place['label'], ucfirst((string) $campaign->platform),
            ),
            $this->pendingSharedPlaces($campaign),
        );

        $set = $campaign->targetingSet()->first();
        if (($set?->options['place_intent_mode'] ?? null) === 'override'
            && ! $set->locations()->whereIn('kind', ['city', 'region', 'postal'])->where('operation', 'include')->exists()) {
            $sharedProblems[] = 'Choose the replacement city or state before publishing, or explicitly target whole countries.';
        }

        if ($campaign->platform === 'google') {
            try {
                $this->googleGeoTargets($campaign);
                $this->googlePresenceMode($campaign);

                return $sharedProblems;
            } catch (RuntimeException $exception) {
                return [$exception->getMessage(), ...$sharedProblems];
            }
        }

        if ($campaign->platform === 'linkedin') {
            try {
                $this->linkedinDmaUrns($campaign);

                return $sharedProblems;
            } catch (RuntimeException $exception) {
                return [$exception->getMessage(), ...$sharedProblems];
            }
        }

        if ($campaign->platform !== 'meta') {
            $platformProblems = $campaign->targetingSet()->first()?->locations()->where('kind', '!=', 'country')->exists()
                ? ['City or region targeting is not available for '.$campaign->platform.' yet.']
                : [];

            return [...$platformProblems, ...$sharedProblems];
        }

        try {
            $this->metaGeoLocations($campaign);

            return $sharedProblems;
        } catch (RuntimeException $exception) {
            return [$exception->getMessage(), ...$sharedProblems];
        }
    }

    private function rememberSharedPlace(Campaign $campaign, PlatformLocation $mapping, ?int $sharedPlaceId): ?int
    {
        $brief = $campaign->brief;

        if ($brief === null) {
            if ($sharedPlaceId !== null) {
                throw new RuntimeException('This campaign has no shared brief place to resolve.');
            }

            return null;
        }

        $location = $mapping->location;
        $intents = $this->sharedPlaceIntents($campaign);

        if ($sharedPlaceId !== null) {
            $intent = collect($intents)->firstWhere('id', $sharedPlaceId)
                ?? throw new RuntimeException('The shared place no longer belongs to this brief. Review it again.');

            if ($intent['kind'] !== $location->type
                || $intent['country_code'] !== $location->country_code
                || mb_strtolower($intent['name']) !== mb_strtolower($location->name)
                || ! $this->sameParentLabel($intent['label'], (string) $mapping->provider_name)) {
                throw new RuntimeException('The selected provider place does not match the shared brief place. Choose the exact city or region.');
            }

            return $sharedPlaceId;
        }

        foreach ($intents as $intent) {
            if ($intent['kind'] === $location->type
                && $intent['country_code'] === $location->country_code
                && mb_strtolower($intent['name']) === mb_strtolower($location->name)
                && $this->sameParentLabel($intent['label'], (string) $mapping->provider_name)) {
                if ($intent['location_id'] === $location->getKey()) {
                    return $intent['id'];
                }

                throw new RuntimeException('This place is already shared by the brief. Select it using shared_place_id '.$intent['id'].' or explicitly override shared places.');
            }
        }

        $set = TargetingSet::query()->where('brief_id', $brief->getKey())->lockForUpdate()->first();
        $set ??= TargetingSet::query()->create([
            'brief_id' => $brief->getKey(),
            'mode' => 'override',
            'revision' => 0,
            'schema_version' => 1,
        ]);

        if ($set->wasRecentlyCreated) {
            $this->replaceCountries($set, array_values((array) ($brief->locations['countries'] ?? [])));
        }

        $place = $set->locations()->create([
            'location_id' => $location->getKey(),
            'operation' => 'include',
            'kind' => $location->type,
            'display_label' => $mapping->provider_name,
            'country_code' => $location->country_code,
        ]);
        $set->update(['revision' => $set->revision + 1]);

        return $place->getKey();
    }

    private function sameParentLabel(string $original, string $candidate): bool
    {
        $originalParts = array_map('trim', explode(',', $original));
        $candidateParts = array_map('trim', explode(',', $candidate));

        if (count($originalParts) < 3 || count($candidateParts) < 3) {
            return count($originalParts) < 3 && count($candidateParts) < 3;
        }

        return mb_strtolower($originalParts[1]) === mb_strtolower($candidateParts[1]);
    }

    /** @param list<string> $codes */
    public function rememberBriefCountries(Brief $brief, array $codes): void
    {
        if ($codes === [] || filled($brief->locations['countries'] ?? null)) {
            return;
        }

        DB::transaction(function () use ($brief, $codes): void {
            $set = TargetingSet::query()->firstOrCreate(
                ['brief_id' => $brief->getKey()],
                ['mode' => 'override', 'revision' => 1, 'schema_version' => 1],
            );
            $this->replaceCountries($set, $codes);
            $brief->update(['locations' => array_replace((array) $brief->locations, ['countries' => $codes])]);
        });
    }

    public function backfillBrief(Brief $brief): void
    {
        $codes = array_values((array) ($brief->locations['countries'] ?? []));

        if ($codes === [] || $brief->targetingSet()->exists()) {
            return;
        }

        DB::transaction(function () use ($brief, $codes): void {
            $set = TargetingSet::query()->create([
                'brief_id' => $brief->getKey(),
                'mode' => 'override',
                'revision' => 1,
                'schema_version' => 1,
            ]);
            $this->replaceCountries($set, $codes);
        });
    }

    public function backfillCampaign(Campaign $campaign): void
    {
        if ($campaign->targetingSet()->exists()) {
            return;
        }

        $rawLocations = $campaign->primaryAdSet?->getRawOriginal('locations');
        $stored = is_string($rawLocations) ? json_decode($rawLocations, true, 512, JSON_THROW_ON_ERROR) : $rawLocations;
        $codes = array_values((array) ($stored['countries'] ?? []));

        if ($codes === [] && ($campaign->brief === null || blank($campaign->brief->locations['countries'] ?? null))) {
            return;
        }

        DB::transaction(function () use ($campaign, $codes): void {
            $set = TargetingSet::query()->create([
                'campaign_id' => $campaign->getKey(),
                'platform' => $campaign->platform,
                'mode' => $codes === [] ? 'inherit' : 'override',
                'revision' => 1,
                'schema_version' => 1,
            ]);

            if ($codes !== []) {
                $this->replaceCountries($set, $codes);
            }
        });
    }

    /** @return list<string> */
    private function briefCountries(?Brief $brief): array
    {
        if ($brief === null) {
            return [];
        }

        $set = $brief->targetingSet;

        if ($set === null) {
            return array_values((array) ($brief->locations['countries'] ?? []));
        }

        return $set->locations()
            ->where('kind', 'country')
            ->where('operation', 'include')
            ->orderBy('id')
            ->pluck('country_code')
            ->filter()
            ->values()
            ->all();
    }

    /** @param list<string> $codes */
    private function replaceCountries(TargetingSet $set, array $codes): void
    {
        $locationIds = [];

        foreach ($codes as $code) {
            $name = config('countries.'.$code);
            if (! is_string($name)) {
                throw new RuntimeException('Unrecognised country code: '.$code.'.');
            }

            $location = Location::query()->firstOrCreate(
                ['iso_code' => $code],
                ['type' => 'country', 'name' => $name, 'country_code' => $code, 'source' => 'iso_3166_1', 'source_key' => $code],
            );
            $locationIds[] = $location->getKey();

            $set->locations()->updateOrCreate(
                ['location_id' => $location->getKey(), 'operation' => 'include'],
                ['kind' => 'country', 'country_code' => $code, 'display_label' => $location->name],
            );
        }

        $set->locations()->where('kind', 'country')->where('operation', 'include')
            ->whereNotIn('location_id', $locationIds)->delete();
    }
}
