<?php

namespace Tests\Feature;

use App\Agent\NamespacedTool;
use App\Agent\Tools\Campaign\ChoosePixel;
use App\Agent\Tools\Campaign\EditGoogleConversionGoals;
use App\Agent\Workspace;
use App\Campaigns\CampaignImporter;
use App\Campaigns\Manager\CampaignSynchronizer;
use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Campaigns\Manager\Editing\EditRefused;
use App\Campaigns\Manager\Editing\EntityEditor;
use App\Livewire\CampaignManager\EditEntity;
use App\Models\Campaign;
use App\Models\CampaignEntityEdit;
use App\Models\CampaignPlatformEntity;
use App\Models\CampaignSyncRun;
use App\Models\GoogleAdsConnection;
use App\Models\User;
use App\Services\GoogleAdsService;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Laravel\Ai\Tools\Request as ToolRequest;
use Livewire\Livewire;
use Mockery;
use RuntimeException;
use Tests\TestCase;

class CampaignManagerGoogleCompletionTest extends TestCase
{
    use RefreshDatabase;

    private Campaign $campaign;

    /** @var array<string, array<string, mixed>> */
    private array $campaigns = [];

    /** @var array<string, array<string, mixed>> */
    private array $budgets = [];

    /** @var array<string, array<string, mixed>> */
    private array $groups = [];

    /** @var array<string, array<string, mixed>> */
    private array $ads = [];

    /** @var array<string, array<string, mixed>> */
    private array $configs = [];

    /** @var array<string, array<string, bool>> */
    private array $goals = [];

    /** @var array<string, array<string, list<array<string, mixed>>>> */
    private array $criteria = ['campaign' => [], 'ad_group' => []];

    /** @var array<string, array<string, mixed>> */
    private array $assetGroups = [];

    /** @var array<string, list<array<string, mixed>>> */
    private array $assetLinks = [];

    /** @var array<string, list<array<string, mixed>>> */
    private array $signals = [];

    /** @var array<string, list<array<string, mixed>>> */
    private array $campaignAssets = [];

    /** @var array<string, list<array<string, mixed>>> */
    private array $sharedSets = [];

    /** @var array<string, array<string, list<array<string, mixed>>>> */
    private array $nativeLinks = ['campaign_asset_set' => [], 'ad_group_asset' => [], 'ad_group_asset_set' => []];

    /** @var array<string, array<string, ?float>> */
    private array $groupModifiers = [];

    private bool $listingGroups = false;

    private bool $customizers = false;

    /** @var array<mixed>|null */
    private ?array $streamResponse = null;

    private int $streamStatus = 200;

    private bool $rejectCriteria = false;

    private bool $ignoreCriteriaMutation = false;

    private bool $omitCopiedAsset = false;

    private bool $mismatchAd = false;

    private bool $creativeMetadata = false;

    private string $customGoalStatus = 'ENABLED';

    private bool $denyGoals = false;

    private bool $rejectConfig = false;

    private bool $ignoreGoalMutation = false;

    private bool $rejectAd = false;

    private bool $sharedAd = false;

    private bool $rejectAdUrls = false;

    private bool $ignoreAdUrls = false;

    private bool $rejectAdGroup = false;

    private bool $mismatchAdGroup = false;

    private bool $rejectCleanup = false;

    private bool $mismatch = false;

    /** @var list<array<string, mixed>>|null */
    private ?array $reportRows = null;

    protected function setUp(): void
    {
        parent::setUp();
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['google:*'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.dry_run' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 100,
            'campaign-manager.edit_platforms' => ['google'],
            'campaign-manager.edit_categories' => ['name', 'optimization', 'targeting', 'creative', 'duplicate', 'delete'],
            'services.google_ads.refresh_token' => 'test-token',
            'services.google_ads.customer_id' => '1234567890',
        ]);
        $this->campaign = Campaign::create([
            'user_id' => User::factory()->create()->id, 'platform' => 'google', 'status' => 'published',
            'name' => 'Search campaign', 'external_campaign_id' => '101', 'ad_account_id' => '1234567890', 'currency' => 'USD',
        ]);
        $this->campaigns['101'] = [
            'id' => '101', 'resourceName' => 'customers/1234567890/campaigns/101',
            'name' => 'Search campaign', 'status' => 'PAUSED', 'advertisingChannelType' => 'SEARCH',
            'campaignBudget' => 'customers/1234567890/campaignBudgets/501',
            'biddingStrategyType' => 'MANUAL_CPC', 'manualCpc' => ['enhancedCpcEnabled' => false],
            'brandGuidelinesEnabled' => false,
            'startDateTime' => now()->addDay()->format('Y-m-d H:i:s'), 'endDateTime' => now()->addWeek()->format('Y-m-d H:i:s'),
            'networkSettings' => ['targetGoogleSearch' => true, 'targetSearchNetwork' => false, 'targetContentNetwork' => false, 'targetPartnerSearchNetwork' => false],
            'geoTargetTypeSetting' => ['positiveGeoTargetType' => 'PRESENCE_OR_INTEREST', 'negativeGeoTargetType' => 'PRESENCE'],
            'trackingUrlTemplate' => 'https://example.com/track?url={lpurl}',
            'finalUrlSuffix' => 'source=google', 'urlCustomParameters' => [['key' => 'campaign', 'value' => 'original']],
        ];
        $this->budgets['501'] = ['resourceName' => 'customers/1234567890/campaignBudgets/501', 'amountMicros' => '20000000', 'referenceCount' => '1', 'period' => 'DAILY', 'deliveryMethod' => 'STANDARD'];
        $this->groups['201'] = [
            'id' => '201', 'resourceName' => 'customers/1234567890/adGroups/201', 'campaign' => 'customers/1234567890/campaigns/101',
            'name' => 'Search group', 'status' => 'ENABLED', 'type' => 'SEARCH_STANDARD', 'cpcBidMicros' => '1000000',
            'trackingUrlTemplate' => 'https://example.com/group?url={lpurl}', 'finalUrlSuffix' => 'group=1',
            'targetingSetting' => ['targetRestrictions' => [['targetingDimension' => 'AUDIENCE', 'bidOnly' => true]]],
        ];
        $this->ads['301'] = [
            'adGroup' => 'customers/1234567890/adGroups/201', 'status' => 'ENABLED',
            'ad' => ['id' => '301', 'name' => 'Search ad', 'type' => 'RESPONSIVE_SEARCH_AD', 'finalUrls' => ['https://example.com'],
                'finalMobileUrls' => ['https://m.example.com'], 'trackingUrlTemplate' => 'https://example.com/ad?url={lpurl}',
                'finalUrlSuffix' => 'ad=1', 'urlCustomParameters' => [['key' => 'source', 'value' => 'ad']],
                'responsiveSearchAd' => ['headlines' => [['text' => 'One', 'pinnedField' => 'HEADLINE_1'], ['text' => 'Two'], ['text' => 'Three']], 'descriptions' => [['text' => 'A description']], 'path1' => 'offer']],
        ];
        $this->configs['101'] = ['campaign' => 'customers/1234567890/campaigns/101', 'goalConfigLevel' => 'CUSTOMER'];
        $this->goals['101'] = ['PURCHASE~WEBSITE' => true, 'SIGNUP~WEBSITE' => false];
        Http::preventStrayRequests();
        Http::fake(function (Request $request) {
            if (str_contains($request->url(), 'oauth2.googleapis.com')) {
                return Http::response(['access_token' => 'test-access-token', 'expires_in' => 3600]);
            }
            if (str_contains($request->url(), 'googleAds:searchStream')) {
                if ($this->streamResponse !== null) {
                    return Http::response($this->streamResponse, $this->streamStatus);
                }
                if ($this->denyGoals && str_contains($request['query'], 'FROM conversion_goal_campaign_config')) {
                    return Http::response(['error' => ['message' => 'Goals permission denied']], 403);
                }
                foreach (['campaign_asset' => 'campaign', 'campaign_asset_set' => 'campaign', 'campaign_shared_set' => 'campaign',
                    'ad_group_asset' => 'ad_group', 'ad_group_asset_set' => 'ad_group'] as $resource => $scope) {
                    if (str_contains($request['query'], "FROM {$resource} ")
                        && ! str_contains(explode(' FROM ', $request['query'])[0], $scope.'.id')) {
                        return Http::response([['error' => ['message' => 'Referenced parent ID is required in SELECT']]], 400);
                    }
                }

                return Http::response([['results' => $this->rows($request['query'])]]);
            }

            return $this->mutation($request);
        });
        app(CampaignSynchronizer::class)->sync($this->campaign);
    }

    /** @return list<array<string, mixed>> */
    private function rows(string $query): array
    {
        if (str_contains($query, 'metrics.cost_micros') && $this->reportRows !== null) {
            return $this->reportRows;
        }
        preg_match('/campaign\.id = ([0-9]+)/', $query, $campaignMatch);
        $campaignId = $campaignMatch[1] ?? '101';
        if (str_contains($query, 'FROM conversion_goal_campaign_config')) {
            return [['conversionGoalCampaignConfig' => $this->configs[$campaignId]]];
        }
        if (str_contains($query, 'FROM campaign_conversion_goal')) {
            return array_map(function (string $key, bool $biddable) use ($campaignId): array {
                [$category, $origin] = explode('~', $key);

                return ['campaignConversionGoal' => ['campaign' => "customers/1234567890/campaigns/{$campaignId}", 'category' => $category, 'origin' => $origin, 'biddable' => $biddable]];
            }, array_keys($this->goals[$campaignId]), array_values($this->goals[$campaignId]));
        }
        if (str_contains($query, 'FROM custom_conversion_goal')) {
            return [['customConversionGoal' => ['resourceName' => 'customers/1234567890/customConversionGoals/701', 'status' => $this->customGoalStatus]]];
        }
        if (str_contains($query, 'FROM conversion_action')) {
            return [['conversionAction' => ['resourceName' => 'customers/1234567890/conversionActions/1',
                'name' => 'Purchase', 'category' => 'PURCHASE', 'type' => 'WEBPAGE']]];
        }
        if (str_contains($query, 'FROM campaign_budget')) {
            preg_match('/campaign_budget.id = ([0-9]+)/', $query, $match);

            return [['campaignBudget' => $this->budgets[$match[1]]]];
        }
        foreach (array_keys($this->nativeLinks) as $native) {
            if (str_contains($query, "FROM {$native} ")) {
                preg_match('/ad_group.id = ([0-9]+)/', $query, $groupMatch);
                $parent = str_starts_with($native, 'ad_group') ? $groupMatch[1] : $campaignId;

                return array_map(fn (array $link): array => [Str::camel($native) => $link], $this->nativeLinks[$native][$parent] ?? []);
            }
        }
        if (str_contains($query, 'FROM ad_group_bid_modifier')) {
            preg_match('/ad_group.id = ([0-9]+)/', $query, $groupMatch);
            $id = $groupMatch[1];

            return array_map(fn (string $device, int $criterion): array => ['adGroupBidModifier' => [
                'resourceName' => "customers/1234567890/adGroupBidModifiers/{$id}~{$criterion}",
                'device' => ['type' => $device], ...(isset($this->groupModifiers[$id][$device]) ? ['bidModifier' => $this->groupModifiers[$id][$device]] : []),
            ]], ['DESKTOP', 'MOBILE', 'TABLET'], [30000, 30001, 30002]);
        }
        if (str_contains($query, 'FROM campaign_customizer') || str_contains($query, 'FROM ad_group_customizer')) {
            return $this->customizers ? [['customizer' => ['resourceName' => 'native-customizer']]] : [];
        }
        if (str_contains($query, 'FROM campaign_asset')) {
            return array_map(fn (array $link): array => ['campaignAsset' => $link], $this->campaignAssets[$campaignId] ?? []);
        }
        if (str_contains($query, 'FROM campaign_shared_set')) {
            return array_map(fn (array $link): array => ['campaignSharedSet' => $link], $this->sharedSets[$campaignId] ?? []);
        }
        if (str_contains($query, 'FROM asset_group_listing_group_filter')) {
            return $this->listingGroups ? [['assetGroupListingGroupFilter' => ['resourceName' => 'listing-filter']]] : [];
        }
        if (str_contains($query, 'FROM asset_group_asset') || str_contains($query, 'FROM asset_group_signal')) {
            preg_match('/asset_group.id = ([0-9]+)/', $query, $groupMatch);
            $assets = str_contains($query, 'FROM asset_group_asset');
            $links = $assets ? $this->assetLinks[$groupMatch[1]] ?? [] : $this->signals[$groupMatch[1]] ?? [];

            return array_map(fn (array $link): array => [$assets ? 'assetGroupAsset' : 'assetGroupSignal' => $link], $links);
        }
        if (str_contains($query, 'FROM asset_group')) {
            return array_values(array_map(fn (array $group): array => ['assetGroup' => $group], array_filter(
                $this->assetGroups, fn (array $group): bool => $group['campaign'] === "customers/1234567890/campaigns/{$campaignId}",
            )));
        }
        if (str_contains($query, 'FROM campaign_criterion') || str_contains($query, 'FROM ad_group_criterion')) {
            $scope = str_contains($query, 'FROM ad_group_criterion') ? 'ad_group' : 'campaign';
            $key = $scope === 'campaign' ? 'campaignCriterion' : 'adGroupCriterion';
            preg_match('/ad_group.id = ([0-9]+)/', $query, $groupMatch);
            $parents = $scope === 'campaign' ? [$campaignId] : (isset($groupMatch[1]) ? [$groupMatch[1]] : array_keys(array_filter(
                $this->groups, fn (array $group): bool => $group['campaign'] === "customers/1234567890/campaigns/{$campaignId}",
            )));
            preg_match('/(?:campaign_criterion|ad_group_criterion)\.type = \'([A-Z_]+)\'/', $query, $typeMatch);
            preg_match('/\.type IN \(([^)]+)\)/', $query, $typeList);
            $rows = [];
            foreach ($parents as $parent) {
                foreach ($this->criteria[$scope][$parent] ?? [] as $criterion) {
                    if ((isset($typeMatch[1]) && $criterion['type'] !== $typeMatch[1])
                        || (isset($typeList[1]) && ! str_contains($typeList[1], "'".$criterion['type']."'"))) {
                        continue;
                    }
                    $rows[] = [$key => $criterion, ...($scope === 'ad_group' ? ['adGroup' => ['id' => (string) $parent]] : [])];
                }
            }

            return $rows;
        }
        if (str_contains($query, 'FROM ad_group_ad')) {
            if (str_starts_with($query, 'SELECT ad_group_ad.ad.id, ad_group.id FROM ad_group_ad WHERE ad_group_ad.ad.id =')) {
                preg_match('/ad_group_ad\.ad\.id = ([0-9]+)/', $query, $match);
                $ad = $this->ads[$match[1]] ?? null;
                if ($ad === null) {
                    return [];
                }
                $rows = [['adGroupAd' => ['ad' => ['id' => $match[1]]], 'adGroup' => ['id' => basename($ad['adGroup'])]]];
                if ($this->sharedAd) {
                    $rows[] = ['adGroupAd' => ['ad' => ['id' => $match[1]]], 'adGroup' => ['id' => '999']];
                }

                return $rows;
            }
            preg_match('/ad_group.id = ([0-9]+)/', $query, $groupMatch);
            preg_match('/ad_group_ad.ad.id = ([0-9]+)/', $query, $adMatch);
            $groupResource = isset($groupMatch[1]) ? 'customers/1234567890/adGroups/'.$groupMatch[1] : null;

            return array_values(array_map(fn (array $ad): array => ['adGroupAd' => $ad, 'adGroup' => $this->groups[basename($ad['adGroup'])]], array_filter(
                $this->ads, fn (array $ad): bool => (! isset($adMatch[1]) || $ad['ad']['id'] === $adMatch[1])
                    && ($groupResource === null || $ad['adGroup'] === $groupResource)
                    && (isset($groupMatch[1]) || $this->groups[basename($ad['adGroup'])]['campaign'] === "customers/1234567890/campaigns/{$campaignId}"),
            )));
        }
        if (str_contains($query, 'FROM ad_group')) {
            preg_match('/ad_group.id = ([0-9]+)/', $query, $match);

            return array_values(array_map(fn (array $group): array => ['adGroup' => $group, 'campaign' => $this->campaigns[basename($group['campaign'])]],
                array_filter($this->groups, fn (array $group): bool => isset($match[1]) ? $group['id'] === $match[1] : $group['campaign'] === "customers/1234567890/campaigns/{$campaignId}")));
        }
        if (str_contains($query, 'FROM campaign')) {
            $campaign = $this->campaigns[$campaignId];

            return [['campaign' => $campaign, 'campaignBudget' => $this->budgets[basename($campaign['campaignBudget'])], 'customer' => ['timeZone' => 'UTC']]];
        }
        throw new RuntimeException('Unexpected Google test query: '.$query);
    }

    private function mutation(Request $request): PromiseInterface
    {
        preg_match('~/([^/:]+):mutate$~', $request->url(), $match);
        $collection = $match[1] ?? '';
        if (in_array($collection, ['campaignConversionGoals', 'conversionGoalCampaignConfigs'], true) && isset($request['partialFailure'])) {
            return Http::response(['error' => ['message' => 'Unsupported partialFailure field on conversion goal endpoint']], 400);
        }
        if ($collection === 'googleAds') {
            $resource = 'customers/1234567890/assetGroups/402';
            $results = [];
            foreach ($request['mutateOperations'] as $operation) {
                if (isset($operation['assetGroupOperation'])) {
                    $group = $operation['assetGroupOperation']['create'];
                    $this->assetGroups['402'] = [...$group, 'id' => '402', 'resourceName' => $resource];
                    $results[] = ['assetGroupResult' => ['resourceName' => $resource]];
                } elseif (isset($operation['assetGroupAssetOperation'])) {
                    if (! $this->omitCopiedAsset) {
                        $this->assetLinks['402'][] = [...$operation['assetGroupAssetOperation']['create'], 'assetGroup' => $resource];
                    }
                    $results[] = ['assetGroupAssetResult' => ['resourceName' => $resource.'~601']];
                } elseif (isset($operation['assetGroupSignalOperation'])) {
                    $this->signals['402'][] = [...$operation['assetGroupSignalOperation']['create'], 'assetGroup' => $resource];
                    $results[] = ['assetGroupSignalResult' => ['resourceName' => $resource.'~701']];
                }
            }

            return Http::response(['mutateOperationResponses' => $results]);
        }
        if (in_array($collection, ['adGroupCriteria', 'campaignCriteria'], true) && $this->rejectCriteria) {
            return Http::response(['error' => ['message' => 'Criteria refused']], 400);
        }
        if (in_array($collection, ['adGroupCriteria', 'campaignCriteria'], true) && $this->ignoreCriteriaMutation) {
            return Http::response(['results' => [['resourceName' => 'customers/1234567890/adGroupCriteria/201~999']]]);
        }
        if ($collection === 'conversionGoalCampaignConfigs' && $this->rejectConfig) {
            return Http::response(['error' => ['message' => 'Config refused']], 400);
        }
        if ($collection === 'adGroupAds' && $this->rejectAd) {
            return Http::response(['error' => ['message' => 'Ad refused']], 400);
        }
        if ($collection === 'ads' && $this->rejectAdUrls) {
            return Http::response(['error' => ['message' => 'Ad URL refused']], 400);
        }
        if ($collection === 'adGroups' && $this->rejectAdGroup) {
            return Http::response(['error' => ['message' => 'Ad group refused']], 400);
        }
        $results = [];
        foreach ($request['operations'] as $operation) {
            if (isset($operation['remove'])) {
                if ($this->rejectCleanup) {
                    return Http::response(['error' => ['message' => 'Cleanup refused']], 400);
                }
                $id = basename($operation['remove']);
                if ($collection === 'campaigns') {
                    unset($this->campaigns[$id]);
                } elseif ($collection === 'campaignBudgets') {
                    unset($this->budgets[$id]);
                } elseif ($collection === 'adGroups') {
                    unset($this->groups[$id]);
                } elseif ($collection === 'assetGroups') {
                    unset($this->assetGroups[$id]);
                } elseif ($collection === 'adGroupAds') {
                    unset($this->ads[explode('~', $id)[1]]);
                } elseif (in_array($collection, ['adGroupCriteria', 'campaignCriteria'], true)) {
                    [$parent] = explode('~', $id);
                    $scope = $collection === 'adGroupCriteria' ? 'ad_group' : 'campaign';
                    $this->criteria[$scope][$parent] = array_values(array_filter(
                        $this->criteria[$scope][$parent], fn (array $criterion): bool => $criterion['resourceName'] !== $operation['remove'],
                    ));
                }
                $results[] = ['resourceName' => $operation['remove']];

                continue;
            }
            $payload = $operation['update'] ?? $operation['create'];
            if ($collection === 'campaigns' && isset($operation['create'])
                && $payload['advertisingChannelType'] !== 'PERFORMANCE_MAX' && array_key_exists('brandGuidelinesEnabled', $payload)) {
                return Http::response(['error' => ['message' => 'Brand guidelines are Performance Max only, even when false']], 400);
            }
            $resource = $payload['resourceName'] ?? "customers/1234567890/{$collection}/".match ($collection) {
                'campaigns' => '102', 'campaignBudgets' => '502', 'adGroups' => '202', 'adGroupAds' => basename($payload['adGroup']).'~302', default => '1',
            };
            $id = basename($resource);
            if ($collection === 'campaignConversionGoals') {
                [$campaignId, $category, $origin] = explode('~', $id);
                if (! $this->ignoreGoalMutation) {
                    $this->goals[$campaignId][$category.'~'.$origin] = $payload['biddable'];
                    $this->configs[$campaignId]['goalConfigLevel'] = 'CAMPAIGN';
                }
            } elseif ($collection === 'conversionGoalCampaignConfigs') {
                $this->configs[$id] = [...$this->configs[$id], ...array_diff_key($payload, ['resourceName' => true])];
            } elseif ($collection === 'campaigns') {
                $this->campaigns[$id] = [...($this->campaigns[$id] ?? []), ...$payload, 'id' => $id, 'resourceName' => $resource];
                if (! isset($operation['update'])) {
                    $this->campaigns[$id]['biddingStrategyType'] = isset($payload['maximizeConversions']) ? 'MAXIMIZE_CONVERSIONS' : 'MANUAL_CPC';
                    $this->configs[$id] = ['campaign' => $resource, 'goalConfigLevel' => 'CUSTOMER'];
                    $this->goals[$id] = ['PURCHASE~WEBSITE' => true, 'SIGNUP~WEBSITE' => false];
                    foreach ($this->criteria['campaign']['101'] ?? [] as $criterion) {
                        if (isset($criterion['device'])) {
                            $this->criteria['campaign'][$id][] = [...$criterion,
                                'resourceName' => "customers/1234567890/campaignCriteria/{$id}~".explode('~', $criterion['resourceName'])[1],
                                'bidModifier' => 1.0];
                        }
                    }
                }
                if ($this->mismatch && isset($payload['networkSettings'])) {
                    $this->campaigns[$id]['networkSettings']['targetSearchNetwork'] = false;
                }
            } elseif ($collection === 'campaignBudgets') {
                $this->budgets[$id] = [...$payload, 'resourceName' => $resource, 'referenceCount' => '1'];
            } elseif ($collection === 'adGroups') {
                if ($this->mismatchAdGroup && isset($payload['targetingSetting'])) {
                    $payload['targetingSetting'] = $this->groups[$id]['targetingSetting'];
                }
                $this->groups[$id] = [...($this->groups[$id] ?? []), ...$payload, 'resourceName' => $resource, 'id' => $id];
            } elseif ($collection === 'ads') {
                if (! $this->ignoreAdUrls) {
                    foreach (['responsiveSearchAd', 'responsiveDisplayAd'] as $block) {
                        if (isset($payload[$block])) {
                            $payload[$block] = [...($this->ads[$id]['ad'][$block] ?? []), ...$payload[$block]];
                        }
                    }
                    $this->ads[$id]['ad'] = [...$this->ads[$id]['ad'], ...array_diff_key($payload, ['resourceName' => true])];
                }
            } elseif ($collection === 'adGroupAds') {
                $payload['ad']['id'] = '302';
                if ($this->mismatchAd) {
                    $payload['ad']['finalUrls'] = ['https://wrong.example.com'];
                }
                if (isset($payload['ad']['imageAd']['adIdToCopyImageFrom'])) {
                    $payload['ad']['imageAd'] = ['imageUrl' => $this->ads['301']['ad']['imageAd']['imageUrl']];
                }
                $this->ads['302'] = $payload;
                if ($this->creativeMetadata) {
                    $this->ads['302']['ad']['responsiveSearchAd']['headlines'][0] += [
                        'assetPerformanceLabel' => 'PENDING', 'policySummaryInfo' => ['reviewStatus' => 'REVIEW_IN_PROGRESS'],
                    ];
                }
            } elseif (in_array($collection, ['adGroupCriteria', 'campaignCriteria'], true)) {
                $scope = $collection === 'adGroupCriteria' ? 'ad_group' : 'campaign';
                if (isset($operation['update'])) {
                    [$parent] = explode('~', $id);
                    foreach ($this->criteria[$scope][$parent] as &$criterion) {
                        if ($criterion['resourceName'] === $resource) {
                            $criterion = [...$criterion, ...$payload];
                        }
                    }
                    unset($criterion);
                    $results[] = ['resourceName' => $resource];

                    continue;
                }
                $parent = basename($payload[$scope === 'campaign' ? 'campaign' : 'adGroup']);
                $blocks = ['keyword' => 'KEYWORD', 'placement' => 'PLACEMENT', 'mobileApplication' => 'MOBILE_APPLICATION',
                    'topic' => 'TOPIC', 'userList' => 'USER_LIST', 'parentalStatus' => 'PARENTAL_STATUS', 'incomeRange' => 'INCOME_RANGE', 'location' => 'LOCATION'];
                $type = array_intersect_key($blocks, $payload);
                $this->criteria[$scope][$parent][] = ['status' => 'ENABLED', ...$payload, 'type' => reset($type),
                    'resourceName' => "customers/1234567890/{$collection}/{$parent}~".(900 + count($this->criteria[$scope][$parent] ?? []))];
            } elseif (in_array($collection, ['campaignAssets', 'campaignSharedSets'], true)) {
                $parent = basename($payload['campaign']);
                if ($collection === 'campaignAssets') {
                    $this->campaignAssets[$parent][] = $payload;
                } else {
                    $this->sharedSets[$parent][] = $payload;
                }
            } elseif (in_array($collection, ['campaignAssetSets', 'adGroupAssets', 'adGroupAssetSets'], true)) {
                $native = match ($collection) {
                    'campaignAssetSets' => 'campaign_asset_set', 'adGroupAssets' => 'ad_group_asset', default => 'ad_group_asset_set',
                };
                $parent = basename($payload[$collection === 'campaignAssetSets' ? 'campaign' : 'adGroup']);
                $this->nativeLinks[$native][$parent][] = $payload;
            } elseif ($collection === 'adGroupBidModifiers') {
                [$parent, $criterion] = explode('~', $id);
                $device = match ($criterion) {
                    '30000' => 'DESKTOP', '30001' => 'MOBILE', default => 'TABLET',
                };
                $this->groupModifiers[$parent][$device] = $payload['bidModifier'] ?? null;
            } else {
                throw new RuntimeException('Unexpected Google test mutation: '.$collection);
            }
            $results[] = ['resourceName' => $resource];
        }

        return Http::response(['results' => $results]);
    }

    private function entity(string $type = 'campaign'): CampaignPlatformEntity
    {
        return $this->campaign->platformEntities()->where('entity_type', $type)->sole()->setRelation('campaign', $this->campaign);
    }

    /** @param array<string, mixed> $patch */
    private function apply(array $patch, string $type = 'campaign'): CampaignEntityEdit
    {
        $editor = app(EntityEditor::class);
        $edit = $editor->propose($this->campaign, $this->entity($type), $this->campaign->user, $patch);

        return $editor->apply($edit, $this->campaign->user, acknowledged: true);
    }

    private function withDeviceAdjustments(): void
    {
        $this->criteria['campaign']['101'] = [
            ['resourceName' => 'customers/1234567890/campaignCriteria/101~30000', 'type' => 'DEVICE', 'status' => 'ENABLED', 'device' => ['type' => 'DESKTOP'], 'bidModifier' => 1.2],
            ['resourceName' => 'customers/1234567890/campaignCriteria/101~30001', 'type' => 'DEVICE', 'status' => 'ENABLED', 'device' => ['type' => 'MOBILE'], 'bidModifier' => 1.0],
        ];
        app(CampaignSynchronizer::class)->sync($this->campaign);
    }

    public function test_ad_urls_change_only_requested_fields_and_preserve_other_tracking(): void
    {
        $urls = ['finalUrls' => ['https://example.com/new'], 'trackingUrlTemplate' => '', 'finalUrlSuffix' => 'ad=1'];
        $edit = app(EntityEditor::class)->propose($this->campaign, $this->entity('ad'), $this->campaign->user, ['ad_urls' => $urls]);
        try {
            app(EntityEditor::class)->apply($edit, $this->campaign->user);
            $this->fail('Ad URL changes require acknowledgement.');
        } catch (EditRefused $exception) {
            $this->assertStringContainsString('acknowledged', $exception->getMessage());
        }

        $edit = app(EntityEditor::class)->apply($edit, $this->campaign->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['https://m.example.com'], $this->ads['301']['ad']['finalMobileUrls']);
        $this->assertSame([['key' => 'source', 'value' => 'ad']], $this->ads['301']['ad']['urlCustomParameters']);
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/ads:mutate')
            && $request['operations'][0]['updateMask'] === 'finalUrls,trackingUrlTemplate'
            && $request['operations'][0]['update'] === [
                'resourceName' => 'customers/1234567890/ads/301',
                'finalUrls' => ['https://example.com/new'], 'trackingUrlTemplate' => '',
            ]);
    }

    public function test_shared_ad_url_changes_are_refused_before_mutation(): void
    {
        $this->sharedAd = true;
        $edit = $this->apply(['ad_urls' => [
            'finalUrls' => ['https://example.com/new'],
            'trackingUrlTemplate' => 'https://example.com/ad?url={lpurl}', 'finalUrlSuffix' => 'ad=1',
        ]], 'ad');

        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertStringContainsString('shared', $edit->error);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/ads:mutate'));
    }

    public function test_ad_url_validation_and_stale_baseline_prevent_mutation(): void
    {
        $editor = app(EntityEditor::class);
        $urls = ['finalUrls' => ['not-a-url'], 'trackingUrlTemplate' => '', 'finalUrlSuffix' => ''];
        try {
            $editor->propose($this->campaign, $this->entity('ad'), $this->campaign->user, ['ad_urls' => $urls]);
            $this->fail('Invalid landing URL was accepted.');
        } catch (ValidationException $exception) {
            $this->assertArrayHasKey('ad_urls', $exception->errors());
        }
        $urls['finalUrls'] = ['https://example.com/new'];
        $edit = $editor->propose($this->campaign, $this->entity('ad'), $this->campaign->user, ['ad_urls' => $urls]);
        $this->ads['301']['ad']['finalUrlSuffix'] = 'changed=1';

        $this->assertSame(CampaignEntityEdit::Stale, $editor->apply($edit, $this->campaign->user, acknowledged: true)->state);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/ads:mutate'));
    }

    public function test_display_ad_url_failure_and_unconfirmed_readback_are_not_applied(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        $this->ads['301']['ad']['type'] = 'RESPONSIVE_DISPLAY_AD';
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $urls = ['finalUrls' => ['https://example.com/new'], 'trackingUrlTemplate' => '', 'finalUrlSuffix' => 'new=1'];
        $this->rejectAdUrls = true;

        $edit = $this->apply(['ad_urls' => $urls], 'ad');

        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertStringContainsString('Ad URL refused', $edit->error);
        $this->rejectAdUrls = false;
        $this->ignoreAdUrls = true;
        $edit = $this->apply(['ad_urls' => $urls], 'ad');
        $this->assertSame(CampaignEntityEdit::Unconfirmed, $edit->state);
        $this->assertSame(['https://example.com'], $this->ads['301']['ad']['finalUrls']);
    }

    public function test_display_ad_url_form_saves_supported_changes(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        $this->ads['301']['ad']['type'] = 'RESPONSIVE_DISPLAY_AD';
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $entity = $this->entity('ad');

        Livewire::actingAs($this->campaign->user)
            ->test(EditEntity::class, ['campaign' => $this->campaign, 'entity' => $entity])
            ->set('values.ad_urls', '{"finalUrls":["https://example.com/new"],"trackingUrlTemplate":"","finalUrlSuffix":"new=1"}')
            ->call('review')
            ->assertSee('Ad landing and tracking URLs');

        $edit = $entity->edits()->latest('id')->firstOrFail();
        $edit = app(EntityEditor::class)->apply($edit, $this->campaign->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('new=1', $this->ads['301']['ad']['finalUrlSuffix']);
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/ads:mutate'));
    }

    public function test_ad_url_edits_require_creative_gate_and_supported_complete_baseline(): void
    {
        config(['campaign-manager.edit_categories' => ['name', 'targeting']]);
        $this->assertNotContains('ad_urls', app(EditCapabilities::class)->editableFields($this->entity('ad')));
        config(['campaign-manager.edit_categories' => ['creative']]);
        $this->ads['301']['ad']['type'] = 'IMAGE_AD';
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $this->assertNotContains('ad_urls', app(EditCapabilities::class)->editableFields($this->entity('ad')));
        $this->ads['301']['ad']['type'] = 'RESPONSIVE_SEARCH_AD';
        unset($this->ads['301']['ad']['finalUrls']);
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $this->assertNotContains('ad_urls', app(EditCapabilities::class)->editableFields($this->entity('ad')));
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_search_ad_text_changes_preserve_pins_and_untouched_creative(): void
    {
        $headlines = [['text' => 'One', 'pinnedField' => 'HEADLINE_1'], ['text' => 'Changed'], ['text' => 'Three']];

        $edit = $this->apply(['ad_headlines' => $headlines], 'ad');

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame([['text' => 'A description']], $this->ads['301']['ad']['responsiveSearchAd']['descriptions']);
        $this->assertSame('offer', $this->ads['301']['ad']['responsiveSearchAd']['path1']);
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/ads:mutate')
            && $request['operations'][0]['updateMask'] === 'responsiveSearchAd.headlines'
            && data_get($request['operations'], '0.update.responsiveSearchAd.headlines.0.pinnedField') === 'HEADLINE_1'
            && data_get($request['operations'], '0.update.responsiveSearchAd.headlines.1.text') === 'Changed');
    }

    public function test_display_ad_text_and_urls_change_together(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        $this->ads['301']['ad']['type'] = 'RESPONSIVE_DISPLAY_AD';
        $this->ads['301']['ad']['responsiveDisplayAd'] = [
            'headlines' => [['text' => 'Original']],
            'descriptions' => [['text' => 'Old description']],
            'longHeadline' => ['text' => 'Keep long headline'],
        ];
        app(CampaignSynchronizer::class)->sync($this->campaign);

        $edit = $this->apply([
            'ad_descriptions' => [['text' => 'New description']],
            'ad_urls' => ['finalUrls' => ['https://example.com/new'], 'trackingUrlTemplate' => 'https://example.com/ad?url={lpurl}', 'finalUrlSuffix' => 'ad=1'],
        ], 'ad');

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['text' => 'Keep long headline'], $this->ads['301']['ad']['responsiveDisplayAd']['longHeadline']);
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/ads:mutate')
            && $request['operations'][0]['updateMask'] === 'finalUrls,responsiveDisplayAd.descriptions');
    }

    public function test_ad_text_rejects_invalid_pins_and_counts_and_locks_unknown_assets(): void
    {
        foreach ([
            [['text' => 'Too few']],
            [['text' => 'One', 'pinnedField' => 'DESCRIPTION_1'], ['text' => 'Two'], ['text' => 'Three']],
            [['text' => 'Same'], ['text' => 'Same'], ['text' => 'Three']],
            [['text' => 'One', 'pinnedField' => 'HEADLINE_1'], ['text' => 'Two', 'pinnedField' => 'HEADLINE_1'], ['text' => 'Three', 'pinnedField' => 'HEADLINE_1']],
        ] as $headlines) {
            try {
                app(EntityEditor::class)->propose($this->campaign, $this->entity('ad'), $this->campaign->user, ['ad_headlines' => $headlines]);
                $this->fail('Invalid headlines were accepted.');
            } catch (ValidationException $exception) {
                $this->assertArrayHasKey('ad_headlines', $exception->errors());
            }
        }
        $this->ads['301']['ad']['responsiveSearchAd']['headlines'][0]['pinnedField'] = 'UNKNOWN';
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $this->assertNotContains('ad_headlines', app(EditCapabilities::class)->editableFields($this->entity('ad')));
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_search_ad_path_changes_preserve_unedited_text_and_require_first_path(): void
    {
        try {
            app(EntityEditor::class)->propose($this->campaign, $this->entity('ad'), $this->campaign->user, [
                'ad_search_path' => ['path1' => '', 'path2' => 'deals'],
            ]);
            $this->fail('A second path without the first was accepted.');
        } catch (ValidationException $exception) {
            $this->assertArrayHasKey('ad_search_path', $exception->errors());
        }

        $edit = $this->apply(['ad_search_path' => ['path1' => 'offer', 'path2' => 'deals']], 'ad');

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('HEADLINE_1', $this->ads['301']['ad']['responsiveSearchAd']['headlines'][0]['pinnedField']);
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/ads:mutate')
            && $request['operations'][0]['updateMask'] === 'responsiveSearchAd.path2'
            && data_get($request['operations'], '0.update.responsiveSearchAd.path2') === 'deals');
    }

    public function test_ad_creative_and_status_must_be_reviewed_separately(): void
    {
        config(['campaign-manager.edit_categories' => ['creative', 'status']]);
        try {
            app(EntityEditor::class)->propose($this->campaign, $this->entity('ad'), $this->campaign->user, [
                'ad_headlines' => [['text' => 'One'], ['text' => 'Two'], ['text' => 'New']],
                'status' => 'PAUSED',
            ]);
            $this->fail('A mixed ad creative and status change was accepted.');
        } catch (EditRefused $exception) {
            $this->assertStringContainsString('separately', $exception->getMessage());
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_ad_text_stale_shared_and_unconfirmed_changes_are_not_applied(): void
    {
        $headlines = [['text' => 'One', 'pinnedField' => 'HEADLINE_1'], ['text' => 'Changed'], ['text' => 'Three']];
        $editor = app(EntityEditor::class);
        $edit = $editor->propose($this->campaign, $this->entity('ad'), $this->campaign->user, ['ad_headlines' => $headlines]);
        $this->ads['301']['ad']['responsiveSearchAd']['headlines'][2]['text'] = 'Changed elsewhere';
        $this->assertSame(CampaignEntityEdit::Stale, $editor->apply($edit, $this->campaign->user, acknowledged: true)->state);

        $this->sharedAd = true;
        $edit = $this->apply(['ad_headlines' => $headlines], 'ad');
        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/ads:mutate'));

        $this->sharedAd = false;
        $this->ignoreAdUrls = true;
        $this->assertSame(CampaignEntityEdit::Unconfirmed, $this->apply(['ad_headlines' => $headlines], 'ad')->state);
    }

    public function test_device_adjustments_are_reviewed_and_update_only_changed_existing_criteria(): void
    {
        $this->withDeviceAdjustments();
        $editor = app(EntityEditor::class);
        $edit = $editor->propose($this->campaign, $this->entity(), $this->campaign->user, [
            'device_bid_adjustments' => ['DESKTOP' => 1.2, 'MOBILE' => 0.8],
        ]);
        try {
            $editor->apply($edit, $this->campaign->user);
            $this->fail('Device changes require acknowledgement.');
        } catch (EditRefused $exception) {
            $this->assertStringContainsString('acknowledged', $exception->getMessage());
        }

        $edit = $editor->apply($edit, $this->campaign->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['DESKTOP' => 1.2, 'MOBILE' => 0.8], data_get($this->entity()->settings, 'device_bid_adjustments'));
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), 'campaignCriteria:mutate')
            && $request['partialFailure'] === false
            && $request['operations'] === [[
                'update' => ['resourceName' => 'customers/1234567890/campaignCriteria/101~30001', 'bidModifier' => 0.8],
                'updateMask' => 'bid_modifier',
            ]]);
    }

    public function test_invalid_or_mixed_device_adjustments_are_refused(): void
    {
        $this->withDeviceAdjustments();
        config(['campaign-manager.edit_categories' => ['targeting', 'bid_strategy']]);
        foreach ([
            ['device_bid_adjustments' => ['MOBILE' => 0.8]],
            ['device_bid_adjustments' => ['DESKTOP' => 1.2, 'MOBILE' => 0.05]],
            ['device_bid_adjustments' => ['DESKTOP' => 1.2, 'MOBILE' => 11]],
            ['device_bid_adjustments' => ['DESKTOP' => 1.2, 'MOBILE' => 0], 'device_exclusions' => ['MOBILE']],
            ['device_bid_adjustments' => ['DESKTOP' => 1.2, 'MOBILE' => 0.8], 'bid_strategy' => 'MAXIMIZE_CONVERSIONS'],
        ] as $patch) {
            try {
                app(EntityEditor::class)->propose($this->campaign, $this->entity(), $this->campaign->user, $patch);
                $this->fail('Invalid device adjustments were accepted.');
            } catch (ValidationException $exception) {
                $this->assertArrayHasKey('device_bid_adjustments', $exception->errors());
            }
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_device_adjustments_lock_on_unsupported_or_incomplete_baselines(): void
    {
        $this->withDeviceAdjustments();
        $original = $this->criteria['campaign']['101'];
        foreach ([
            [$original[0], $original[0]],
            [[...$original[0], 'bidModifier' => null]],
            [[...$original[0], 'status' => 'PAUSED']],
        ] as $criteria) {
            $this->criteria['campaign']['101'] = $criteria;
            app(CampaignSynchronizer::class)->sync($this->campaign);
            $this->assertNotContains('device_bid_adjustments', app(EditCapabilities::class)->editableFields($this->entity()));
        }
        $this->criteria['campaign']['101'] = $original;
        $this->campaigns['101']['biddingStrategyType'] = 'MAXIMIZE_CONVERSIONS';
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $this->assertNotContains('device_bid_adjustments', app(EditCapabilities::class)->editableFields($this->entity()));
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_device_write_treats_an_omitted_modifier_as_neutral_without_touching_exclusions(): void
    {
        $this->withDeviceAdjustments();
        unset($this->criteria['campaign']['101'][1]['bidModifier']);
        $this->criteria['campaign']['101'][] = [
            'resourceName' => 'customers/1234567890/campaignCriteria/101~30002',
            'type' => 'DEVICE', 'status' => 'ENABLED', 'device' => ['type' => 'TABLET'], 'bidModifier' => 0.0,
        ];
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $edit = $this->apply(['device_bid_adjustments' => ['DESKTOP' => 1.2, 'MOBILE' => 0.8, 'TABLET' => 0.0]]);
        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(0.0, $this->criteria['campaign']['101'][2]['bidModifier']);
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), 'campaignCriteria:mutate')
            && $request['operations'] === [[
                'update' => ['resourceName' => 'customers/1234567890/campaignCriteria/101~30001', 'bidModifier' => 0.8],
                'updateMask' => 'bid_modifier',
            ]]);
    }

    public function test_device_adjustments_detect_stale_baselines_and_unconfirmed_readback(): void
    {
        $this->withDeviceAdjustments();
        $editor = app(EntityEditor::class);
        $patch = ['device_bid_adjustments' => ['DESKTOP' => 1.2, 'MOBILE' => 0.8]];
        $edit = $editor->propose($this->campaign, $this->entity(), $this->campaign->user, $patch);
        $this->criteria['campaign']['101'][0]['bidModifier'] = 1.5;

        $this->assertSame(CampaignEntityEdit::Stale, $editor->apply($edit, $this->campaign->user, acknowledged: true)->state);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));

        $this->ignoreCriteriaMutation = true;
        $patch['device_bid_adjustments']['DESKTOP'] = 1.5;
        $edit = $this->apply($patch);

        $this->assertSame(CampaignEntityEdit::Unconfirmed, $edit->state);
        $this->assertSame(1.0, $this->criteria['campaign']['101'][1]['bidModifier']);
    }

    public function test_display_device_adjustment_can_exclude_and_restore_a_device(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        $this->withDeviceAdjustments();

        Livewire::actingAs($this->campaign->user)
            ->test(EditEntity::class, ['campaign' => $this->campaign, 'entity' => $this->entity()])
            ->set('values.device_bid_adjustments', '{"DESKTOP":1.2,"MOBILE":0}')
            ->call('review')
            ->assertSee('Device bid adjustments');

        $edit = $this->entity()->edits()->latest('id')->firstOrFail();
        $this->assertSame(CampaignEntityEdit::Applied, app(EntityEditor::class)->apply($edit, $this->campaign->user, acknowledged: true)->state);
        $this->assertSame(['MOBILE'], data_get($this->entity()->settings, 'device_exclusions'));
        $this->assertSame(CampaignEntityEdit::Applied, $this->apply(['device_bid_adjustments' => ['DESKTOP' => 1.2, 'MOBILE' => 1]])->state);
        $this->assertSame([], data_get($this->entity()->settings, 'device_exclusions'));
    }

    public function test_device_adjustment_rejection_is_not_reported_as_applied(): void
    {
        $this->withDeviceAdjustments();
        $this->rejectCriteria = true;

        $edit = $this->apply(['device_bid_adjustments' => ['DESKTOP' => 1.2, 'MOBILE' => 0.8]]);

        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertStringContainsString('Criteria refused', $edit->error);
        $this->assertSame(1.0, $this->criteria['campaign']['101'][1]['bidModifier']);
    }

    public function test_native_network_and_geographic_intent_are_read_reviewed_written_and_confirmed(): void
    {
        $edit = $this->apply(['network_settings' => ['targetSearchNetwork' => true], 'geo_target_type' => [
            'positiveGeoTargetType' => 'PRESENCE', 'negativeGeoTargetType' => 'PRESENCE',
        ]]);
        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertTrue($this->campaigns['101']['networkSettings']['targetGoogleSearch']);
        $this->assertTrue($this->campaigns['101']['networkSettings']['targetSearchNetwork']);
        $this->assertSame('PRESENCE', $this->campaigns['101']['geoTargetTypeSetting']['positiveGeoTargetType']);
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), 'campaigns:mutate')
            && str_contains($request['operations'][0]['updateMask'], 'networkSettings.targetSearchNetwork'));
    }

    public function test_network_readback_mismatch_is_unconfirmed(): void
    {
        $this->mismatch = true;
        $this->assertSame(CampaignEntityEdit::Unconfirmed, $this->apply(['network_settings' => ['targetSearchNetwork' => true]])->state);
    }

    public function test_goals_select_category_and_origin_and_can_restore_account_defaults(): void
    {
        $selection = ['level' => 'CAMPAIGN', 'goals' => [['category' => 'SIGNUP', 'origin' => 'WEBSITE']]];
        $edit = $this->apply(['conversion_goals' => $selection]);
        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['PURCHASE~WEBSITE' => false, 'SIGNUP~WEBSITE' => true], $this->goals['101']);
        $this->assertSame(CampaignEntityEdit::Applied, $this->apply(['conversion_goals' => ['level' => 'CUSTOMER']])->state);
        $this->assertSame('CUSTOMER', $this->configs['101']['goalConfigLevel']);
        foreach (Http::recorded() as [$request]) {
            if (preg_match('~/(campaignConversionGoals|conversionGoalCampaignConfigs):mutate$~', $request->url())) {
                $this->assertArrayNotHasKey('partialFailure', $request->data());
            }
        }
    }

    public function test_chat_reads_approves_and_writes_published_google_goals(): void
    {
        $this->actingAs($this->campaign->user);
        $workspace = app(Workspace::class);
        $workspace->bindTo('google-goal-edit');
        $workspace->ownedBy($this->campaign->user);
        $workspace->produced($this->campaign);
        $workspace->focusOn($this->campaign);
        $tool = new NamespacedTool('campaign', app(EditGoogleConversionGoals::class));

        $read = json_decode((string) $tool->handle(new ToolRequest(['campaign_id' => '101'], 'goal-read')), true, flags: JSON_THROW_ON_ERROR);
        $this->assertTrue($read['ok']);
        $this->assertSame(['PURCHASE~WEBSITE'], $read['effective']);
        $this->assertContains('SIGNUP~WEBSITE', $read['available']);
        $this->assertSame('Purchase', $read['conversion_actions'][0]['name']);

        $request = new ToolRequest(['campaign_id' => '101', 'level' => 'CAMPAIGN', 'goal_keys' => ['SIGNUP~WEBSITE']], 'goal-write');
        $this->assertNotNull($tool->shouldRequestApproval($request));
        $result = json_decode((string) $tool->handle($request), true, flags: JSON_THROW_ON_ERROR);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['verified']);
        $this->assertSame(['SIGNUP~WEBSITE'], $result['after']['effective']);
        $this->assertSame(['PURCHASE~WEBSITE' => false, 'SIGNUP~WEBSITE' => true], $this->goals['101']);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), 'conversionGoalCampaignConfigs:mutate'));
        $restore = new ToolRequest(['campaign_id' => '101', 'level' => 'CUSTOMER'], 'goal-restore');
        $this->assertNotNull($tool->shouldRequestApproval($restore));
        $restored = json_decode((string) $tool->handle($restore), true, flags: JSON_THROW_ON_ERROR);
        $this->assertTrue($restored['ok'], $restored['error'] ?? '');
        $this->assertSame('CUSTOMER', $this->configs['101']['goalConfigLevel']);
    }

    public function test_chat_refuses_stale_goals_and_published_draft_selector(): void
    {
        $this->actingAs($this->campaign->user);
        $workspace = app(Workspace::class);
        $workspace->bindTo('google-goal-stale');
        $workspace->ownedBy($this->campaign->user);
        $workspace->produced($this->campaign);
        $workspace->focusOn($this->campaign);
        $tool = new NamespacedTool('campaign', app(EditGoogleConversionGoals::class));
        $request = new ToolRequest(['campaign_id' => '101', 'level' => 'CAMPAIGN', 'goal_keys' => ['SIGNUP~WEBSITE']], 'stale-goals');
        $this->assertNotNull($tool->shouldRequestApproval($request));
        $this->goals['101']['PURCHASE~WEBSITE'] = false;
        $result = json_decode((string) $tool->handle($request), true, flags: JSON_THROW_ON_ERROR);
        $this->assertFalse($result['ok']);
        $this->assertFalse($result['reconciliation_required']);
        $draft = json_decode((string) app(ChoosePixel::class)->handle(new ToolRequest(['pixel_id' => 'customers/1234567890/conversionActions/1'], 'draft')), true, flags: JSON_THROW_ON_ERROR);
        $this->assertFalse($draft['ok']);
        $this->assertStringContainsString('published Google campaign', $draft['error']);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_chat_refuses_unknown_and_custom_conversion_goals(): void
    {
        $this->actingAs($this->campaign->user);
        $workspace = app(Workspace::class);
        $workspace->bindTo('google-goal-invalid');
        $workspace->ownedBy($this->campaign->user);
        $workspace->produced($this->campaign);
        $workspace->focusOn($this->campaign);
        $tool = new NamespacedTool('campaign', app(EditGoogleConversionGoals::class));
        $unknown = new ToolRequest(['campaign_id' => '101', 'level' => 'CAMPAIGN', 'goal_keys' => ['PURCHASE~STORE']], 'unknown-goal');
        $this->assertNull($tool->shouldRequestApproval($unknown));
        $this->configs['101']['goalConfigLevel'] = 'CAMPAIGN';
        $this->configs['101']['customConversionGoal'] = 'customers/1234567890/customConversionGoals/701';
        $custom = new ToolRequest(['campaign_id' => '101', 'level' => 'CUSTOMER'], 'custom-goal');
        $this->assertNull($tool->shouldRequestApproval($custom));
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_chat_reports_unconfirmed_goal_writes_for_reconciliation(): void
    {
        $this->actingAs($this->campaign->user);
        $workspace = app(Workspace::class);
        $workspace->bindTo('google-goal-unconfirmed');
        $workspace->ownedBy($this->campaign->user);
        $workspace->produced($this->campaign);
        $workspace->focusOn($this->campaign);
        $tool = new NamespacedTool('campaign', app(EditGoogleConversionGoals::class));
        $request = new ToolRequest(['campaign_id' => '101', 'level' => 'CAMPAIGN', 'goal_keys' => ['SIGNUP~WEBSITE']], 'unconfirmed-goals');
        $this->assertNotNull($tool->shouldRequestApproval($request));
        $this->ignoreGoalMutation = true;
        $result = json_decode((string) $tool->handle($request), true, flags: JSON_THROW_ON_ERROR);
        $this->assertFalse($result['ok']);
        $this->assertTrue($result['reconciliation_required']);
    }

    public function test_goal_update_rechecks_effective_account_defaults_before_writing(): void
    {
        $google = app(GoogleAdsService::class);
        $connection = GoogleAdsConnection::shared();
        $snapshot = $google->readManagerGoals($connection, '101');
        $this->goals['101']['PURCHASE~WEBSITE'] = false;
        try {
            $google->updateManagerGoals($connection, '101',
                ['level' => 'CAMPAIGN', 'goals' => [['category' => 'SIGNUP', 'origin' => 'WEBSITE']]],
                $snapshot['selection'], $snapshot);
            $this->fail('A changed account default was accepted.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('changed after review', $exception->getMessage());
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_enabled_native_custom_goal_can_be_selected_without_modifying_the_shared_goal(): void
    {
        $edit = $this->apply(['conversion_goals' => ['level' => 'CAMPAIGN', 'goals' => [], 'custom_goal' => 'customers/1234567890/customConversionGoals/701']]);
        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('customers/1234567890/customConversionGoals/701', $this->configs['101']['customConversionGoal']);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), 'customConversionGoals:mutate'));
    }

    public function test_goal_partial_failure_reads_back_the_new_campaign_goals(): void
    {
        $this->rejectConfig = true;
        $this->configs['101']['goalConfigLevel'] = 'CAMPAIGN';
        $this->configs['101']['customConversionGoal'] = 'customers/1234567890/customConversionGoals/701';
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $result = $this->apply(['conversion_goals' => ['level' => 'CAMPAIGN', 'goals' => [['category' => 'SIGNUP', 'origin' => 'WEBSITE']]]]);
        $this->assertSame(CampaignEntityEdit::Failed, $result->state);
        $this->assertStringContainsString('Config refused', $result->error);
        $this->assertStringContainsString('Partly applied', $result->error);
        $this->assertSame('CAMPAIGN', $this->configs['101']['goalConfigLevel']);
        $this->assertTrue($this->goals['101']['SIGNUP~WEBSITE']);
    }

    public function test_goal_permission_failure_locks_goals_and_campaign_copy_but_not_unrelated_fields(): void
    {
        $this->denyGoals = true;
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $this->assertNull($this->entity()->settings['conversion_goals']);
        $capabilities = app(EditCapabilities::class);
        $this->assertNotNull($capabilities->fieldRefusal($this->entity(), 'conversion_goals'));
        $this->assertNotNull($capabilities->actionRefusal($this->entity(), CampaignEntityEdit::Duplicate));
        $this->assertContains('name', $capabilities->editableFields($this->entity()));
    }

    public function test_unknown_goal_pairs_foreign_custom_goals_and_combined_edits_are_rejected_before_mutation(): void
    {
        foreach ([
            ['conversion_goals' => ['level' => 'CAMPAIGN', 'goals' => [['category' => 'SIGNUP', 'origin' => 'STORE']]]],
            ['conversion_goals' => ['level' => 'CAMPAIGN', 'goals' => [], 'custom_goal' => 'customers/999/customConversionGoals/1']],
            ['conversion_goals' => ['level' => 'CUSTOMER', 'goals' => []]],
            ['conversion_goals' => ['level' => 'CAMPAIGN', 'goals' => []], 'name' => 'Other'],
            ['network_settings' => ['inventedNetwork' => true]],
            ['network_settings' => ['targetGoogleSearch' => false]],
        ] as $patch) {
            try {
                app(EntityEditor::class)->propose($this->campaign, $this->entity(), $this->campaign->user, $patch);
                $this->fail('Accepted invalid native changes.');
            } catch (ValidationException $exception) {
                $this->assertNotEmpty($exception->errors());
            }
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_conversion_goal_wizard_shows_native_scope_and_requires_acknowledgement(): void
    {
        Livewire::actingAs($this->campaign->user)->test(EditEntity::class, ['campaign' => $this->campaign, 'entity' => $this->entity()])
            ->set('values.conversion_goals', json_encode(['level' => 'CAMPAIGN', 'goals' => [['category' => 'SIGNUP', 'origin' => 'WEBSITE']]]))
            ->call('review')->assertSee('Campaign overrides stop inheriting account defaults')
            ->call('confirm')->assertSee('acknowledged')
            ->set('acknowledged', true)->call('confirm')->assertSee('Done.');
    }

    public function test_campaign_copy_is_paused_uses_an_independent_budget_and_preserves_tracking_and_creatives(): void
    {
        $original = $this->campaigns['101'];
        $id = app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101');
        $this->assertSame('102', $id);
        $this->assertSame('PAUSED', $this->campaigns['102']['status']);
        $this->assertSame('customers/1234567890/campaignBudgets/502', $this->campaigns['102']['campaignBudget']);
        $this->assertSame($original['trackingUrlTemplate'], $this->campaigns['102']['trackingUrlTemplate']);
        $this->assertSame($original['urlCustomParameters'], $this->campaigns['102']['urlCustomParameters']);
        $this->assertSame($this->groups['201']['targetingSetting'], $this->groups['202']['targetingSetting']);
        $this->assertSame('PAUSED', $this->groups['202']['status']);
        $this->assertSame('PAUSED', $this->ads['302']['status']);
        foreach (['finalMobileUrls', 'trackingUrlTemplate', 'finalUrlSuffix', 'urlCustomParameters', 'responsiveSearchAd'] as $field) {
            $this->assertSame($this->ads['301']['ad'][$field], $this->ads['302']['ad'][$field]);
        }
        $this->assertSame($original, $this->campaigns['101']);
    }

    public function test_failed_campaign_copy_rolls_back_only_the_created_parent_and_budget(): void
    {
        $this->rejectAd = true;
        try {
            app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101');
            $this->fail('Incomplete campaign copy reported success.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('Incomplete copies were removed', $exception->getMessage());
        }
        $this->assertArrayNotHasKey('102', $this->campaigns);
        $this->assertArrayNotHasKey('502', $this->budgets);
        $this->assertArrayHasKey('101', $this->campaigns);
        $this->assertArrayHasKey('501', $this->budgets);
    }

    public function test_cleanup_failure_identifies_the_remaining_paused_resources(): void
    {
        $this->rejectAd = true;
        $this->rejectCleanup = true;
        $this->expectExceptionMessage('Cleanup is incomplete; PAUSED resources remain:');
        app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101');
    }

    public function test_campaign_copy_refuses_portfolio_bidding_and_expired_end_dates_before_writing(): void
    {
        $this->campaigns['101']['biddingStrategy'] = 'customers/1234567890/biddingStrategies/1';
        try {
            app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101');
            $this->fail('Copied shared portfolio bidding.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('Portfolio bidding', $exception->getMessage());
        }
        unset($this->campaigns['101']['biddingStrategy']);
        $this->campaigns['101']['endDateTime'] = now()->subDay()->format('Y-m-d H:i:s');
        try {
            app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101');
            $this->fail('Dropped an expired end date.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('expired', $exception->getMessage());
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_whole_campaign_copy_uses_google_adoption_for_the_original_owner(): void
    {
        $importer = Mockery::mock(CampaignImporter::class);
        $importer->shouldReceive('adoptGoogle')->once()->withArgs(fn (string $id, User $owner, string $account): bool => $id === '102' && $owner->id === $this->campaign->user_id && $account === '1234567890')
            ->andReturnUsing(fn (): Campaign => Campaign::create([
                'user_id' => $this->campaign->user_id, 'platform' => 'google', 'status' => 'published',
                'name' => $this->campaigns['102']['name'], 'external_campaign_id' => '102', 'ad_account_id' => '1234567890', 'currency' => 'USD',
            ]));
        $this->app->instance(CampaignImporter::class, $importer);
        $editor = app(EntityEditor::class);
        $edit = $editor->proposeAction($this->campaign, $this->entity(), $this->campaign->user, CampaignEntityEdit::Duplicate);
        $result = $editor->apply($edit, $this->campaign->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Applied, $result->state, (string) $result->error);
        $this->assertSame('google', Campaign::findOrFail($result->details['copy_campaign_id'])->platform);
    }

    public function test_empty_reporting_is_unknown_but_explicit_zero_rows_are_valid(): void
    {
        $this->reportRows = [];
        try {
            app(GoogleAdsService::class)->readLifetimeDelivery(GoogleAdsConnection::shared(), 'campaign', ['101']);
            $this->fail('Converted an empty report to zero.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('Unknown spend is not zero', $exception->getMessage());
        }
        $this->reportRows = [['campaign' => ['id' => '101'], 'metrics' => []]];
        $this->assertSame(['101' => ['spend' => 0.0, 'impressions' => 0]], app(GoogleAdsService::class)->readLifetimeDelivery(GoogleAdsConnection::shared(), 'campaign', ['101']));
    }

    public function test_keywords_are_changed_atomically_without_recreating_unchanged_criteria(): void
    {
        $this->criteria['ad_group']['201'] = [
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~11', 'type' => 'KEYWORD', 'status' => 'PAUSED',
                'negative' => false, 'keyword' => ['text' => 'insurance', 'matchType' => 'PHRASE']],
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~12', 'type' => 'KEYWORD', 'status' => 'ENABLED',
                'negative' => true, 'keyword' => ['text' => 'free', 'matchType' => 'BROAD']],
        ];
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $edit = $this->apply(['keywords' => [
            ['text' => ' INSURANCE ', 'match_type' => 'PHRASE', 'negative' => false],
            ['text' => 'cheap', 'match_type' => 'EXACT', 'negative' => true],
        ]], 'ad_group');
        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('customers/1234567890/adGroupCriteria/201~11', $this->criteria['ad_group']['201'][0]['resourceName']);
        $this->assertSame('PAUSED', $this->criteria['ad_group']['201'][0]['status']);
        $requests = Http::recorded(fn (Request $request): bool => str_contains($request->url(), 'adGroupCriteria:mutate'))->values();
        $this->assertCount(1, $requests);
        $this->assertFalse($requests[0][0]['partialFailure']);
        $this->assertSame('customers/1234567890/adGroupCriteria/201~12', $requests[0][0]['operations'][0]['remove']);
        $this->assertTrue($requests[0][0]['operations'][1]['create']['negative']);
    }

    public function test_audience_mode_changes_preserve_other_targeting_restrictions_and_are_read_back(): void
    {
        $this->groups['201']['targetingSetting']['targetRestrictions'][] = ['targetingDimension' => 'TOPIC', 'bidOnly' => false];
        app(CampaignSynchronizer::class)->sync($this->campaign);

        $edit = $this->apply(['audience_mode' => 'TARGETING'], 'ad_group');

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('TARGETING', data_get($this->entity('ad_group')->settings, 'audience_mode'));
        $requests = Http::recorded(fn (Request $request): bool => str_contains($request->url(), 'adGroups:mutate'))->values();
        $this->assertCount(1, $requests);
        $operation = $requests[0][0]['operations'][0];
        $this->assertSame('targeting_setting.target_restrictions', $operation['updateMask']);
        $this->assertSame([
            ['bidOnly' => false, 'targetingDimension' => 'AUDIENCE'],
            ['bidOnly' => false, 'targetingDimension' => 'TOPIC'],
        ], $operation['update']['targetingSetting']['targetRestrictions']);

        $edit = $this->apply(['audience_mode' => 'OBSERVATION'], 'ad_group');

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('OBSERVATION', data_get($this->entity('ad_group')->settings, 'audience_mode'));
        $this->assertSame(['bidOnly' => false, 'targetingDimension' => 'TOPIC'], $this->groups['201']['targetingSetting']['targetRestrictions'][1]);
    }

    public function test_parental_and_income_demographics_preserve_existing_criteria_and_read_back(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        $this->criteria['ad_group']['201'] = [[
            'resourceName' => 'customers/1234567890/adGroupCriteria/201~11',
            'adGroup' => 'customers/1234567890/adGroups/201',
            'status' => 'ENABLED', 'type' => 'PARENTAL_STATUS', 'parentalStatus' => ['type' => 'PARENT'],
        ]];
        app(CampaignSynchronizer::class)->sync($this->campaign);

        $edit = $this->apply(['audience_criteria' => [
            ['type' => 'PARENTAL_STATUS', 'parentalStatus' => ['type' => 'PARENT'], 'negative' => false],
            ['type' => 'INCOME_RANGE', 'incomeRange' => ['type' => 'INCOME_RANGE_0_50'], 'negative' => true],
        ]], 'ad_group');

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('customers/1234567890/adGroupCriteria/201~11', $this->criteria['ad_group']['201'][0]['resourceName']);
        $this->assertSame('OBSERVATION', data_get($this->entity('ad_group')->settings, 'audience_mode'));
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), 'adGroupCriteria:mutate')
            && $request['partialFailure'] === false && count($request['operations']) === 1
            && data_get($request['operations'], '0.create.incomeRange.type') === 'INCOME_RANGE_0_50'
            && data_get($request['operations'], '0.create.negative') === true);
    }

    public function test_invalid_or_duplicate_demographics_are_rejected(): void
    {
        $parent = ['type' => 'PARENTAL_STATUS', 'parentalStatus' => ['type' => 'PARENT'], 'negative' => false];
        foreach ([
            [['type' => 'INCOME_RANGE', 'incomeRange' => ['type' => 'UNKNOWN']]],
            [['type' => 'PARENTAL_STATUS', 'parentalStatus' => ['type' => 'UNKNOWN']]],
            [$parent, $parent],
        ] as $criteria) {
            try {
                app(EntityEditor::class)->propose($this->campaign, $this->entity('ad_group'), $this->campaign->user, ['audience_criteria' => $criteria]);
                $this->fail('Invalid demographics were accepted.');
            } catch (ValidationException $exception) {
                $this->assertArrayHasKey('audience_criteria', $exception->errors());
            }
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_parental_demographics_are_stale_if_the_native_criterion_changes(): void
    {
        $this->criteria['ad_group']['201'] = [[
            'resourceName' => 'customers/1234567890/adGroupCriteria/201~11',
            'adGroup' => 'customers/1234567890/adGroups/201',
            'status' => 'ENABLED', 'type' => 'PARENTAL_STATUS', 'parentalStatus' => ['type' => 'PARENT'],
        ]];
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $editor = app(EntityEditor::class);
        $edit = $editor->propose($this->campaign, $this->entity('ad_group'), $this->campaign->user, ['audience_criteria' => []]);
        $this->criteria['ad_group']['201'][0]['parentalStatus']['type'] = 'NOT_A_PARENT';

        $this->assertSame(CampaignEntityEdit::Stale, $editor->apply($edit, $this->campaign->user, acknowledged: true)->state);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_incomplete_or_duplicate_audience_restrictions_cannot_be_edited(): void
    {
        foreach ([
            null,
            [],
            [['targetingDimension' => 'AUDIENCE', 'bidOnly' => true], ['targetingDimension' => 'AUDIENCE', 'bidOnly' => false]],
            [['targetingDimension' => 'AUDIENCE', 'bidOnly' => 'false']],
        ] as $restrictions) {
            $this->groups['201']['targetingSetting']['targetRestrictions'] = $restrictions;
            app(CampaignSynchronizer::class)->sync($this->campaign);
            $this->assertNotContains('audience_mode', app(EditCapabilities::class)->editableFields($this->entity('ad_group')));
        }

        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_display_audience_mode_can_be_reviewed_and_requires_acknowledgement(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $entity = $this->entity('ad_group');

        Livewire::actingAs($this->campaign->user)
            ->test(EditEntity::class, ['campaign' => $this->campaign, 'entity' => $entity])
            ->set('values.audience_mode', 'TARGETING')
            ->call('review')
            ->assertSee('Observation')
            ->assertSee('Targeting');

        $edit = $entity->edits()->latest('id')->firstOrFail();
        try {
            app(EntityEditor::class)->apply($edit, $this->campaign->user);
            $this->fail('A reach-changing edit was accepted without acknowledgement.');
        } catch (EditRefused $exception) {
            $this->assertStringContainsString('acknowledged', $exception->getMessage());
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));

        $edit = app(EntityEditor::class)->apply($edit, $this->campaign->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('TARGETING', data_get($this->entity('ad_group')->settings, 'audience_mode'));
    }

    public function test_invalid_audience_mode_is_rejected_without_mutation(): void
    {
        try {
            app(EntityEditor::class)->propose($this->campaign, $this->entity('ad_group'), $this->campaign->user, ['audience_mode' => 'INVALID']);
            $this->fail('An invalid audience mode was accepted.');
        } catch (ValidationException $exception) {
            $this->assertArrayHasKey('audience_mode', $exception->errors());
        }

        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_audience_restriction_without_bid_only_is_read_as_targeting(): void
    {
        unset($this->groups['201']['targetingSetting']['targetRestrictions'][0]['bidOnly']);
        app(CampaignSynchronizer::class)->sync($this->campaign);

        $edit = $this->apply(['audience_mode' => 'OBSERVATION'], 'ad_group');

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame('OBSERVATION', data_get($this->entity('ad_group')->settings, 'audience_mode'));
    }

    public function test_audience_mode_change_is_stale_if_another_restriction_changes(): void
    {
        $editor = app(EntityEditor::class);
        $edit = $editor->propose($this->campaign, $this->entity('ad_group'), $this->campaign->user, ['audience_mode' => 'TARGETING']);
        $this->groups['201']['targetingSetting']['targetRestrictions'][] = ['targetingDimension' => 'TOPIC', 'bidOnly' => false];

        $edit = $editor->apply($edit, $this->campaign->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Stale, $edit->state);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_rejected_audience_mode_change_is_not_reported_as_applied(): void
    {
        $this->rejectAdGroup = true;

        $edit = $this->apply(['audience_mode' => 'TARGETING'], 'ad_group');

        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertSame('OBSERVATION', data_get($this->entity('ad_group')->settings, 'audience_mode'));
        $this->assertStringContainsString('Ad group refused', $edit->error);
    }

    public function test_audience_mode_change_is_unconfirmed_when_readback_does_not_match(): void
    {
        $this->mismatchAdGroup = true;

        $edit = $this->apply(['audience_mode' => 'TARGETING'], 'ad_group');

        $this->assertSame(CampaignEntityEdit::Unconfirmed, $edit->state);
        $this->assertSame('OBSERVATION', data_get($this->entity('ad_group')->settings, 'audience_mode'));
    }

    public function test_display_content_targeting_is_changed_atomically_and_preserves_unedited_criteria(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        $this->criteria['ad_group']['201'] = [
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~11', 'adGroup' => 'customers/1234567890/adGroups/201',
                'type' => 'PLACEMENT', 'status' => 'ENABLED', 'negative' => false, 'placement' => ['url' => 'example.com']],
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~12', 'adGroup' => 'customers/1234567890/adGroups/201',
                'type' => 'TOPIC', 'status' => 'ENABLED', 'negative' => false, 'topic' => ['topicConstant' => 'topicConstants/5']],
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~13', 'adGroup' => 'customers/1234567890/adGroups/201',
                'type' => 'KEYWORD', 'status' => 'ENABLED', 'negative' => false, 'keyword' => ['text' => 'insurance', 'matchType' => 'BROAD']],
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~14', 'adGroup' => 'customers/1234567890/adGroups/201',
                'type' => 'USER_LIST', 'status' => 'ENABLED', 'negative' => false, 'userList' => ['userList' => 'customers/1234567890/userLists/9']],
        ];
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $entity = $this->entity('ad_group');
        Livewire::actingAs($this->campaign->user)
            ->test(EditEntity::class, ['campaign' => $this->campaign, 'entity' => $entity])
            ->assertSee('Display placements')
            ->assertSee('Display topics')
            ->assertSee('Display keywords');

        $edit = $this->apply([
            'display_placements' => [
                ['type' => 'PLACEMENT', 'value' => 'example.com', 'negative' => false],
                ['type' => 'MOBILE_APPLICATION', 'value' => '2-com.example.app', 'negative' => false],
            ],
            'display_topics' => [['type' => 'TOPIC', 'value' => 'topicConstants/6', 'negative' => false]],
            'display_keywords' => [
                ['type' => 'KEYWORD', 'value' => 'INSURANCE', 'negative' => false],
                ['type' => 'KEYWORD', 'value' => 'home insurance', 'negative' => false],
            ],
        ], 'ad_group');

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $requests = Http::recorded(fn (Request $request): bool => str_contains($request->url(), 'adGroupCriteria:mutate'))->values();
        $this->assertCount(1, $requests);
        $request = $requests[0][0];
        $this->assertFalse($request['partialFailure']);
        $this->assertCount(4, $request['operations']);
        $this->assertSame('customers/1234567890/adGroupCriteria/201~12', $request['operations'][0]['remove']);
        $this->assertSame('2-com.example.app', $request['operations'][1]['create']['mobileApplication']['appId']);
        $this->assertSame('topicConstants/6', $request['operations'][2]['create']['topic']['topicConstant']);
        $this->assertSame('BROAD', $request['operations'][3]['create']['keyword']['matchType']);
        $resources = array_column($this->criteria['ad_group']['201'], 'resourceName');
        $this->assertContains('customers/1234567890/adGroupCriteria/201~11', $resources);
        $this->assertContains('customers/1234567890/adGroupCriteria/201~13', $resources);
        $this->assertContains('customers/1234567890/adGroupCriteria/201~14', $resources);
    }

    public function test_display_content_targeting_refuses_invalid_mixed_or_paused_criteria(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        $this->criteria['ad_group']['201'] = [
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~11', 'adGroup' => 'customers/1234567890/adGroups/201',
                'type' => 'PLACEMENT', 'status' => 'PAUSED', 'placement' => ['url' => 'example.com']],
        ];
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $entity = $this->entity('ad_group');
        $this->assertNotContains('display_placements', app(EditCapabilities::class)->editableFields($entity));

        foreach ([
            ['display_topics' => [['type' => 'TOPIC', 'value' => 'topics/5', 'negative' => false]]],
            ['display_keywords' => [['type' => 'KEYWORD', 'value' => ' ', 'negative' => false]]],
            ['display_keywords' => [['type' => 'KEYWORD', 'value' => 'one two three four five six seven eight nine ten eleven', 'negative' => false]]],
            ['display_topics' => [], 'name' => 'Other name'],
        ] as $patch) {
            try {
                app(EntityEditor::class)->propose($this->campaign, $entity, $this->campaign->user, $patch);
                $this->fail('Invalid or mixed Display targeting was accepted: '.json_encode($patch));
            } catch (ValidationException|EditRefused $exception) {
                $this->assertNotEmpty($exception->getMessage());
            }
        }

        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_display_content_targeting_detects_drift_and_provider_failure(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $editor = app(EntityEditor::class);
        $patch = ['display_topics' => [['type' => 'TOPIC', 'value' => 'topicConstants/6', 'negative' => false]]];
        $edit = $editor->propose($this->campaign, $this->entity('ad_group'), $this->campaign->user, $patch);
        $this->criteria['ad_group']['201'][] = [
            'resourceName' => 'customers/1234567890/adGroupCriteria/201~11', 'adGroup' => 'customers/1234567890/adGroups/201',
            'type' => 'PLACEMENT', 'status' => 'ENABLED', 'placement' => ['url' => 'example.com'],
        ];

        $edit = $editor->apply($edit, $this->campaign->user, acknowledged: true);

        $this->assertSame(CampaignEntityEdit::Stale, $edit->state);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));

        $this->rejectCriteria = true;
        $edit = $this->apply($patch, 'ad_group');

        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertStringContainsString('Criteria refused', $edit->error);
        $this->assertSame([], data_get($this->entity('ad_group')->settings, 'display_topics'));
    }

    public function test_removing_display_topics_keeps_other_content_targeting(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        $this->criteria['ad_group']['201'] = [
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~11', 'adGroup' => 'customers/1234567890/adGroups/201',
                'type' => 'TOPIC', 'status' => 'ENABLED', 'topic' => ['topicConstant' => 'topicConstants/5']],
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~12', 'adGroup' => 'customers/1234567890/adGroups/201',
                'type' => 'PLACEMENT', 'status' => 'ENABLED', 'placement' => ['url' => 'example.com']],
        ];
        app(CampaignSynchronizer::class)->sync($this->campaign);

        $edit = $this->apply(['display_topics' => []], 'ad_group');

        $this->assertSame(CampaignEntityEdit::Applied, $edit->state, (string) $edit->error);
        $this->assertSame(['customers/1234567890/adGroupCriteria/201~12'], array_column($this->criteria['ad_group']['201'], 'resourceName'));
        $this->assertSame([], data_get($this->entity('ad_group')->settings, 'display_topics'));
    }

    public function test_incomplete_display_criterion_does_not_replace_the_last_good_snapshot(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $baseline = $this->entity('ad_group')->settings;
        $incomplete = [
            'resourceName' => 'customers/1234567890/adGroupCriteria/201~11', 'adGroup' => 'customers/1234567890/adGroups/201',
            'type' => 'TOPIC', 'status' => 'ENABLED', 'topic' => [],
        ];
        $valid = [...$incomplete, 'topic' => ['topicConstant' => 'topicConstants/5']];
        foreach ([
            [$incomplete],
            [[...$valid, 'resourceName' => 'customers/9999999999/adGroupCriteria/201~11']],
            [$valid, $valid],
        ] as $criteria) {
            $this->criteria['ad_group']['201'] = $criteria;
            $run = app(CampaignSynchronizer::class)->sync($this->campaign);

            $this->assertSame(CampaignSyncRun::Failed, $run->status);
            $this->assertStringContainsString('incomplete or unrelated Display targeting', $run->error);
            $this->assertSame($baseline, $this->entity('ad_group')->settings);
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_display_content_targeting_is_unconfirmed_when_readback_does_not_match(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'DISPLAY';
        $this->groups['201']['type'] = 'DISPLAY_STANDARD';
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $this->ignoreCriteriaMutation = true;

        $edit = $this->apply(['display_topics' => [['type' => 'TOPIC', 'value' => 'topicConstants/5', 'negative' => false]]], 'ad_group');

        $this->assertSame(CampaignEntityEdit::Unconfirmed, $edit->state);
        $this->assertSame([], data_get($this->entity('ad_group')->settings, 'display_topics'));
    }

    public function test_refused_keyword_batch_does_not_remove_existing_history(): void
    {
        $this->criteria['ad_group']['201'] = [
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~11', 'type' => 'KEYWORD', 'status' => 'ENABLED',
                'negative' => false, 'keyword' => ['text' => 'insurance', 'matchType' => 'PHRASE']],
        ];
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $original = $this->criteria;
        $this->rejectCriteria = true;
        $edit = $this->apply(['keywords' => [['text' => 'insurance', 'match_type' => 'EXACT', 'negative' => false]]], 'ad_group');
        $this->assertSame(CampaignEntityEdit::Failed, $edit->state);
        $this->assertStringContainsString('Nothing changed on the platform', $edit->error);
        $this->assertSame($original, $this->criteria);
    }

    public function test_malformed_and_duplicate_keywords_are_refused_before_any_mutation(): void
    {
        foreach ([
            [false],
            [['text' => null, 'match_type' => 'EXACT', 'negative' => false]],
            [['text' => 'insurance', 'match_type' => 'INVENTED', 'negative' => false]],
            [['text' => str_repeat('x', 81), 'match_type' => 'EXACT', 'negative' => false]],
            array_fill(0, 2, ['text' => 'insurance', 'match_type' => 'EXACT', 'negative' => false]),
        ] as $keywords) {
            try {
                app(EntityEditor::class)->propose($this->campaign, $this->entity('ad_group'), $this->campaign->user, ['keywords' => $keywords]);
                $this->fail('Invalid keyword proposal accepted.');
            } catch (ValidationException $exception) {
                $this->assertNotEmpty($exception->errors());
            }
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_copies_preserve_negative_placements_paused_audiences_assets_and_shared_exclusions(): void
    {
        $this->criteria['ad_group']['201'] = [
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~11', 'type' => 'PLACEMENT', 'status' => 'ENABLED',
                'negative' => true, 'placement' => ['url' => 'blocked.example.com']],
            ['resourceName' => 'customers/1234567890/adGroupCriteria/201~12', 'type' => 'USER_LIST', 'status' => 'PAUSED',
                'negative' => false, 'userList' => ['userList' => 'customers/1234567890/userLists/701']],
        ];
        $this->campaignAssets['101'] = [['campaign' => 'customers/1234567890/campaigns/101',
            'asset' => 'customers/1234567890/assets/601', 'fieldType' => 'SITELINK', 'status' => 'ENABLED']];
        $this->sharedSets['101'] = [['campaign' => 'customers/1234567890/campaigns/101',
            'sharedSet' => 'customers/1234567890/sharedSets/801', 'status' => 'ENABLED']];
        $this->nativeLinks['campaign_asset_set']['101'] = [['campaign' => 'customers/1234567890/campaigns/101',
            'assetSet' => 'customers/1234567890/assetSets/901', 'status' => 'ENABLED']];
        $this->nativeLinks['ad_group_asset']['201'] = [['adGroup' => 'customers/1234567890/adGroups/201',
            'asset' => 'customers/1234567890/assets/602', 'fieldType' => 'CALLOUT', 'status' => 'ENABLED']];
        $this->nativeLinks['ad_group_asset_set']['201'] = [['adGroup' => 'customers/1234567890/adGroups/201',
            'assetSet' => 'customers/1234567890/assetSets/902', 'status' => 'ENABLED']];
        $this->groups['201']['excludedParentAssetFieldTypes'] = ['SITELINK'];
        $original = $this->criteria['ad_group']['201'];
        $this->assertSame('102', app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101'));
        $this->assertSame('blocked.example.com', $this->criteria['ad_group']['202'][0]['placement']['url']);
        $this->assertTrue($this->criteria['ad_group']['202'][0]['negative']);
        $this->assertSame('PAUSED', $this->criteria['ad_group']['202'][1]['status']);
        $this->assertSame('customers/1234567890/assets/601', $this->campaignAssets['102'][0]['asset']);
        $this->assertSame('customers/1234567890/sharedSets/801', $this->sharedSets['102'][0]['sharedSet']);
        $this->assertSame($original, $this->criteria['ad_group']['201']);
        $this->assertSame('customers/1234567890/assetSets/901', $this->nativeLinks['campaign_asset_set']['102'][0]['assetSet']);
        $this->assertSame('customers/1234567890/assets/602', $this->nativeLinks['ad_group_asset']['202'][0]['asset']);
        $this->assertSame('customers/1234567890/assetSets/902', $this->nativeLinks['ad_group_asset_set']['202'][0]['assetSet']);
        $this->assertSame(['SITELINK'], $this->groups['202']['excludedParentAssetFieldTypes']);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/assets:mutate') || str_contains($request->url(), '/sharedSets:mutate'));
    }

    public function test_foreign_shared_assets_refuse_campaign_copy_before_any_creation(): void
    {
        $this->campaignAssets['101'] = [['campaign' => 'customers/1234567890/campaigns/101',
            'asset' => 'customers/999/assets/601', 'fieldType' => 'SITELINK', 'status' => 'ENABLED']];
        try {
            app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101');
            $this->fail('Foreign asset was copied.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('foreign campaign link', $exception->getMessage());
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_display_and_image_ads_preserve_native_assets_and_urls(): void
    {
        $base = $this->ads['301']['ad'];
        unset($base['responsiveSearchAd']);
        foreach ([
            ['type' => 'RESPONSIVE_DISPLAY_AD', 'responsiveDisplayAd' => [
                'marketingImages' => [['asset' => 'customers/1234567890/assets/601']],
                'squareMarketingImages' => [['asset' => 'customers/1234567890/assets/602']],
                'headlines' => [['text' => 'Headline']], 'longHeadline' => ['text' => 'Long headline'],
                'descriptions' => [['text' => 'Description']], 'businessName' => 'Example',
                'allowFlexibleColor' => false, 'controlSpec' => ['enableAssetEnhancements' => true],
            ]],
            ['type' => 'IMAGE_AD', 'imageAd' => ['imageUrl' => 'https://example.com/image.jpg']],
        ] as $creative) {
            $this->ads['301']['ad'] = [...$base, ...$creative];
            $id = app(GoogleAdsService::class)->duplicateAd(GoogleAdsConnection::shared(), '301', '201');
            $this->assertSame('302', $id);
            $this->assertSame('PAUSED', $this->ads[$id]['status']);
            $this->assertSame($base['finalMobileUrls'], $this->ads[$id]['ad']['finalMobileUrls']);
            $field = isset($creative['imageAd']) ? 'imageAd' : 'responsiveDisplayAd';
            $this->assertSame($creative[$field], $this->ads[$id]['ad'][$field]);
        }
    }

    public function test_creative_readback_mismatch_is_removed_instead_of_reporting_success(): void
    {
        $this->mismatchAd = true;
        try {
            app(GoogleAdsService::class)->duplicateAd(GoogleAdsConnection::shared(), '301', '201');
            $this->fail('An altered creative was accepted.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('Incomplete ad copy was removed', $exception->getMessage());
        }
        $this->assertArrayNotHasKey('302', $this->ads);
        $this->assertArrayHasKey('301', $this->ads);
    }

    private function preparePerformanceMax(): void
    {
        $this->campaigns['101']['advertisingChannelType'] = 'PERFORMANCE_MAX';
        $this->campaigns['101']['biddingStrategyType'] = 'MAXIMIZE_CONVERSIONS';
        $this->campaigns['101']['maximizeConversions'] = ['targetCpaMicros' => '3000000'];
        unset($this->campaigns['101']['manualCpc'], $this->campaigns['101']['networkSettings']);
        $this->groups = [];
        $this->ads = [];
        $resource = 'customers/1234567890/assetGroups/401';
        $this->assetGroups['401'] = ['id' => '401', 'resourceName' => $resource, 'campaign' => 'customers/1234567890/campaigns/101',
            'name' => 'PMax assets', 'status' => 'ENABLED', 'finalUrls' => ['https://example.com'],
            'finalMobileUrls' => ['https://m.example.com'], 'path1' => 'offer'];
        $this->assetLinks['401'] = [['assetGroup' => $resource, 'asset' => 'customers/1234567890/assets/601', 'fieldType' => 'HEADLINE', 'status' => 'ENABLED']];
        $this->signals['401'] = [
            ['assetGroup' => $resource, 'audience' => ['audience' => 'customers/1234567890/audiences/701']],
            ['assetGroup' => $resource, 'searchTheme' => ['text' => 'insurance']],
        ];
    }

    public function test_performance_max_campaign_copy_creates_paused_asset_groups_and_required_assets_atomically(): void
    {
        $this->preparePerformanceMax();
        $this->assertSame('102', app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101'));
        $this->assertSame('PAUSED', $this->assetGroups['402']['status']);
        $this->assertSame($this->assetGroups['401']['finalMobileUrls'], $this->assetGroups['402']['finalMobileUrls']);
        $this->assertSame('customers/1234567890/assets/601', $this->assetLinks['402'][0]['asset']);
        $this->assertCount(2, $this->signals['402']);
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/googleAds:mutate')
            && ! isset($request['operations']) && $request['partialFailure'] === false && count($request['mutateOperations']) === 4
            && $request['mutateOperations'][0]['assetGroupOperation']['create']['resourceName'] === 'customers/1234567890/assetGroups/-1'
            && $request['mutateOperations'][1]['assetGroupAssetOperation']['create']['assetGroup'] === 'customers/1234567890/assetGroups/-1');
    }

    public function test_standalone_asset_group_copy_is_available_and_confirmed_paused_in_the_manager(): void
    {
        $this->preparePerformanceMax();
        app(CampaignSynchronizer::class)->sync($this->campaign);
        $this->assertNull(app(EditCapabilities::class)->actionRefusal($this->entity('asset_group'), CampaignEntityEdit::Duplicate));
        $editor = app(EntityEditor::class);
        $edit = $editor->proposeAction($this->campaign, $this->entity('asset_group'), $this->campaign->user, CampaignEntityEdit::Duplicate);
        $result = $editor->apply($edit, $this->campaign->user, acknowledged: true);
        $this->assertSame(CampaignEntityEdit::Applied, $result->state, (string) $result->error);
        $this->assertSame('402', $result->details['copy_id']);
        $this->assertSame('PAUSED', $this->assetGroups['402']['status']);
        $this->assertSame('ENABLED', $this->assetGroups['401']['status']);
    }

    public function test_asset_group_readback_loss_rolls_back_the_new_group(): void
    {
        $this->preparePerformanceMax();
        $this->omitCopiedAsset = true;
        try {
            app(GoogleAdsService::class)->duplicateManagerAssetGroup(GoogleAdsConnection::shared(), '101', '401');
            $this->fail('An asset group missing assets was accepted.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('Incomplete asset group copy was removed', $exception->getMessage());
        }
        $this->assertArrayNotHasKey('402', $this->assetGroups);
        $this->assertSame('ENABLED', $this->assetGroups['401']['status']);
    }

    public function test_retail_performance_max_refuses_lossy_copy_before_mutation(): void
    {
        $this->preparePerformanceMax();
        $this->listingGroups = true;
        try {
            app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101');
            $this->fail('Retail copy was accepted.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('Retail/listing-group', $exception->getMessage());
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_disabled_custom_goals_and_changed_goal_baselines_are_not_written(): void
    {
        $this->customGoalStatus = 'REMOVED';
        try {
            app(GoogleAdsService::class)->updateManagerGoals(GoogleAdsConnection::shared(), '101',
                ['level' => 'CAMPAIGN', 'goals' => [], 'custom_goal' => 'customers/1234567890/customConversionGoals/701'], ['level' => 'CUSTOMER']);
            $this->fail('Removed custom goal was accepted.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('not confirmed enabled', $exception->getMessage());
        }
        $this->configs['101']['goalConfigLevel'] = 'CAMPAIGN';
        try {
            app(GoogleAdsService::class)->updateManagerGoals(GoogleAdsConnection::shared(), '101', ['level' => 'CUSTOMER'], ['level' => 'CUSTOMER']);
            $this->fail('Stale baseline was accepted.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('changed after review', $exception->getMessage());
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_malformed_foreign_duplicate_or_partial_reports_never_become_zero_delivery(): void
    {
        foreach ([
            [['campaign' => ['id' => '999'], 'metrics' => []]],
            [['campaign' => ['id' => '101']]],
            [['campaign' => ['id' => '101'], 'metrics' => []], ['campaign' => ['id' => '101'], 'metrics' => []]],
            [['campaign' => ['id' => '101'], 'metrics' => ['costMicros' => '-1']]],
            [['campaign' => ['id' => '101'], 'metrics' => ['impressions' => '1.5']]],
            [['campaign' => ['id' => '101'], 'metrics' => ['impressions' => true]]],
            [['campaign' => ['id' => '101'], 'metrics' => ['costMicros' => '1e100']]],
            [['campaign' => ['id' => '101'], 'metrics' => ['impressions' => '9223372036854775808']]],
        ] as $rows) {
            $this->reportRows = $rows;
            try {
                app(GoogleAdsService::class)->readLifetimeDelivery(GoogleAdsConnection::shared(), 'campaign', ['101', '102']);
                $this->fail('Unknown reporting was accepted.');
            } catch (RuntimeException $exception) {
                $this->assertStringContainsString('Google', $exception->getMessage());
            }
        }
        $this->reportRows = [['campaign' => ['id' => '101'], 'metrics' => ['costMicros' => '1']]];
        $delivery = app(GoogleAdsService::class)->readLifetimeDelivery(GoogleAdsConnection::shared(), 'campaign', ['101']);
        $this->assertSame(0.000001, $delivery['101']['spend']);
    }

    public function test_new_controls_respect_the_google_write_gate_and_acknowledgement(): void
    {
        $editor = app(EntityEditor::class);
        $edit = $editor->propose($this->campaign, $this->entity(), $this->campaign->user, ['network_settings' => ['targetSearchNetwork' => true]]);
        try {
            $editor->apply($edit, $this->campaign->user);
            $this->fail('Unacknowledged network change was sent.');
        } catch (EditRefused $exception) {
            $this->assertStringContainsString('acknowledge', strtolower($exception->getMessage()));
        }
        config(['campaign-manager.edit_platforms' => ['meta', 'linkedin']]);
        try {
            $editor->apply($edit, $this->campaign->user, acknowledged: true);
            $this->fail('Google gate was bypassed.');
        } catch (EditRefused $exception) {
            $this->assertStringContainsString('not switched on', $exception->getMessage());
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_unknown_reporting_blocks_manager_deletion_for_active_and_paused_campaigns(): void
    {
        $this->reportRows = [];
        foreach (['ENABLED', 'PAUSED'] as $status) {
            $this->campaigns['101']['status'] = $status;
            app(CampaignSynchronizer::class)->sync($this->campaign);
            try {
                app(EntityEditor::class)->proposeAction($this->campaign, $this->entity(), $this->campaign->user, CampaignEntityEdit::Delete);
                $this->fail('Deletion was offered without known reporting.');
            } catch (EditRefused $exception) {
                $this->assertStringContainsString('Unknown spend is not zero', $exception->getMessage());
            }
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_malformed_stream_envelopes_and_rows_are_not_silently_discarded(): void
    {
        foreach ([['results' => []], [['results' => 'malformed']], [['results' => [false]]]] as $response) {
            $this->streamResponse = $response;
            try {
                app(GoogleAdsService::class)->readLifetimeDelivery(GoogleAdsConnection::shared(), 'campaign', ['101']);
                $this->fail('Malformed response accepted.');
            } catch (RuntimeException $exception) {
                $this->assertStringContainsString('Google returned', $exception->getMessage());
            }
        }
    }

    public function test_customizers_and_unknown_criterion_types_refuse_reconstruction_before_creation(): void
    {
        $this->customizers = true;
        try {
            app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101');
            $this->fail('Source customizers were silently lost.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('customizer', $exception->getMessage());
        }
        $this->customizers = false;
        $this->criteria['campaign']['101'] = [['type' => 'UNKNOWN_NATIVE_TYPE']];
        try {
            app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101');
            $this->fail('Unknown criterion was silently lost.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('unsupported UNKNOWN_NATIVE_TYPE', $exception->getMessage());
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_missing_keyword_readback_never_compares_equal_to_an_explicit_clear(): void
    {
        $this->assertFalse(EditCapabilities::same($this->entity('ad_group'), 'keywords', null, []));
        $this->assertTrue(EditCapabilities::same($this->entity('ad_group'), 'keywords',
            [['text' => ' INSURANCE ', 'match_type' => 'EXACT', 'negative' => false]],
            [['text' => 'insurance', 'match_type' => 'EXACT', 'negative' => false]],
        ));
    }

    public function test_ad_copy_destination_is_separate_from_its_checked_source_group(): void
    {
        $this->groups['202'] = [...$this->groups['201'], 'id' => '202', 'resourceName' => 'customers/1234567890/adGroups/202'];
        $this->assertSame('302', app(GoogleAdsService::class)->duplicateAd(
            GoogleAdsConnection::shared(), '301', '202', expectedSourceAdGroupId: '201',
        ));
        $this->assertSame('customers/1234567890/adGroups/202', $this->ads['302']['adGroup']);
        $this->assertSame('customers/1234567890/adGroups/201', $this->ads['301']['adGroup']);
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), 'googleAds:searchStream')
            && str_contains($request['query'], 'ad_group_ad.ad.id = 301 AND ad_group.id = 201'));
    }

    public function test_copy_refuses_a_remaining_schedule_that_would_end_before_the_new_start(): void
    {
        $this->campaigns['101']['startDateTime'] = now()->subDay()->format('Y-m-d H:i:s');
        $this->campaigns['101']['endDateTime'] = now()->addSeconds(30)->format('Y-m-d H:i:s');
        try {
            app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101');
            $this->fail('An impossible copied schedule was accepted.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('schedule ends before a safe new start', $exception->getMessage());
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_native_array_shaped_search_errors_keep_actionable_field_details(): void
    {
        $this->streamStatus = 400;
        $this->streamResponse = [['error' => ['message' => 'Request contains an invalid argument.',
            'details' => [['errors' => [['errorCode' => ['queryError' => 'EXPECTED_REFERENCED_FIELD_IN_SELECT_CLAUSE'],
                'message' => 'The following field must be present in SELECT clause: campaign.id.']]]]]]];
        try {
            app(GoogleAdsService::class)->readLifetimeDelivery(GoogleAdsConnection::shared(), 'campaign', ['101']);
            $this->fail('Invalid native query reported success.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('campaign.id', $exception->getMessage());
            $this->assertStringContainsString('EXPECTED_REFERENCED_FIELD_IN_SELECT_CLAUSE', $exception->getMessage());
        }
    }

    public function test_campaign_copy_updates_automatically_created_device_criteria_and_preserves_group_modifiers(): void
    {
        $this->groupModifiers['201']['MOBILE'] = 0.6;
        $this->criteria['campaign']['101'] = [
            ['resourceName' => 'customers/1234567890/campaignCriteria/101~30000', 'type' => 'DEVICE', 'status' => 'ENABLED',
                'device' => ['type' => 'DESKTOP'], 'bidModifier' => 1.0],
            ['resourceName' => 'customers/1234567890/campaignCriteria/101~30001', 'type' => 'DEVICE', 'status' => 'ENABLED',
                'device' => ['type' => 'MOBILE'], 'bidModifier' => 0.8],
        ];
        $this->assertSame('102', app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101'));
        $this->assertSame(0.6, $this->groupModifiers['202']['MOBILE']);
        $this->assertSame(0.8, $this->criteria['campaign']['102'][1]['bidModifier']);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/campaignCriteria:mutate')
            && collect($request['operations'])->contains(fn (array $operation): bool => isset($operation['create']['device'])));
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/adGroupBidModifiers:mutate')
            && $request['operations'][0]['update']['resourceName'] === 'customers/1234567890/adGroupBidModifiers/202~30001');
    }

    public function test_empty_native_message_containers_remain_objects_not_repeated_lists(): void
    {
        $this->campaigns['101']['textGuidelines'] = [];
        $this->groups['201']['targetingSetting'] = [];
        $this->assertSame('102', app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101'));
        Http::assertSent(function (Request $request): bool {
            if (! str_contains($request->url(), '/campaigns:mutate') || ! isset($request['operations'][0]['create'])) {
                return false;
            }

            return data_get(json_decode($request->body()), 'operations.0.create.textGuidelines') instanceof \stdClass;
        });
        Http::assertSent(function (Request $request): bool {
            if (! str_contains($request->url(), '/adGroups:mutate')) {
                return false;
            }

            return data_get(json_decode($request->body()), 'operations.0.create.targetingSetting') instanceof \stdClass;
        });
    }

    public function test_deprecated_campaign_rotation_is_never_sent_and_legacy_nondefault_modes_are_refused(): void
    {
        $this->campaigns['101']['adServingOptimizationStatus'] = 'ROTATE';
        try {
            app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101');
            $this->fail('Legacy campaign rotation was silently dropped.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('Legacy campaign ad rotation', $exception->getMessage());
        }
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
        $this->campaigns['101']['adServingOptimizationStatus'] = 'OPTIMIZE';
        $this->assertSame('102', app(GoogleAdsService::class)->duplicateManagerCampaign(GoogleAdsConnection::shared(), '101'));
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/campaigns:mutate')
            && isset($request['operations'][0]['create']['adServingOptimizationStatus']));
    }

    public function test_group_copy_preserves_applicable_bids_rotation_and_keyword_url_overrides_without_writing_unset_bids(): void
    {
        $this->groups['201'] += ['cpmBidMicros' => '10000', 'cpvBidMicros' => '0', 'targetCpaMicros' => '0', 'adRotationMode' => 'OPTIMIZE'];
        $overrides = ['cpcBidMicros' => '2500000', 'finalUrls' => ['https://example.com/keyword'],
            'finalMobileUrls' => ['https://m.example.com/keyword'], 'trackingUrlTemplate' => 'https://example.com/?url={lpurl}',
            'finalUrlSuffix' => 'keyword=1', 'urlCustomParameters' => [['key' => 'keyword', 'value' => 'original']]];
        $this->criteria['ad_group']['201'] = [[
            'resourceName' => 'customers/1234567890/adGroupCriteria/201~501', 'status' => 'ENABLED', 'negative' => false,
            'type' => 'KEYWORD', 'keyword' => ['text' => 'workflow', 'matchType' => 'EXACT'],
            ...$overrides, 'cpmBidMicros' => '0', 'cpvBidMicros' => '0',
        ]];
        app(GoogleAdsService::class)->duplicateAdGroup(GoogleAdsConnection::shared(), '201');
        $this->assertSame('1000000', $this->groups['202']['cpcBidMicros']);
        $this->assertSame('OPTIMIZE', $this->groups['202']['adRotationMode']);
        foreach (['cpmBidMicros', 'cpvBidMicros', 'targetCpaMicros'] as $field) {
            $this->assertArrayNotHasKey($field, $this->groups['202']);
        }
        foreach ($overrides as $field => $value) {
            $this->assertSame($value, $this->criteria['ad_group']['202'][0][$field]);
        }
    }

    public function test_creative_readback_ignores_only_readonly_review_metadata_and_preserves_pins(): void
    {
        $this->creativeMetadata = true;
        $this->ads['301']['ad']['responsiveSearchAd']['headlines'][0] += [
            'assetPerformanceLabel' => 'LOW', 'policySummaryInfo' => ['reviewStatus' => 'REVIEWED'],
        ];
        $this->assertSame('302', app(GoogleAdsService::class)->duplicateAd(GoogleAdsConnection::shared(), '301', '201'));
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/adGroupAds:mutate')
            && ($request['operations'][0]['create']['ad']['responsiveSearchAd']['headlines'][0] ?? null) === ['text' => 'One', 'pinnedField' => 'HEADLINE_1']);
    }
}
