<?php

namespace Tests\Feature;

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\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 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 $omitCopiedAsset = false;

    private bool $mismatchAd = false;

    private bool $creativeMetadata = false;

    private string $customGoalStatus = 'ENABLED';

    private bool $denyGoals = false;

    private bool $rejectConfig = false;

    private bool $rejectAd = 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', '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 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('/\.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')) {
            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 ($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);
        }
        $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);
                $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') {
                $this->groups[$id] = [...$payload, 'resourceName' => $resource, 'id' => $id];
            } 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', 'userList' => 'USER_LIST', 'location' => 'LOCATION'];
                $type = array_intersect_key($blocks, $payload);
                $this->criteria[$scope][$parent][] = [...$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);
    }

    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_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;
        $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_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']);
    }
}
