<?php

namespace Tests\Feature;

use App\Agent\NamespacedTool;
use App\Agent\Tools\Campaign\EditEntity;
use App\Agent\Tools\Campaign\ListCampaignStructure;
use App\Agent\Workspace;
use App\Models\Campaign;
use App\Models\CampaignChange;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request as ClientRequest;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

class GoogleChatAdEditTest extends TestCase
{
    use RefreshDatabase;

    private array $ad;

    private bool $shared = false;

    private bool $ignoreUpdate = false;

    private bool $rejectUpdate = false;

    private bool $displayGroup = false;

    private array $criteria = [];

    private array $googleAssets = [];

    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,
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '1234567890',
        ]);
        $user = User::factory()->create();
        $this->actingAs($user);
        $workspace = app(Workspace::class);
        $workspace->bindTo('google-ad-edit');
        $workspace->ownedBy($user);
        $campaign = Campaign::create([
            'user_id' => $user->id, 'name' => 'Search', 'platform' => 'google',
            'status' => 'published', 'ad_account_id' => '1234567890', 'external_campaign_id' => '101',
        ]);
        $workspace->produced($campaign);
        $workspace->focusOn($campaign);
        $this->ad = [
            'id' => '301', 'type' => 'RESPONSIVE_SEARCH_AD', 'finalUrls' => ['https://example.com'],
            'trackingUrlTemplate' => 'https://tracker.example/?url={lpurl}', 'finalUrlSuffix' => 'source=old',
            'responsiveSearchAd' => [
                'headlines' => [['text' => 'First', 'pinnedField' => 'HEADLINE_1'], ['text' => 'Second'], ['text' => 'Third']],
                'descriptions' => [['text' => 'Description one'], ['text' => 'Description two']],
                'path1' => 'old', 'path2' => '',
            ],
        ];
        Http::preventStrayRequests();
        Http::fake(function (ClientRequest $request) {
            if (str_contains($request->url(), 'oauth2.googleapis.com')) {
                return Http::response(['access_token' => 'token', 'expires_in' => 3600]);
            }
            if (str_contains($request->url(), 'googleAds:searchStream')) {
                $query = $request['query'];
                if (str_contains($query, 'FROM ad_group_criterion')) {
                    $rows = str_contains($query, "'PLACEMENT','MOBILE_APPLICATION'") ? array_map(
                        fn (array $criterion): array => ['adGroupCriterion' => $criterion], $this->criteria,
                    ) : [];
                } elseif (str_contains($query, 'FROM asset')) {
                    $rows = array_map(fn (array $asset): array => ['asset' => $asset], array_values($this->googleAssets));
                } elseif (str_contains($query, 'FROM ad_group_ad')) {
                    $rows = [['adGroupAd' => ['ad' => $this->ad, 'status' => 'ENABLED'], 'adGroup' => ['id' => '201', 'name' => 'Group']]];
                    if ($this->shared && str_contains($query, 'WHERE ad_group_ad.ad.id')) {
                        $rows[] = ['adGroupAd' => ['ad' => ['id' => '301']], 'adGroup' => ['id' => '202']];
                    }
                } elseif (str_contains($query, 'FROM ad_group')) {
                    $rows = [['adGroup' => ['id' => '201', 'name' => 'Group', 'type' => $this->displayGroup ? 'DISPLAY_STANDARD' : 'SEARCH_STANDARD', 'status' => 'ENABLED'],
                        'campaign' => ['advertisingChannelType' => $this->displayGroup ? 'DISPLAY' : 'SEARCH']]];
                } else {
                    $this->fail('Unexpected Google query: '.$query);
                }

                return Http::response([['results' => $rows]]);
            }
            if (str_contains($request->url(), '/ads:mutate')) {
                if ($this->rejectUpdate) {
                    return Http::response(['error' => ['message' => 'Rejected']], 400);
                }
                if (! $this->ignoreUpdate) {
                    $update = $request['operations'][0]['update'];
                    foreach (['finalUrls', 'trackingUrlTemplate', 'finalUrlSuffix'] as $field) {
                        if (array_key_exists($field, $update)) {
                            $this->ad[$field] = $update[$field];
                        }
                    }
                    if (array_key_exists('urlCustomParameters', $update)) {
                        $this->ad['urlCustomParameters'] = $update['urlCustomParameters'];
                    }
                    foreach ($update['responsiveSearchAd'] ?? [] as $field => $value) {
                        $this->ad['responsiveSearchAd'][$field] = $value;
                    }
                    foreach ($update['responsiveDisplayAd'] ?? [] as $field => $value) {
                        $this->ad['responsiveDisplayAd'][$field] = $value;
                    }
                    if (in_array('responsiveDisplayAd.callToActionText', explode(',', $request['operations'][0]['updateMask']), true)
                        && ! array_key_exists('callToActionText', $update['responsiveDisplayAd'] ?? [])) {
                        unset($this->ad['responsiveDisplayAd']['callToActionText']);
                    }
                }

                return Http::response(['results' => [['resourceName' => 'customers/1234567890/ads/301']]]);
            }
            if (str_contains($request->url(), '/adGroupCriteria:mutate')) {
                if (! $this->ignoreUpdate) {
                    foreach ($request['operations'] as $operation) {
                        if (isset($operation['remove'])) {
                            $this->criteria = array_values(array_filter($this->criteria, fn (array $criterion): bool => $criterion['resourceName'] !== $operation['remove']));
                        } else {
                            $criterion = $operation['create'];
                            $criterion['resourceName'] = 'customers/1234567890/adGroupCriteria/201~'.(100 + count($this->criteria));
                            $criterion['type'] = match (true) {
                                isset($criterion['placement']) => 'PLACEMENT',
                                isset($criterion['mobileApplication']) => 'MOBILE_APPLICATION',
                                isset($criterion['topic']) => 'TOPIC',
                                default => 'KEYWORD',
                            };
                            $this->criteria[] = $criterion;
                        }
                    }
                }

                return Http::response(['results' => []]);
            }
            $this->fail('Unexpected request: '.$request->url());
        });
    }

    private function tool(): NamespacedTool
    {
        return new NamespacedTool('campaign', app(EditEntity::class));
    }

    private function request(array $changes, string $callId): Request
    {
        return new Request(['entity_type' => 'ad', 'id' => '301', ...$changes], $callId);
    }

    private function edit(Request $request): array
    {
        return json_decode((string) $this->tool()->handle($request), true, flags: JSON_THROW_ON_ERROR);
    }

    private function assertNoMutation(): void
    {
        Http::assertNotSent(fn (ClientRequest $request): bool => str_contains($request->url(), ':mutate'));
    }

    private function useDisplayAdWithAssets(): void
    {
        $this->displayGroup = true;
        $this->ad['type'] = 'RESPONSIVE_DISPLAY_AD';
        $this->ad['urlCustomParameters'] = [['key' => 'source', 'value' => 'old']];
        $this->ad['responsiveDisplayAd'] = [
            'headlines' => [['text' => 'Short headline']],
            'descriptions' => [['text' => 'Description']],
            'longHeadline' => ['text' => 'Long headline'],
            'businessName' => 'Business',
            'callToActionText' => 'Learn more',
            'marketingImages' => [['asset' => 'customers/1234567890/assets/801']],
            'squareMarketingImages' => [['asset' => 'customers/1234567890/assets/802']],
            'logoImages' => [['asset' => 'customers/1234567890/assets/803']],
            'squareLogoImages' => [],
            'youtubeVideos' => [['asset' => 'customers/1234567890/assets/804']],
        ];
        $this->googleAssets = [
            'customers/1234567890/assets/801' => ['resourceName' => 'customers/1234567890/assets/801', 'type' => 'IMAGE', 'imageAsset' => ['fullSize' => ['widthPixels' => 1200, 'heightPixels' => 628]]],
            'customers/1234567890/assets/802' => ['resourceName' => 'customers/1234567890/assets/802', 'type' => 'IMAGE', 'imageAsset' => ['fullSize' => ['widthPixels' => 1200, 'heightPixels' => 1200]]],
            'customers/1234567890/assets/803' => ['resourceName' => 'customers/1234567890/assets/803', 'type' => 'IMAGE', 'imageAsset' => ['fullSize' => ['widthPixels' => 512, 'heightPixels' => 128]]],
            'customers/1234567890/assets/804' => ['resourceName' => 'customers/1234567890/assets/804', 'type' => 'YOUTUBE_VIDEO'],
            'customers/1234567890/assets/805' => ['resourceName' => 'customers/1234567890/assets/805', 'type' => 'IMAGE', 'imageAsset' => ['fullSize' => ['widthPixels' => 1200, 'heightPixels' => 628]]],
            'customers/1234567890/assets/806' => ['resourceName' => 'customers/1234567890/assets/806', 'type' => 'IMAGE', 'imageAsset' => ['fullSize' => ['widthPixels' => 1200, 'heightPixels' => 1200]]],
            'customers/1234567890/assets/807' => ['resourceName' => 'customers/1234567890/assets/807', 'type' => 'IMAGE', 'imageAsset' => ['fullSize' => ['widthPixels' => 512, 'heightPixels' => 128]]],
            'customers/1234567890/assets/808' => ['resourceName' => 'customers/1234567890/assets/808', 'type' => 'IMAGE', 'imageAsset' => ['fullSize' => ['widthPixels' => 128, 'heightPixels' => 128]]],
            'customers/1234567890/assets/809' => ['resourceName' => 'customers/1234567890/assets/809', 'type' => 'YOUTUBE_VIDEO'],
            'customers/1234567890/assets/810' => ['resourceName' => 'customers/1234567890/assets/810', 'type' => 'IMAGE', 'imageAsset' => ['fullSize' => ['widthPixels' => 512, 'heightPixels' => 128]]],
        ];
    }

    public function test_approved_ad_changes_are_verified_and_leave_other_fields_untouched(): void
    {
        $request = $this->request([
            'ad_headlines' => [['text' => 'First', 'pinnedField' => 'HEADLINE_1'], ['text' => 'New second'], ['text' => 'Third']],
            'ad_urls' => ['finalUrls' => ['https://example.com/new'], 'trackingUrlTemplate' => $this->ad['trackingUrlTemplate'], 'finalUrlSuffix' => 'source=new'],
            'ad_search_path' => ['path1' => 'new', 'path2' => 'page'],
        ], 'approved');
        $this->assertNotNull($this->tool()->shouldRequestApproval($request));
        $result = $this->edit($request);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['verified']);
        $this->assertSame('HEADLINE_1', $this->ad['responsiveSearchAd']['headlines'][0]['pinnedField']);
        $this->assertSame('Description one', $this->ad['responsiveSearchAd']['descriptions'][0]['text']);
        $this->assertSame('https://tracker.example/?url={lpurl}', $this->ad['trackingUrlTemplate']);
        $this->assertSame('applied', CampaignChange::sole()->state);
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertCount(1, CampaignChange::all());
    }

    public function test_changed_baseline_and_changed_arguments_are_not_written(): void
    {
        $request = $this->request(['ad_search_path' => ['path1' => 'new', 'path2' => '']], 'stale');
        $this->tool()->shouldRequestApproval($request);
        $this->ad['responsiveSearchAd']['path1'] = 'external';
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('changed since approval', $result['error']);

        $request = $this->request(['ad_search_path' => ['path1' => 'new', 'path2' => '']], 'arguments');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($this->request(['ad_search_path' => ['path1' => 'other', 'path2' => '']], 'arguments'));
        $this->assertFalse($result['ok']);
        $this->assertNoMutation();
    }

    public function test_approved_display_headline_business_and_cta_are_verified(): void
    {
        $this->ad['type'] = 'RESPONSIVE_DISPLAY_AD';
        unset($this->ad['responsiveSearchAd']);
        $this->ad['responsiveDisplayAd'] = [
            'headlines' => [['text' => 'Short headline']],
            'descriptions' => [['text' => 'Description']],
            'longHeadline' => ['text' => 'Previous long headline'],
            'businessName' => 'Previous name',
            'callToActionText' => 'Learn more',
        ];
        $request = $this->request([
            'ad_display_long_headline' => 'New long headline',
            'ad_display_business_name' => 'New name',
            'ad_display_cta' => '',
        ], 'display');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('New long headline', $this->ad['responsiveDisplayAd']['longHeadline']['text']);
        $this->assertSame('New name', $this->ad['responsiveDisplayAd']['businessName']);
        $this->assertArrayNotHasKey('callToActionText', $this->ad['responsiveDisplayAd']);
        $this->assertSame('Short headline', $this->ad['responsiveDisplayAd']['headlines'][0]['text']);
        Http::assertSent(fn (ClientRequest $request): bool => str_contains($request->url(), '/ads:mutate')
            && in_array('responsiveDisplayAd.longHeadline.text', explode(',', $request['operations'][0]['updateMask']), true)
            && data_get($request['operations'][0], 'update.responsiveDisplayAd.longHeadline.text') === 'New long headline');
    }

    public function test_display_cta_can_be_cleared_on_its_own(): void
    {
        $this->useDisplayAdWithAssets();
        $request = $this->request(['ad_display_cta' => ''], 'clear-cta');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['verified']);
        $this->assertArrayNotHasKey('callToActionText', $this->ad['responsiveDisplayAd']);
        Http::assertSent(fn (ClientRequest $request): bool => str_contains($request->url(), '/ads:mutate')
            && $request['operations'][0]['updateMask'] === 'responsiveDisplayAd.callToActionText'
            && ! array_key_exists('responsiveDisplayAd', $request['operations'][0]['update']));
    }

    public function test_display_assets_and_custom_parameters_are_approved_and_read_back(): void
    {
        $this->useDisplayAdWithAssets();
        $list = new NamespacedTool('campaign', app(ListCampaignStructure::class));
        $listed = json_decode((string) $list->handle(new Request([])), true, flags: JSON_THROW_ON_ERROR);
        $this->assertSame(
            ['customers/1234567890/assets/801'],
            $listed['ads'][0]['ad_display_assets']['marketing_images'],
        );
        $this->assertSame([['key' => 'source', 'value' => 'old']], $listed['ads'][0]['ad_custom_parameters']);
        Http::assertSent(fn (ClientRequest $request): bool => str_contains($request->url(), 'googleAds:searchStream')
            && str_contains($request['query'], 'ad_group_ad.ad.responsive_display_ad.marketing_images,')
            && ! str_contains($request['query'], 'ad_group_ad.ad.responsive_display_ad.marketing_images.asset'));

        $request = $this->request([
            'ad_display_assets' => [
                'marketing_images' => ['customers/1234567890/assets/805'],
                'square_marketing_images' => ['customers/1234567890/assets/806'],
                'logo_images' => ['customers/1234567890/assets/807'],
                'square_logo_images' => ['customers/1234567890/assets/808'],
                'youtube_videos' => ['customers/1234567890/assets/809'],
            ],
            'ad_custom_parameters' => [['key' => 'campaign', 'value' => 'spring']],
        ], 'display-assets');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['verified']);
        $this->assertSame('customers/1234567890/assets/805', $this->ad['responsiveDisplayAd']['marketingImages'][0]['asset']);
        $this->assertSame('customers/1234567890/assets/809', $this->ad['responsiveDisplayAd']['youtubeVideos'][0]['asset']);
        $this->assertSame([['key' => 'campaign', 'value' => 'spring']], $this->ad['urlCustomParameters']);
        Http::assertSent(fn (ClientRequest $request): bool => str_contains($request->url(), '/ads:mutate')
            && isset($request['operations'][0]['update']['urlCustomParameters'])
            && str_contains($request['operations'][0]['updateMask'], 'url_custom_parameters')
            && str_contains($request['operations'][0]['updateMask'], 'responsiveDisplayAd.marketingImages'));
    }

    public function test_display_asset_lists_reject_foreign_assets_and_bad_image_types(): void
    {
        $this->useDisplayAdWithAssets();
        $assets = [
            'marketing_images' => ['customers/1234567890/assets/805'],
            'square_marketing_images' => ['customers/1234567890/assets/806'],
            'logo_images' => ['customers/1234567890/assets/807'],
            'square_logo_images' => [],
            'youtube_videos' => ['customers/1234567890/assets/809'],
        ];
        $foreign = $assets;
        $foreign['marketing_images'] = ['customers/9999999999/assets/805'];
        $result = $this->edit($this->request(['ad_display_assets' => $foreign], 'foreign-asset'));
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('belong to this Google Ads account', $result['error']);

        $wrongType = $assets;
        $wrongType['youtube_videos'] = ['customers/1234567890/assets/807'];
        $result = $this->edit($this->request(['ad_display_assets' => $wrongType], 'wrong-video-type'));
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('YouTube video assets only', $result['error']);

        $wrongDimensions = $assets;
        $wrongDimensions['marketing_images'] = ['customers/1234567890/assets/810'];
        $result = $this->edit($this->request(['ad_display_assets' => $wrongDimensions], 'wrong-image-dimensions'));
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('dimensions and aspect ratio', $result['error']);

        $result = $this->edit($this->request([
            'ad_custom_parameters' => [['key' => 'source', 'value' => 'one'], ['key' => 'SOURCE', 'value' => 'two']],
        ], 'duplicate-parameters'));
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('unique regardless of case', $result['error']);
        $this->assertNoMutation();
    }

    public function test_display_asset_change_is_refused_when_the_live_asset_baseline_changes_after_approval(): void
    {
        $this->useDisplayAdWithAssets();
        $request = $this->request([
            'ad_display_assets' => [
                'marketing_images' => ['customers/1234567890/assets/805'],
                'square_marketing_images' => ['customers/1234567890/assets/806'],
                'logo_images' => ['customers/1234567890/assets/807'],
                'square_logo_images' => [],
                'youtube_videos' => ['customers/1234567890/assets/809'],
            ],
        ], 'stale-assets');
        $this->tool()->shouldRequestApproval($request);
        $this->ad['responsiveDisplayAd']['marketingImages'] = [['asset' => 'customers/1234567890/assets/805']];

        $result = $this->edit($request);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('changed since approval', $result['error']);
        $this->assertNoMutation();
    }

    public function test_invalid_or_unapproved_edits_are_not_written(): void
    {
        $invalid = $this->request(['ad_search_path' => ['path1' => '', 'path2' => 'page']], 'invalid');
        $result = $this->edit($invalid);
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('second display path', $result['error']);
        $result = $this->edit($this->request(['ad_headlines' => '[{"text":"First"}]'], 'wrong-shape'));
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('array or object', $result['error']);
        $result = $this->edit($this->request(['ad_search_path' => ['path1' => 'new', 'path2' => '']], 'unapproved'));
        $this->assertFalse($result['ok']);
        $this->assertNoMutation();
    }

    public function test_search_text_edit_does_not_silently_remove_existing_pins(): void
    {
        $request = $this->request(['ad_headlines' => [
            ['text' => 'First'], ['text' => 'New second'], ['text' => 'Third'],
        ]], 'lost-pin');
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('pinning', $result['error']);
        $this->assertNoMutation();
    }

    public function test_ads_outside_the_campaign_and_display_fields_on_search_ads_are_refused(): void
    {
        $unknown = new Request(['entity_type' => 'ad', 'id' => '999', 'ad_search_path' => ['path1' => 'new', 'path2' => '']], 'foreign-ad');
        $result = $this->edit($unknown);
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('in this campaign', $result['error']);
        $result = $this->edit($this->request(['ad_display_business_name' => 'New name'], 'wrong-type'));
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('responsive Display ad', $result['error']);
        $result = $this->edit($this->request(['campaign_id' => '999', 'ad_search_path' => ['path1' => 'new', 'path2' => '']], 'foreign-campaign'));
        $this->assertFalse($result['ok']);
        $this->assertNoMutation();
    }

    public function test_shared_ad_is_refused_without_mutation(): void
    {
        $this->shared = true;
        $request = $this->request(['ad_search_path' => ['path1' => 'new', 'path2' => '']], 'shared');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('shared', $result['error']);
        $this->assertNoMutation();
    }

    public function test_rejected_or_unconfirmed_writes_are_not_reported_as_applied(): void
    {
        $this->ignoreUpdate = true;
        $request = $this->request(['ad_search_path' => ['path1' => 'new', 'path2' => '']], 'unconfirmed');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertTrue($result['reconciliation_required']);
        $this->assertSame('failed', CampaignChange::latest('id')->first()->state);

        $this->rejectUpdate = true;
        $request = $this->request(['ad_search_path' => ['path1' => 'new', 'path2' => '']], 'rejected');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertSame('failed', CampaignChange::latest('id')->first()->state);
    }

    public function test_display_targeting_is_listed_approved_and_read_back(): void
    {
        $this->displayGroup = true;
        $this->criteria = [[
            'resourceName' => 'customers/1234567890/adGroupCriteria/201~1', 'adGroup' => 'customers/1234567890/adGroups/201',
            'type' => 'PLACEMENT', 'status' => 'ENABLED', 'negative' => false, 'placement' => ['url' => 'example.com'],
        ]];
        $list = new NamespacedTool('campaign', app(ListCampaignStructure::class));
        $result = json_decode((string) $list->handle(new Request(['include_display_targeting' => true])), true, flags: JSON_THROW_ON_ERROR);
        $this->assertTrue($result['ok']);
        $this->assertSame('example.com', $result['ad_groups'][0]['display_placements'][0]['value']);
        $request = new Request(['entity_type' => 'ad_group', 'id' => '201',
            'display_placements' => [
                ['type' => 'PLACEMENT', 'value' => 'example.com', 'negative' => false],
                ['type' => 'PLACEMENT', 'value' => 'another.example', 'negative' => false],
            ],
            'display_keywords' => [['type' => 'KEYWORD', 'value' => 'shoes', 'negative' => false]],
        ], 'targeting');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['verified']);
        $this->assertCount(3, $this->criteria);
        $this->assertSame('customers/1234567890/adGroupCriteria/201~1', $this->criteria[0]['resourceName']);
    }

    public function test_display_placement_url_scheme_is_normalized_before_comparison_and_write(): void
    {
        $this->displayGroup = true;
        $this->criteria = [[
            'resourceName' => 'customers/1234567890/adGroupCriteria/201~1', 'adGroup' => 'customers/1234567890/adGroups/201',
            'type' => 'PLACEMENT', 'status' => 'ENABLED', 'negative' => false, 'placement' => ['url' => 'example.com'],
        ]];
        $request = new Request(['entity_type' => 'ad_group', 'id' => '201',
            'display_placements' => [
                ['type' => 'PLACEMENT', 'value' => 'https://example.com', 'negative' => false],
                ['type' => 'PLACEMENT', 'value' => 'https://another.example/path', 'negative' => false],
            ],
        ], 'targeting-url');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($result['verified']);
        $this->assertCount(2, $this->criteria);
        $this->assertSame('customers/1234567890/adGroupCriteria/201~1', $this->criteria[0]['resourceName']);
        $this->assertSame('another.example/path', $this->criteria[1]['placement']['url']);
    }

    public function test_display_targeting_rejects_stale_or_paused_criteria_and_unconfirmed_writes(): void
    {
        $this->displayGroup = true;
        $request = new Request(['entity_type' => 'ad_group', 'id' => '201',
            'display_keywords' => [['type' => 'KEYWORD', 'value' => 'shoes', 'negative' => false]],
        ], 'targeting-stale');
        $this->tool()->shouldRequestApproval($request);
        $this->criteria[] = [
            'resourceName' => 'customers/1234567890/adGroupCriteria/201~1', 'adGroup' => 'customers/1234567890/adGroups/201',
            'type' => 'KEYWORD', 'status' => 'ENABLED', 'negative' => false, 'keyword' => ['text' => 'external', 'matchType' => 'BROAD'],
        ];
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('changed since approval', $result['error']);
        $this->criteria[0]['status'] = 'PAUSED';
        $result = $this->edit(new Request($request->all(), 'targeting-paused'));
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('paused', $result['error']);
        $this->assertNoMutation();

        $this->criteria[0]['status'] = 'ENABLED';
        $this->ignoreUpdate = true;
        $request = new Request($request->all(), 'targeting-unconfirmed');
        $this->tool()->shouldRequestApproval($request);
        $result = $this->edit($request);
        $this->assertFalse($result['ok']);
        $this->assertTrue($result['reconciliation_required']);
        $this->assertSame('failed', CampaignChange::latest('id')->first()->state);
    }

    public function test_display_targeting_does_not_mix_edits_or_accept_invalid_topics(): void
    {
        $this->displayGroup = true;
        $result = $this->edit(new Request(['entity_type' => 'ad_group', 'id' => '201',
            'display_topics' => [['type' => 'TOPIC', 'value' => 'guessed topic', 'negative' => false]],
        ], 'bad-topic'));
        $this->assertFalse($result['ok']);
        $result = $this->edit(new Request(['entity_type' => 'ad_group', 'id' => '201',
            'display_topics' => [], 'name' => 'Renamed',
        ], 'mixed'));
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('separately', $result['error']);
        $this->assertNoMutation();
    }
}
