<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Platforms\GoogleRules;
use App\Campaigns\Publisher;
use App\Campaigns\Publishing\GooglePublisher;
use App\Campaigns\Targeting\AudienceSizing;
use App\Campaigns\Targeting\GoogleAdAssets;
use App\Campaigns\Targeting\GoogleUserListSelections;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Campaigns\Targeting\TargetingSelections;
use App\DTOs\LandingPageAnalysis;
use App\Models\Asset;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Laravel\Ai\Tools\Request as ToolRequest;
use RuntimeException;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * Publishing a Google campaign, from the campaign we hold.
 *
 * The point of this class is that the thing reaching Google is the campaign the
 * buyer actually built: its budget, its bidding, its countries, its copy. Before
 * GooglePublisher, Google's create path read a GoogleAdsDraft filled in by a
 * separate agent in a separate chat, so none of that was true.
 *
 * Nothing here talks to Google. Every call is faked, and the assertions are
 * about the payload that would have been sent.
 */
class GooglePublisherTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    private User $user;

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

    protected function setUp(): void
    {
        parent::setUp();

        $this->seedVerifiedCountries();

        $this->user = User::factory()->create();

        // One common internal account from config, the same shape as Meta's
        // single access token. Google is not connected per user.
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['1234567890'],
            'platforms.guardrails.max_daily_budget' => 100,
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '123-456-7890',
        ]);
    }

    /** Every Google call answered with a plausible shape, and recorded. */
    private function fakeGoogle(): void
    {
        // The shape a single-resource mutate actually returns: one result
        // carrying the resource name, not one nested under a per-type key.
        $resource = fn (string $path): array => ['results' => [['resourceName' => $path]]];

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*campaignBudgets:mutate' => Http::response($resource('customers/1234567890/campaignBudgets/111')),
            '*campaigns:mutate' => Http::response($resource('customers/1234567890/campaigns/222')),
            '*adGroups:mutate' => Http::response($resource('customers/1234567890/adGroups/333')),
            '*adGroupAds:mutate' => Http::response($resource('customers/1234567890/adGroupAds/444')),
            // Reached only once a creative actually matches one of Google's
            // shapes. Nothing did before, so this was never needed.
            '*assets:mutate' => Http::response($resource('customers/1234567890/assets/555')),
            '*adGroupCriteria:mutate' => Http::response(['results' => []]),
            '*campaignCriteria:mutate' => Http::response(['results' => []]),
            '*googleAds:searchStream' => fn (Request $request) => Http::response([[
                'results' => str_contains((string) ($request->data()['query'] ?? ''), 'FROM user_list')
                    ? $this->userListResults : [],
            ]]),
        ]);
    }

    private function campaign(array $attributes = []): Campaign
    {
        $brief = Brief::create([
            'user_id' => $this->user->id,
            'conversation_id' => 'conv-google-publish',
            'landing_url' => 'https://iblockads.org/',
            'page_analysis' => [
                'url' => 'https://iblockads.org/',
                'title' => 'iBlockAds',
                'description' => 'Block annoying ads.',
                'headings' => ['iBlockAds'],
                'text' => 'Block annoying ads and browse faster.',
                'keywords' => ['ad blocker', 'block ads', 'browse faster'],
            ],
        ]);

        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'brief_id' => $brief->id,
            'name' => 'iBlockAds Search',
            'platform' => 'google',
            'status' => 'draft',
            'objective' => 'LEADS',
            'ad_account_id' => '1234567890',
            'pixel_id' => 'customers/1234567890/conversionActions/9',
            'landing_url' => 'https://iblockads.org/',
            'budget' => 25,
            'budget_mode' => 'daily',
            'currency' => 'USD',
            'bid_strategy' => 'MAXIMIZE_CONVERSIONS',
            'locations' => ['countries' => ['US', 'GB']],
            'placements' => ['search'],
            'utm' => '',
            ...$attributes,
        ]);

        $asset = Asset::create([
            'user_id' => $this->user->id,
            'kind' => 'image',
            'disk' => 'local',
            'path' => 'a.png',
        ]);

        // Three headlines and two descriptions, which is Google's minimum for a
        // responsive search ad.
        foreach ([
            ['Block Annoying Ads', 'Browse faster on every site.'],
            ['Browse Faster Today', 'Stop trackers and pop ups.'],
            ['Private Browsing Made Easy', 'Browse faster on every site.'],
        ] as [$headline, $description]) {
            CampaignAd::create([
                'campaign_id' => $campaign->id,
                'asset_id' => $asset->id,
                'headline' => $headline,
                'description' => $description,
                'primary_text' => $description,
                'cta' => 'LEARN_MORE',
                'status' => 'draft',
            ]);
        }

        return $campaign->fresh();
    }

    /** The body of the nth call to a mutate endpoint. */
    private function sent(string $endpoint): ?array
    {
        foreach (Http::recorded() as [$request]) {
            /** @var Request $request */
            if (str_contains($request->url(), $endpoint)) {
                return $request->data();
            }
        }

        return null;
    }

    public function test_live_budget_edit_refuses_missing_budget_id_before_google_mutation(): void
    {
        $campaign = $this->campaign([
            'external_campaign_id' => '222',
            'external_ids' => ['campaign_id' => '222'],
            'status' => 'published',
        ]);
        Http::fake();

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Google budget id is missing');

        try {
            app(GooglePublisher::class)->update($campaign, ['budget' => ['from' => '25', 'to' => '30']], 'tester');
        } finally {
            Http::assertNothingSent();
        }
    }

    public function test_it_creates_a_paused_search_campaign_from_our_campaign(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();

        $decision = app(Publisher::class)->propose($campaign, 'tester');
        $this->assertSame('proposed', $decision->state, 'Blocked: '.$decision->reason);

        app(Publisher::class)->approve($decision, 'tester');

        $campaign->refresh();

        $this->assertSame('published', $campaign->status, (string) $campaign->last_error);
        $this->assertSame('222', $campaign->external_campaign_id);

        $sent = $this->sent('campaigns:mutate')['operations'][0]['create'];

        $this->assertSame('PAUSED', $sent['status'], 'A campaign must never be created live.');
        $this->assertSame('SEARCH', $sent['advertisingChannelType']);
        $this->assertSame('iBlockAds Search', $sent['name']);
    }

    /** The budget that reaches Google is the one on the campaign, in micros. */
    public function test_the_budget_is_sent_as_micros_of_our_daily_amount(): void
    {
        $this->fakeGoogle();

        $decision = app(Publisher::class)->propose($this->campaign(), 'tester');
        app(Publisher::class)->approve($decision, 'tester');

        $budget = $this->sent('campaignBudgets:mutate')['operations'][0]['create'];

        $this->assertSame('25000000', $budget['amountMicros']);
    }

    /**
     * A target strategy carries its target.
     *
     * biddingSettings fell through to maximizeConversions for anything it did
     * not recognise, so TARGET_CPA became "spend it all at any price" and the
     * number the user chose was dropped in silence.
     */
    public function test_a_target_cpa_campaign_sends_the_target(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign([
            'bid_strategy' => 'TARGET_CPA',
            'bid_amount' => 12.50,
        ]);

        $decision = app(Publisher::class)->propose($campaign, 'tester');
        $this->assertSame('proposed', $decision->state, 'Blocked: '.$decision->reason);

        app(Publisher::class)->approve($decision, 'tester');

        $sent = $this->sent('campaigns:mutate')['operations'][0]['create'];

        // The target is sent, in the field a Search campaign accepts. This
        // asserted campaign.target_cpa and that maximize_conversions was
        // absent, which is exactly backwards: Google refuses target_cpa on
        // Search outright with OPERATION_NOT_PERMITTED_FOR_CONTEXT, which is
        // what a buyer hit publishing a $0.71 target CPA. Display still takes
        // the old field, and GoogleTakesItsBiddingTargetWhereItLivesTest covers
        // that side.
        $this->assertArrayHasKey('maximizeConversions', $sent, 'The strategy was replaced by a different one.');
        $this->assertSame('12500000', $sent['maximizeConversions']['targetCpaMicros']);
        $this->assertArrayNotHasKey('targetCpa', $sent);
    }

    /**
     * Countries reach Google as its own geo ids.
     *
     * Passing our ISO codes made the lookup search for a country literally
     * named "US", find nothing, and skip the criterion, which is a campaign
     * targeting the entire world with no error anywhere.
     */
    public function test_countries_are_sent_as_google_geo_targets(): void
    {
        $this->fakeGoogle();

        $decision = app(Publisher::class)->propose($this->campaign(), 'tester');
        app(Publisher::class)->approve($decision, 'tester');

        $criteria = $this->sent('campaignCriteria:mutate')['operations'] ?? [];
        $targets = array_map(fn (array $op): string => $op['create']['location']['geoTargetConstant'], $criteria);

        $this->assertContains('geoTargetConstants/2840', $targets, 'US was not targeted.');
        $this->assertContains('geoTargetConstants/2826', $targets, 'GB was not targeted.');
    }

    public function test_selected_google_city_replaces_its_whole_country_criterion(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $mapping = $this->locationMapping('geoTargetConstants/123');
        app(TargetingSelections::class)->addCampaignLocation($campaign, $mapping);

        $panel = view('partials.campaign-panel', [
            'campaign' => $campaign->fresh(),
            'progress' => [],
            'nextStep' => null,
            'blocking' => [],
            'sources' => [],
            'pending' => [],
            'needsRebuild' => [],
            'campaigns' => collect([$campaign]),
            'assets' => collect(),
        ])->render();
        $this->assertStringContainsString('US (selected places only)', $panel);

        $publisher = app(Publisher::class);
        $decision = $publisher->propose($campaign->fresh(), 'tester');
        $this->assertSame(['countries' => ['GB'], 'geo_targets' => ['geoTargetConstants/123']], $decision->params['google_targeting']['locations']);
        $applied = $publisher->approve($decision, 'tester');
        $this->assertTrue($applied->wasApplied(), (string) $applied->reason);

        $criteria = $this->sent('campaignCriteria:mutate')['operations'] ?? [];
        $targets = array_column(array_column($criteria, 'create'), 'location');
        $resources = array_column($targets, 'geoTargetConstant');

        $this->assertContains('geoTargetConstants/123', $resources);
        $this->assertContains('geoTargetConstants/2826', $resources);
        $this->assertNotContains('geoTargetConstants/2840', $resources);
    }

    public function test_stale_google_city_blocks_publish_before_any_mutation(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $mapping = $this->locationMapping('geoTargetConstants/123');
        app(TargetingSelections::class)->addCampaignLocation($campaign, $mapping);
        $mapping->update(['verified_at' => now()->subDays(31)]);

        $decision = app(Publisher::class)->propose($campaign->fresh(), 'tester');

        $this->assertSame('blocked', $decision->state);
        $this->assertStringContainsString('out of date', $decision->reason);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_existing_google_campaign_is_not_blocked_by_an_expired_local_lookup(): void
    {
        $campaign = $this->campaign();
        $mapping = $this->locationMapping('geoTargetConstants/123');
        $selections = app(TargetingSelections::class);
        $selections->addCampaignLocation($campaign, $mapping);
        $campaign->update(['external_campaign_id' => 'live-123', 'status' => 'published']);
        $mapping->update(['verified_at' => now()->subDays(31)]);

        $this->assertSame([], $selections->locationProblems($campaign->fresh()));
    }

    public function test_removing_a_country_does_not_publish_its_old_city_selection(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $selections = app(TargetingSelections::class);
        $selections->addCampaignLocation($campaign, $this->locationMapping('geoTargetConstants/123'));
        $selections->saveCampaignCountries($campaign->fresh(), ['GB']);

        $decision = app(Publisher::class)->propose($campaign->fresh(), 'tester');

        $this->assertSame('blocked', $decision->state);
        $this->assertStringContainsString('invalid', $decision->reason);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_selected_google_state_uses_its_region_criterion(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        app(TargetingSelections::class)->addCampaignLocation($campaign, $this->locationMapping('geoTargetConstants/21167', 'region', 'New York'));

        $publisher = app(Publisher::class);
        $decision = $publisher->propose($campaign->fresh(), 'tester');
        $this->assertTrue($publisher->approve($decision, 'tester')->wasApplied());

        $criteria = $this->sent('campaignCriteria:mutate')['operations'] ?? [];
        $resources = array_column(array_column(array_column($criteria, 'create'), 'location'), 'geoTargetConstant');

        $this->assertContains('geoTargetConstants/21167', $resources);
        $this->assertNotContains('geoTargetConstants/2840', $resources);
    }

    public function test_google_search_dma_narrows_us_using_the_verified_market_id(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $market = $this->locationMapping('geoTargetConstants/200501', 'dma', 'New York, NY');
        $market->update(['parent_external_id' => 'geoTargetConstants/2840']);
        app(TargetingSelections::class)->addGoogleDma($campaign, $market);

        $publisher = app(Publisher::class);
        $decision = $publisher->propose($campaign->fresh(), 'tester');

        $this->assertSame('proposed', $decision->state, (string) $decision->reason);
        $this->assertSame(['countries' => ['GB'], 'geo_targets' => ['geoTargetConstants/200501']], $decision->params['google_targeting']['locations']);
        $this->assertSame('geoTargetConstants/2840', $decision->params['google_targeting']['places'][0]['parent_external_id']);
        $this->assertTrue($publisher->approve($decision, 'tester')->wasApplied());

        $criteria = $this->sent('campaignCriteria:mutate')['operations'] ?? [];
        $resources = array_column(array_column(array_column($criteria, 'create'), 'location'), 'geoTargetConstant');
        $this->assertContains('geoTargetConstants/200501', $resources);
        $this->assertContains('geoTargetConstants/2826', $resources);
        $this->assertNotContains('geoTargetConstants/2840', $resources);
    }

    public function test_google_dma_without_parent_blocks_before_provider_mutation(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $market = $this->locationMapping('geoTargetConstants/200501', 'dma', 'New York, NY');
        $market->update(['parent_external_id' => 'geoTargetConstants/2840']);
        app(TargetingSelections::class)->addGoogleDma($campaign, $market);
        $market->update(['parent_external_id' => null]);

        $decision = app(Publisher::class)->propose($campaign->fresh(), 'tester');

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

    public function test_google_search_radius_sends_exact_microdegree_center_and_keeps_other_country(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        app(TargetingSelections::class)->addGoogleRadius($campaign, 'US', 40.712776, -74.005974, 10, 'mi');

        $publisher = app(Publisher::class);
        $decision = $publisher->propose($campaign->fresh(), 'tester');

        $this->assertSame('proposed', $decision->state, (string) $decision->reason);
        $this->assertSame(['countries' => ['GB'], 'geo_targets' => [], 'proximity_targets' => [[
            'latitude' => '40.712776', 'longitude' => '-74.005974', 'radius' => '10.00', 'radius_unit' => 'mi',
        ]]], $decision->params['google_targeting']['locations']);
        $applied = $publisher->approve($decision, 'tester');
        $this->assertTrue($applied->wasApplied(), (string) $applied->reason);

        $criteria = $this->sent('campaignCriteria:mutate')['operations'] ?? [];
        $this->assertCount(2, $criteria);
        $this->assertSame('geoTargetConstants/2826', $criteria[0]['create']['location']['geoTargetConstant']);
        $this->assertSame([
            'geoPoint' => ['latitudeInMicroDegrees' => 40712776, 'longitudeInMicroDegrees' => -74005974],
            'radius' => 10.0, 'radiusUnits' => 'MILES',
        ], $criteria[1]['create']['proximity']);
    }

    public function test_invalid_google_radius_is_rejected_before_provider_mutation(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();

        $this->expectException(RuntimeException::class);
        try {
            app(TargetingSelections::class)->addGoogleRadius($campaign, 'US', 91, 0, 10, 'km');
        } finally {
            Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
        }
    }

    public function test_google_search_presence_or_interest_is_reviewed_and_sent_to_provider(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        app(TargetingSelections::class)->setGooglePresenceMode($campaign, 'PRESENCE_OR_INTEREST');

        $publisher = app(Publisher::class);
        $decision = $publisher->propose($campaign->fresh(), 'tester');
        $this->assertSame('proposed', $decision->state, (string) $decision->reason);
        $this->assertSame('PRESENCE_OR_INTEREST', $decision->params['google_targeting']['positive_geo_target_type']);
        $this->assertTrue($publisher->approve($decision, 'tester')->wasApplied());

        $sent = $this->sent('campaigns:mutate')['operations'][0]['create'];
        $this->assertSame('PRESENCE_OR_INTEREST', $sent['geoTargetTypeSetting']['positiveGeoTargetType']);
        $this->assertSame('PRESENCE_OR_INTEREST', $campaign->fresh()->published_state['positive_geo_target_type']);
    }

    public function test_adding_a_radius_after_review_requires_new_publish_approval(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $publisher = app(Publisher::class);
        $decision = $publisher->propose($campaign, 'tester');
        app(TargetingSelections::class)->addGoogleRadius($campaign, 'US', 40.712776, -74.005974, 10, 'km');

        $applied = $publisher->approve($decision, 'tester');

        $this->assertFalse($applied->wasApplied());
        $this->assertStringContainsString('changed since review', $applied->reason);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_search_only_advanced_geo_is_blocked_if_campaign_type_changes(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        app(TargetingSelections::class)->setGooglePresenceMode($campaign, 'PRESENCE_OR_INTEREST');
        $campaign->update(['campaign_type' => 'display']);

        $decision = app(Publisher::class)->propose($campaign->fresh(), 'tester');

        $this->assertSame('blocked', $decision->state);
        $this->assertStringContainsString('Search campaigns only', $decision->reason);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_google_search_city_exclusion_keeps_the_country_and_sends_a_negative_criterion(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $excluded = $this->locationMapping('geoTargetConstants/1023191', 'city', 'Chicago');
        app(TargetingSelections::class)->addGoogleLocationExclusion($campaign, $excluded);

        $panel = view('partials.campaign-panel', [
            'campaign' => $campaign->fresh(), 'progress' => [], 'nextStep' => null,
            'blocking' => [], 'sources' => [], 'pending' => [], 'needsRebuild' => [],
            'campaigns' => collect([$campaign]), 'assets' => collect(),
        ])->render();
        $this->assertStringContainsString('Excluded: Chicago, United States', $panel);
        $this->assertStringNotContainsString('US (selected places only)', $panel);

        $publisher = app(Publisher::class);
        $decision = $publisher->propose($campaign->fresh(), 'tester');

        $this->assertSame('proposed', $decision->state, (string) $decision->reason);
        $this->assertSame([
            'countries' => ['US', 'GB'], 'geo_targets' => [],
            'excluded_geo_targets' => ['geoTargetConstants/1023191'],
        ], $decision->params['google_targeting']['locations']);
        $this->assertSame('exclude', $decision->params['google_targeting']['places'][0]['operation']);
        $this->assertTrue($publisher->approve($decision, 'tester')->wasApplied());

        $criteria = $this->sent('campaignCriteria:mutate')['operations'] ?? [];
        $byId = collect($criteria)->keyBy(fn (array $operation): string => $operation['create']['location']['geoTargetConstant'] ?? '');
        $this->assertFalse($byId['geoTargetConstants/2840']['create']['negative'] ?? false);
        $this->assertFalse($byId['geoTargetConstants/2826']['create']['negative'] ?? false);
        $this->assertTrue($byId['geoTargetConstants/1023191']['create']['negative']);
    }

    public function test_stale_google_exclusion_blocks_publish_before_any_mutation(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $excluded = $this->locationMapping('geoTargetConstants/1023191', 'city', 'Chicago');
        app(TargetingSelections::class)->addGoogleLocationExclusion($campaign, $excluded);
        $excluded->update(['verified_at' => now()->subDays(31)]);

        $decision = app(Publisher::class)->propose($campaign->fresh(), 'tester');

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

    public function test_the_same_google_city_cannot_be_included_after_it_was_excluded(): void
    {
        $campaign = $this->campaign();
        $mapping = $this->locationMapping('geoTargetConstants/1023191', 'city', 'Chicago');
        $selections = app(TargetingSelections::class);
        $selections->addGoogleLocationExclusion($campaign, $mapping);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('both included and excluded');
        $selections->addCampaignLocation($campaign->fresh(), $mapping);
    }

    public function test_changing_a_google_exclusion_after_review_blocks_publication(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $publisher = app(Publisher::class);
        $decision = $publisher->propose($campaign, 'tester');
        $excluded = $this->locationMapping('geoTargetConstants/1023191', 'city', 'Chicago');
        app(TargetingSelections::class)->addGoogleLocationExclusion($campaign, $excluded);

        $applied = $publisher->approve($decision, 'tester');

        $this->assertFalse($applied->wasApplied());
        $this->assertStringContainsString('changed since review', $applied->reason);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_google_display_cannot_publish_search_location_exclusions(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $excluded = $this->locationMapping('geoTargetConstants/1023191', 'city', 'Chicago');
        app(TargetingSelections::class)->addGoogleLocationExclusion($campaign, $excluded);
        $campaign->update(['campaign_type' => 'display']);

        $decision = app(Publisher::class)->propose($campaign->fresh(), 'tester');

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

    public function test_google_location_change_after_review_requires_a_new_approval(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $publisher = app(Publisher::class);
        $decision = $publisher->propose($campaign, 'tester');

        app(TargetingSelections::class)->addCampaignLocation($campaign, $this->locationMapping('geoTargetConstants/123'));

        $applied = $publisher->approve($decision, 'tester');

        $this->assertFalse($applied->wasApplied());
        $this->assertStringContainsString('changed since review', $applied->reason);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_a_changed_city_parent_after_review_blocks_google_publication(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $mapping = $this->locationMapping('geoTargetConstants/123');
        $mapping->update(['parent_external_id' => 'geoTargetConstants/1']);
        app(TargetingSelections::class)->addCampaignLocation($campaign, $mapping);

        $publisher = app(Publisher::class);
        $proposal = $publisher->propose($campaign->fresh(), 'tester');
        $this->assertSame('proposed', $proposal->state);
        $this->assertSame('geoTargetConstants/1', $proposal->params['google_targeting']['places'][0]['parent_external_id']);

        $mapping->update(['parent_external_id' => 'geoTargetConstants/2']);
        $decision = $publisher->approve($proposal, 'tester');

        $this->assertFalse($decision->wasApplied());
        $this->assertStringContainsString('changed since review', $decision->reason);
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    private function locationMapping(string $resourceName, string $type = 'city', string $name = 'Springfield'): PlatformLocation
    {
        $city = Location::factory()->create([
            'type' => $type,
            'name' => $name,
            'country_code' => 'US',
            'iso_code' => null,
            'source' => 'google',
            'source_key' => $resourceName,
        ]);

        return PlatformLocation::factory()->create([
            'location_id' => $city->getKey(),
            'platform' => 'google',
            'external_id' => $resourceName,
            'provider_name' => $name.', United States',
        ]);
    }

    /** The copy written in chat becomes the responsive search ad's variations. */
    public function test_the_ad_carries_our_headlines_and_descriptions(): void
    {
        $this->fakeGoogle();

        $decision = app(Publisher::class)->propose($this->campaign(), 'tester');
        app(Publisher::class)->approve($decision, 'tester');

        $ad = $this->sent('adGroupAds:mutate')['operations'][0]['create'];
        $headlines = array_column($ad['ad']['responsiveSearchAd']['headlines'], 'text');

        $this->assertContains('Block Annoying Ads', $headlines);
        $this->assertCount(3, $headlines);
        $this->assertSame('PAUSED', $ad['status']);
        $this->assertSame('https://iblockads.org/', $ad['ad']['finalUrls'][0]);
    }

    /** Keywords come from the landing page, which is the only place they exist. */
    public function test_keywords_come_from_the_landing_page_analysis(): void
    {
        $this->fakeGoogle();

        $decision = app(Publisher::class)->propose($this->campaign(), 'tester');
        app(Publisher::class)->approve($decision, 'tester');

        $keywords = array_map(
            fn (array $op): string => $op['create']['keyword']['text'],
            $this->sent('adGroupCriteria:mutate')['operations'],
        );

        $this->assertContains('ad blocker', $keywords);
    }

    public function test_reviewed_search_keywords_send_exact_match_types_and_negatives(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        app(SearchKeywordSelections::class)->save($campaign, [
            ['text' => 'ad blocker', 'match_type' => 'EXACT', 'negative' => false],
            ['text' => 'free ads', 'match_type' => 'PHRASE', 'negative' => true],
        ], 0);

        $decision = app(Publisher::class)->propose($campaign, 'tester');
        $this->assertSame('proposed', $decision->state, (string) $decision->reason);
        $this->assertSame('EXACT', $decision->params['google_targeting']['search_keywords'][0]['match_type']);
        app(Publisher::class)->approve($decision, 'tester');

        $criteria = array_column($this->sent('adGroupCriteria:mutate')['operations'], 'create');
        $this->assertSame([
            ['text' => 'ad blocker', 'matchType' => 'EXACT'],
            ['text' => 'free ads', 'matchType' => 'PHRASE'],
        ], array_column($criteria, 'keyword'));
        $this->assertSame([false, true], array_column($criteria, 'negative'));
        $this->assertSame('published', $campaign->fresh()->status);
    }

    public function test_a_changed_keyword_selection_blocks_old_publish_approval_before_mutation(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $selections = app(SearchKeywordSelections::class);
        $selections->save($campaign, [['text' => 'ad blocker', 'match_type' => 'EXACT']], 0);
        $decision = app(Publisher::class)->propose($campaign, 'tester');

        $selections->save($campaign, [['text' => 'browse faster', 'match_type' => 'BROAD']], 2);
        app(Publisher::class)->approve($decision, 'tester');

        $this->assertSame('blocked', $decision->fresh()->state);
        $this->assertNull($campaign->fresh()->external_campaign_id);
        Http::assertNothingSent();
    }

    public function test_owned_search_remarketing_list_is_reviewed_and_sent_as_targeting(): void
    {
        $this->userListResults = [[
            'userList' => [
                'resourceName' => 'customers/1234567890/userLists/77',
                'name' => 'Recent visitors', 'type' => 'REMARKETING',
                'accessReason' => 'OWNED', 'eligibleForSearch' => true,
                'membershipStatus' => 'OPEN', 'accountUserListStatus' => 'ENABLED',
                'sizeForSearch' => '2500',
            ],
        ]];
        $this->fakeGoogle();
        $campaign = $this->campaign();
        app(GoogleUserListSelections::class)->save($campaign, 'customers/1234567890/userLists/77', 'include', 0);

        $decision = app(Publisher::class)->propose($campaign, 'tester');
        $this->assertSame('proposed', $decision->state, (string) $decision->reason);
        $this->assertSame('Recent visitors', $decision->params['google_targeting']['user_lists'][0]['name']);
        app(Publisher::class)->approve($decision, 'tester');

        $this->assertSame('published', $campaign->fresh()->status);
        $adGroup = $this->sent('adGroups:mutate')['operations'][0]['create'];
        $this->assertSame([['targetingDimension' => 'AUDIENCE', 'bidOnly' => false]],
            $adGroup['targetingSetting']['targetRestrictions']);

        $audienceRequests = Http::recorded(fn (Request $request): bool => str_contains($request->url(), 'adGroupCriteria:mutate')
            && isset($request->data()['operations'][0]['create']['userList']));
        $this->assertCount(1, $audienceRequests);
        $this->assertSame('customers/1234567890/userLists/77',
            $audienceRequests->first()[0]->data()['operations'][0]['create']['userList']['userList']);
    }

    public function test_unavailable_remarketing_list_blocks_publish_before_provider_mutation(): void
    {
        $this->userListResults = [[
            'userList' => [
                'resourceName' => 'customers/1234567890/userLists/77',
                'name' => 'Recent visitors', 'type' => 'REMARKETING',
                'accessReason' => 'OWNED', 'eligibleForSearch' => true,
                'membershipStatus' => 'OPEN', 'accountUserListStatus' => 'ENABLED',
            ],
        ]];
        $this->fakeGoogle();
        $campaign = $this->campaign();
        app(GoogleUserListSelections::class)->save($campaign, 'customers/1234567890/userLists/77', 'include', 0);
        $decision = app(Publisher::class)->propose($campaign, 'tester');

        $this->userListResults[0]['userList']['membershipStatus'] = 'CLOSED';

        try {
            app(Publisher::class)->approve($decision, 'tester');
            $this->fail('Publishing accepted a closed list.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('unavailable or changed', $exception->getMessage());
        }

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

    public function test_a_different_customer_user_list_is_rejected_before_a_provider_read(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign();

        try {
            app(GoogleUserListSelections::class)->save(
                $campaign, 'customers/9999999999/userLists/77', 'include', 0,
            );
            $this->fail('Another customer’s audience was accepted.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('does not belong', $exception->getMessage());
        }

        $this->assertNull($campaign->fresh()->targetingSet);
        Http::assertNothingSent();
    }

    public function test_main_chat_offers_only_eligible_remarketing_lists_and_saves_the_exact_choice(): void
    {
        $this->userListResults = [
            ['userList' => [
                'resourceName' => 'customers/1234567890/userLists/77',
                'name' => 'Recent visitors', 'type' => 'REMARKETING',
                'accessReason' => 'OWNED', 'eligibleForSearch' => true,
                'membershipStatus' => 'OPEN', 'accountUserListStatus' => 'ENABLED',
            ]],
            ['userList' => [
                'resourceName' => 'customers/1234567890/userLists/88',
                'name' => 'Closed visitors', 'type' => 'REMARKETING',
                'accessReason' => 'OWNED', 'eligibleForSearch' => true,
                'membershipStatus' => 'CLOSED', 'accountUserListStatus' => 'ENABLED',
            ]],
        ];
        $this->fakeGoogle();
        $this->actingAs($this->user);
        $campaign = $this->campaign();
        app(Workspace::class)->bindTo('audience-chat');
        app(Workspace::class)->focusOn($campaign);
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__choose_audience_list');
        $this->assertNotNull($tool);

        $listing = json_decode((string) $tool->handle(new ToolRequest([])), true);
        $this->assertTrue($listing['ok']);
        $this->assertTrue($listing['lists'][0]['available']);
        $this->assertFalse($listing['lists'][1]['available']);
        $this->assertCount(2, app(Choices::class)->all()[0]['options']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $this->userListResults = [$this->userListResults[0]];

        $saved = json_decode((string) $tool->handle(new ToolRequest([
            'resource_name' => 'customers/1234567890/userLists/77',
            'operation' => 'include', 'expected_revision' => $listing['revision'],
        ])), true);

        $this->assertTrue($saved['ok'], (string) ($saved['error'] ?? ''));
        $this->assertSame('customers/1234567890/userLists/77', $saved['selected'][0]['resource_name']);
    }

    public function test_audience_sizing_is_per_list_cached_by_revision_and_never_claims_campaign_reach(): void
    {
        Cache::flush();
        $this->userListResults = [[
            'userList' => [
                'resourceName' => 'customers/1234567890/userLists/77',
                'name' => 'Recent visitors', 'type' => 'REMARKETING',
                'accessReason' => 'OWNED', 'eligibleForSearch' => true,
                'membershipStatus' => 'OPEN', 'accountUserListStatus' => 'ENABLED',
                'sizeForSearch' => '2500',
            ],
        ]];
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $selections = app(GoogleUserListSelections::class);
        $selections->save($campaign, 'customers/1234567890/userLists/77', 'include', 0);

        $first = app(AudienceSizing::class)->review($campaign);
        $this->assertSame('fresh', $first['status']);
        $this->assertSame(2500, $first['list_sizes'][0]['users']);
        $this->assertSame('unavailable', $first['campaign_reach_status']);
        $this->assertSame($first, app(AudienceSizing::class)->review($campaign));

        config(['platforms.guardrails.allowed_ad_accounts' => []]);
        $revoked = app(AudienceSizing::class)->review($campaign);
        $this->assertSame('error', $revoked['status']);
        $this->assertSame([], $revoked['list_sizes']);
        config(['platforms.guardrails.allowed_ad_accounts' => ['1234567890']]);

        $reads = Http::recorded(fn (Request $request): bool => str_contains((string) ($request->data()['query'] ?? ''), 'FROM user_list'));
        $this->assertCount(2, $reads, 'Selection and one size fetch should be the only provider reads.');

        $refreshed = app(AudienceSizing::class)->review($campaign, refresh: true);
        $this->assertSame('fresh', $refreshed['status']);
        $this->assertCount(3, Http::recorded(fn (Request $request): bool => str_contains((string) ($request->data()['query'] ?? ''), 'FROM user_list')));

        $this->userListResults[0]['userList']['name'] = 'Renamed by provider';
        $renamed = app(AudienceSizing::class)->review($campaign, refresh: true);
        $this->assertSame('unavailable', $renamed['list_sizes'][0]['status']);
        $this->assertNull($renamed['list_sizes'][0]['users']);

        $selections->remove($campaign, 'customers/1234567890/userLists/77', 2);
        $changed = app(AudienceSizing::class)->review($campaign);
        $this->assertSame('unavailable', $changed['status']);
        $this->assertSame([], $changed['list_sizes']);
    }

    public function test_an_account_changed_draft_can_remove_a_stale_audience_list(): void
    {
        $this->userListResults = [[
            'userList' => [
                'resourceName' => 'customers/1234567890/userLists/77',
                'name' => 'Recent visitors', 'type' => 'REMARKETING',
                'accessReason' => 'OWNED', 'eligibleForSearch' => true,
                'membershipStatus' => 'OPEN', 'accountUserListStatus' => 'ENABLED',
            ],
        ]];
        $this->fakeGoogle();
        $campaign = $this->campaign();
        $selections = app(GoogleUserListSelections::class);
        $selections->save($campaign, 'customers/1234567890/userLists/77', 'include', 0);
        $campaign->update(['ad_account_id' => '9999999999']);

        $set = $selections->remove($campaign, 'customers/1234567890/userLists/77', 2);

        $this->assertSame([], $set->options['google_user_lists']);
        $this->assertSame([], $selections->selected($campaign->fresh()));
    }

    /**
     * A failure removes the budget as well as the campaign.
     *
     * A Google campaign budget is an account level object the campaign points
     * at, so deleting the campaign alone leaves one behind on every failure.
     */
    public function test_a_failure_part_way_through_removes_what_was_created(): void
    {
        $resource = fn (string $path): array => ['results' => [['resourceName' => $path]]];

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            // The second response in each sequence is the rollback's remove.
            '*campaignBudgets:mutate' => Http::sequence()
                ->push($resource('customers/1234567890/campaignBudgets/111'))
                ->push(['results' => []]),
            '*campaigns:mutate' => Http::sequence()
                ->push($resource('customers/1234567890/campaigns/222'))
                ->push(['results' => []]),
            // The ad group is where it breaks, after campaign and budget exist.
            '*adGroups:mutate' => Http::response(['error' => ['message' => 'Ad group refused']], 400),
            '*campaignCriteria:mutate' => Http::response(['results' => []]),
            '*googleAds:searchStream' => Http::response([['results' => []]]),
        ]);

        $campaign = $this->campaign();
        $decision = app(Publisher::class)->propose($campaign, 'tester');

        try {
            app(Publisher::class)->approve($decision, 'tester');
        } catch (\Throwable) {
            // Publisher rethrows after rolling back, which is the Meta behaviour too.
        }

        $this->assertSame('failed', $campaign->fresh()->status);

        $removals = [];

        foreach (Http::recorded() as [$request]) {
            $data = $request->data();

            if (isset($data['operations'][0]['remove'])) {
                $removals[] = $data['operations'][0]['remove'];
            }
        }

        $this->assertContains('customers/1234567890/campaigns/222', $removals, 'The campaign was left behind.');
        $this->assertContains('customers/1234567890/campaignBudgets/111', $removals, 'The budget was orphaned.');
    }

    /**
     * Picking Display builds a Display campaign, not a Search one.
     *
     * The payload hardcoded 'search'. Offering three types while always
     * building one would have been the worst kind of wrong: it succeeds, and
     * nothing anywhere says the choice was ignored.
     */
    /**
     * Real image bytes at the shapes Google takes.
     *
     * The shared fixture points its asset at a path nothing ever wrote, so the
     * publisher found no image at all and both slots came out empty. That is
     * why the Display build was never exercised against a real creative, and
     * why an exact-size match that silently dropped everything else went
     * unnoticed.
     */
    private function attachDisplayImages(Campaign $campaign): void
    {
        Storage::fake('local');

        $ads = $campaign->ads()->orderBy('id')->get();

        foreach ([['landscape.png', 1200, 628], ['square.png', 1200, 1200]] as $index => [$name, $width, $height]) {
            $image = imagecreatetruecolor($width, $height);
            ob_start();
            imagepng($image);
            $bytes = (string) ob_get_clean();
            imagedestroy($image);

            Storage::disk('local')->put($name, $bytes);

            $asset = Asset::create([
                'user_id' => $this->user->id,
                'kind' => 'image',
                'disk' => 'local',
                'path' => $name,
            ]);

            $ads[$index]->update(['asset_id' => $asset->id]);
        }
    }

    public function test_choosing_display_builds_a_display_campaign(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign(['campaign_type' => 'display']);
        $this->attachDisplayImages($campaign);

        $publisher = app(GooglePublisher::class);
        $created = [];

        try {
            $publisher->create($campaign, 'tester', $created);
        } catch (\Throwable) {
            // The fake does not model every Display response; what is asserted
            // is the payload that went out, not that the fake satisfied it.
        }

        $sent = $this->sent('campaigns:mutate')['operations'][0]['create'] ?? [];

        $this->assertSame('DISPLAY', $sent['advertisingChannelType'] ?? null);
        $this->assertSame('PAUSED', $sent['status'] ?? null);
    }

    /** And Search still builds Search, which is what makes the branch a choice. */
    public function test_choosing_search_still_builds_a_search_campaign(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign(['campaign_type' => 'search']);

        $decision = app(Publisher::class)->propose($campaign, 'tester');
        app(Publisher::class)->approve($decision, 'tester');

        $sent = $this->sent('campaigns:mutate')['operations'][0]['create'];

        $this->assertSame('SEARCH', $sent['advertisingChannelType']);
    }

    /**
     * The conversion action does not go out as selective optimization.
     *
     * It used to, on Search, Display and Performance Max alike, and Google
     * refuses it on Search: publishing campaign 54 on 23 Sep failed the first
     * mutate with OPERATION_NOT_PERMITTED_FOR_CONTEXT and named no field.
     * Selective optimization belongs to App campaigns.
     *
     * Sending nothing is not a loss: a campaign with no conversion settings of
     * its own uses the account's conversion goals. Narrowing a campaign to one
     * action needs CampaignConversionGoal resources and is not built. The
     * action is still asked for and still stored, because the gate reads it and
     * it is the answer to what counts as success; it just does not reach Google.
     */
    public function test_the_conversion_action_is_not_sent_as_selective_optimization(): void
    {
        $this->fakeGoogle();

        $decision = app(Publisher::class)->propose($this->campaign(), 'tester');
        app(Publisher::class)->approve($decision, 'tester');

        $sent = $this->sent('campaigns:mutate')['operations'][0]['create'];

        $this->assertArrayNotHasKey(
            'selectiveOptimization',
            $sent,
            'Google refuses this on a Search campaign and makes nothing at all.',
        );
    }

    /**
     * The campaign is still created, which is the part that was failing.
     *
     * Publishing campaign 54 on the live account died on the first mutate with
     * OPERATION_NOT_PERMITTED_FOR_CONTEXT and no field named, so the campaign,
     * its budget and everything under it never existed.
     */
    public function test_a_search_campaign_is_created_with_its_bidding_intact(): void
    {
        $this->fakeGoogle();

        $decision = app(Publisher::class)->propose($this->campaign(), 'tester');
        app(Publisher::class)->approve($decision, 'tester');

        $sent = $this->sent('campaigns:mutate')['operations'][0]['create'];

        $this->assertSame('SEARCH', $sent['advertisingChannelType'] ?? null);
        $this->assertSame('PAUSED', $sent['status'] ?? null);
        $this->assertArrayHasKey('maximizeConversions', $sent);
    }

    /** The networks the buyer picked, not a hardcoded set. */
    public function test_the_chosen_networks_are_sent(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign(['placements' => ['search', 'display']]);

        $decision = app(Publisher::class)->propose($campaign, 'tester');
        app(Publisher::class)->approve($decision, 'tester');

        $networks = $this->sent('campaigns:mutate')['operations'][0]['create']['networkSettings'];

        $this->assertTrue($networks['targetGoogleSearch']);
        $this->assertTrue($networks['targetContentNetwork'], 'Display was chosen and not sent.');
        $this->assertFalse($networks['targetSearchNetwork'], 'Search partners was not chosen.');
    }

    /** An end date has to reach Google, or the campaign runs until somebody notices. */
    public function test_the_schedule_is_sent(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign(['ends_at' => now()->addDays(30)]);

        $decision = app(Publisher::class)->propose($campaign, 'tester');
        app(Publisher::class)->approve($decision, 'tester');

        $sent = $this->sent('campaigns:mutate')['operations'][0]['create'];

        $this->assertSame(now()->addDays(30)->format('Y-m-d 23:59:59'), $sent['endDateTime'] ?? null);
    }

    /** A platform with no publisher is refused by name, not by exception. */
    public function test_a_platform_with_no_publisher_is_refused_clearly(): void
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Taboola one',
            'platform' => 'taboola',
            'status' => 'draft',
        ]);

        $decision = app(Publisher::class)->propose($campaign, 'tester');
        $result = app(Publisher::class)->approve($decision, 'tester');

        $this->assertSame('blocked', $result->state);
        $this->assertSame('draft', $campaign->fresh()->status, 'The campaign was left mid publish.');
    }

    /**
     * Six descriptions do not reach Google, which takes four.
     *
     * Publishing campaign 47 on 23 Sep failed with "Request contains an invalid
     * argument. (TOO_MANY)". Three ads, each contributing its description and
     * its primary text, made six descriptions; a responsive search ad holds
     * four. The error names no field, so nothing in it pointed at the copy, and
     * the campaign sat at "Ready to publish" with no way forward.
     *
     * The factory above gives every ad the same text for both fields, so
     * unique() collapsed them to three and no test ever saw six. Real ad copy
     * differs, which is the whole point of writing it.
     */
    public function test_descriptions_are_capped_at_what_a_responsive_search_ad_holds(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign();

        foreach ($campaign->ads as $index => $ad) {
            $ad->update(['primary_text' => 'A different primary text number '.$index]);
        }

        $publisher = app(GooglePublisher::class);
        $created = [];

        try {
            $publisher->create($campaign->fresh(), 'tester', $created);
        } catch (\Throwable) {
            // What is asserted is the payload that went out.
        }

        $ad = $this->sent('adGroupAds:mutate')['operations'][0]['create']['ad']['responsiveSearchAd'] ?? [];

        $this->assertLessThanOrEqual(
            GoogleRules::MAX_DESCRIPTIONS,
            count($ad['descriptions'] ?? []),
            'Google refuses the whole request when there are more than four.',
        );

        $this->assertGreaterThanOrEqual(
            2,
            count($ad['descriptions'] ?? []),
            'Capping must not take it below Google\'s minimum of two.',
        );

        $this->assertLessThanOrEqual(
            GoogleRules::MAX_HEADLINES,
            count($ad['headlines'] ?? []),
        );
    }

    /**
     * Every level Google creates is paused, not just the campaign and the ad.
     *
     * The ad group was created ENABLED. Nothing served through it, because a
     * paused campaign stops everything and the ad was paused as well, so there
     * were two independent stops. But it made createPausedCampaign() untrue of
     * a third of what it creates, and it differed from Meta, where campaign,
     * ad set and ad are all paused. Seen on the live account on 23 Sep:
     * campaign 24285639010 PAUSED, ad 825696152281 PAUSED, ad group
     * 203150420849 ENABLED.
     *
     * Keywords stay enabled on purpose: they are criteria rather than a serving
     * level, and the paused ad group above them is what stops them.
     */
    public function test_every_level_google_creates_is_paused(): void
    {
        $this->fakeGoogle();

        $publisher = app(GooglePublisher::class);
        $created = [];

        try {
            $publisher->create($this->campaign(), 'tester', $created);
        } catch (\Throwable) {
            // The payloads that went out are what is asserted.
        }

        foreach (['campaigns:mutate', 'adGroups:mutate', 'adGroupAds:mutate'] as $endpoint) {
            $sent = $this->sent($endpoint)['operations'][0]['create'] ?? null;

            $this->assertNotNull($sent, "Nothing was sent to {$endpoint}.");
            $this->assertSame('PAUSED', $sent['status'] ?? null, "{$endpoint} was created enabled.");
        }
    }

    /** Ad group omits cpcBidMicros on Smart Bidding (Target CPA) to prevent OPERATION_NOT_PERMITTED_FOR_CONTEXT. */
    public function test_ad_group_omits_cpc_bid_on_smart_bidding_campaigns(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign([
            'bid_strategy' => 'TARGET_CPA',
            'bid_amount' => '1.50',
        ]);

        $publisher = app(GooglePublisher::class);
        $created = [];

        try {
            $publisher->create($campaign, 'tester', $created);
        } catch (\Throwable) {
        }

        $adGroup = $this->sent('adGroups:mutate')['operations'][0]['create'] ?? [];
        $this->assertArrayNotHasKey('cpcBidMicros', $adGroup, 'Smart bidding ad group must not send cpcBidMicros');
    }

    public function test_unmapped_countries_are_refused_before_any_google_request(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign(['locations' => ['countries' => ['US', 'ZA']]]);
        $created = [];

        try {
            app(GooglePublisher::class)->create($campaign, 'test', $created);
            $this->fail('An unmapped country must not be silently omitted.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('country mapping is not available for: ZA', $exception->getMessage());
        }

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

    /**
     * An account nobody permitted is still refused, by the guard that is for it.
     *
     * This asserted the publisher refused any account other than the configured
     * one. That check pre-dated the chat asking which child of the manager to
     * use, and once it did, the check contradicted the question: a buyer picked
     * an account, answered everything else, and was told at the publish step
     * that their own answer did not match - with no step to go back to.
     *
     * The account on the campaign now wins, so what decides whether it may be
     * touched is the allow list, which is the thing that was always meant to
     * decide it. Refusal still happens before any mutate, and the message now
     * names the real reason and what to change.
     */
    public function test_an_account_outside_the_allow_list_is_refused_before_creation(): void
    {
        $this->fakeGoogle();
        $campaign = $this->campaign(['ad_account_id' => '9876543210']);
        $created = [];

        try {
            app(GooglePublisher::class)->create($campaign, 'test', $created);
            $this->fail('A campaign for an account nobody permitted must not be published.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('9876543210 is not on the allowed list', $exception->getMessage());
        }

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

    /** And a permitted account other than the configured default is published to. */
    public function test_a_permitted_account_other_than_the_default_is_used(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => ['3460855874', '1234567890']]);

        $this->fakeGoogle();
        $campaign = $this->campaign(['ad_account_id' => '1234567890']);
        $created = [];

        app(GooglePublisher::class)->create($campaign, 'test', $created);

        $sent = collect(Http::recorded())
            ->map(fn (array $pair): string => (string) $pair[0]->url())
            ->filter(fn (string $url): bool => str_contains($url, ':mutate'))
            ->values();

        $this->assertNotEmpty($sent, 'the campaign must actually be built');
        $this->assertTrue(
            $sent->every(fn (string $url): bool => str_contains($url, 'customers/1234567890/')),
            'every write must go to the account the buyer chose, not the configured default'
        );
    }

    /**
     * A Display publish that breaks after the campaign leaves ids to clean up.
     *
     * The by-reference $created is the whole mechanism for that, and only the
     * Search branch ever received it: createPausedDisplayCampaign and
     * createPausedPerformanceMaxCampaign were called without it, so a failure
     * at the ad group or the ad left a campaign and an orphan budget on the
     * account while $created stayed empty. rollBack() then iterated two blank
     * ids, removed nothing, and returned [] - so the decision recorded that
     * nothing was left behind, and the buyer was told their account was clean
     * while it was being billed for a budget nobody could find.
     */
    public function test_a_display_failure_after_the_campaign_still_reports_what_exists(): void
    {
        // Registered before fakeGoogle(), because Http matches the first stub
        // that fits and fakeGoogle() answers adGroups:mutate with a success.
        Http::fake(['*adGroups:mutate' => Http::response(['error' => ['message' => 'refused']], 400)]);
        $this->fakeGoogle();

        $campaign = $this->campaign(['campaign_type' => 'display']);
        $this->attachDisplayImages($campaign);
        $created = [];

        try {
            app(GooglePublisher::class)->create($campaign, 'test', $created);
            $this->fail('The ad group was refused, so this must not report success.');
        } catch (\Throwable) {
            // The failure itself is not what is under test.
        }

        $this->assertSame('111', $created['budget_id'] ?? null, 'the budget exists and must be recoverable');
        $this->assertSame('222', $created['campaign_id'] ?? null, 'the campaign exists and must be recoverable');
    }

    /** The same for Performance Max, which fails at its asset group. */
    public function test_a_performance_max_failure_still_reports_what_exists(): void
    {
        Http::fake(['*assetGroups:mutate' => Http::response(['error' => ['message' => 'refused']], 400)]);
        $this->fakeGoogle();

        $campaign = $this->campaign(['campaign_type' => 'performance_max']);
        $this->attachDisplayImages($campaign);
        // Performance Max refuses an asset group with no logo before it calls
        // Google at all, so without this the publish never reaches the budget
        // and the test would prove nothing.
        $campaign->update(['meta' => [
            ...(array) $campaign->meta,
            'google_logo_asset_id' => $campaign->ads()->orderBy('id')->get()[1]->asset_id,
        ]]);
        $created = [];

        try {
            app(GooglePublisher::class)->create($campaign, 'test', $created);
            $this->fail('The asset group was refused, so this must not report success.');
        } catch (\Throwable) {
            // The failure itself is not what is under test.
        }

        $this->assertSame('111', $created['budget_id'] ?? null, 'the budget exists and must be recoverable');
        $this->assertSame('222', $created['campaign_id'] ?? null, 'the campaign exists and must be recoverable');
    }

    /**
     * Clearing the end date is sent to Google, not silently dropped.
     *
     * $fields was array_filter'd on "not null", which removed both date keys
     * whenever a buyer cleared one, and updateLiveCampaign returns early on an
     * empty set. So "drop the end date and let it keep running" made no call at
     * all, while CampaignUpdater went on to write the new published_state and
     * mark the change applied: the campaign stopped serving on its old end date
     * and our record said it had none. Google clears a field by carrying it in
     * the update mask with a null value.
     */
    public function test_clearing_the_end_date_is_actually_sent_to_google(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign([
            'external_campaign_id' => '222',
            'external_ids' => ['campaign_id' => '222', 'budget_id' => '111'],
            'ends_at' => null,
        ]);

        app(GooglePublisher::class)->update($campaign, [
            'ends_at' => ['from' => '2026-11-30 00:00:00', 'to' => null],
        ], 'tester');

        $sent = $this->sent('campaigns:mutate')['operations'][0]['update'] ?? [];
        $mask = $this->sent('campaigns:mutate')['operations'][0]['updateMask'] ?? '';

        $this->assertArrayHasKey('endDateTime', $sent, 'the cleared date must be sent');
        $this->assertNull($sent['endDateTime'], 'Google clears a field with a null in the mask');
        $this->assertStringContainsString('endDateTime', (string) $mask);
    }

    /** A field that was simply not asked about is still left out. */
    public function test_a_field_that_was_not_changed_is_not_sent(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign([
            'external_campaign_id' => '222',
            'external_ids' => ['campaign_id' => '222', 'budget_id' => '111'],
        ]);

        app(GooglePublisher::class)->update($campaign, [
            'name' => ['from' => 'Old', 'to' => 'New'],
        ], 'tester');

        $sent = $this->sent('campaigns:mutate')['operations'][0]['update'] ?? [];

        $this->assertSame('New', $sent['name'] ?? null);
        $this->assertArrayNotHasKey('endDateTime', $sent);
        $this->assertArrayNotHasKey('startDateTime', $sent);
    }

    /**
     * Sitelinks and callouts the buyer approved reach Google on publish.
     *
     * The derivation is covered in GoogleCampaignsCarrySitelinksAndCallouts;
     * what matters here is that they are actually sent, as SITELINK and CALLOUT
     * assets with campaignAssets rows pointing the campaign at them.
     *
     * The approval is the part this test used to be missing, and the part that
     * mattered: it asserted that assets derived from the page went out with
     * nobody having seen them, which is what put "Login to continue" and a
     * stock ticker on a live ad. See the sibling test below.
     */
    public function test_sitelinks_and_callouts_are_sent_with_the_campaign(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign();
        $campaign->brief?->rememberPageAnalysis(new LandingPageAnalysis(
            url: 'https://example.com/landing',
            title: 'Example',
            description: '',
            headings: [],
            text: '',
            keywords: ['widgets'],
            subheadings: ['Blocks Trackers', 'No Account Needed'],
            callsToAction: [],
            sameHostLinks: [
                ['url' => 'https://example.com/features', 'label' => 'Features'],
                ['url' => 'https://example.com/pricing', 'label' => 'Pricing'],
            ],
        ));

        // What the buyer ticked on the copy screen. Without this nothing is
        // sent, which is the point of the sibling test.
        $campaign->update(['meta' => [...(array) $campaign->meta, 'google_ad_assets' => [
            'sitelinks' => ['Features'],
            'callouts' => ['Blocks Trackers'],
        ]]]);

        $created = [];

        try {
            app(GooglePublisher::class)->create($campaign->fresh(), 'tester', $created);
        } catch (\Throwable) {
            // The fake does not model every response; what is asserted is what
            // went out.
        }

        $assetPayloads = collect(Http::recorded())
            ->filter(fn (array $pair): bool => str_contains((string) $pair[0]->url(), 'assets:mutate'))
            ->map(fn (array $pair): array => (array) data_get($pair[0]->data(), 'operations.0.create'))
            ->values();

        $types = $assetPayloads->pluck('type')->filter()->values()->all();

        $this->assertContains('SITELINK', $types, 'no sitelink asset was created');
        $this->assertContains('CALLOUT', $types, 'no callout asset was created');

        $sitelink = $assetPayloads->firstWhere('type', 'SITELINK');
        $this->assertSame('Features', data_get($sitelink, 'sitelinkAsset.linkText'));
        $this->assertSame(['https://example.com/features'], data_get($sitelink, 'finalUrls'));

        $callout = $assetPayloads->firstWhere('type', 'CALLOUT');
        $this->assertSame('Blocks Trackers', data_get($callout, 'calloutAsset.calloutText'));

        $fieldTypes = collect(Http::recorded())
            ->filter(fn (array $pair): bool => str_contains((string) $pair[0]->url(), 'campaignAssets:mutate'))
            ->flatMap(fn (array $pair): array => (array) data_get($pair[0]->data(), 'operations'))
            ->pluck('create.fieldType')->filter()->unique()->values()->all();

        $this->assertContains('SITELINK', $fieldTypes, 'the sitelink was never linked to the campaign');
        $this->assertContains('CALLOUT', $fieldTypes, 'the callout was never linked to the campaign');
    }

    /**
     * And nothing the buyer has not approved is sent at all.
     *
     * The page offers these; that is not the same as anybody wanting them.
     * Mohsin's campaign went out with sitelinks reading "PRSO Peraso Inc.
     * +54.13%" and "Login to continue" because the page linked to them, and he
     * found out from Google Ads. Ad assets are published copy, and copy is
     * chosen.
     */
    public function test_assets_the_buyer_never_approved_are_not_sent(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign();
        $campaign->brief?->rememberPageAnalysis(new LandingPageAnalysis(
            url: 'https://example.com/landing',
            title: 'Example',
            description: '',
            headings: [],
            text: '',
            keywords: ['widgets'],
            subheadings: ['Blocks Trackers', 'No Account Needed'],
            callsToAction: [],
            sameHostLinks: [
                ['url' => 'https://example.com/features', 'label' => 'Features'],
                ['url' => 'https://example.com/pricing', 'label' => 'Pricing'],
            ],
        ));

        // The premise: the page really does offer them.
        $this->assertNotSame([], app(GoogleAdAssets::class)
            ->sitelinksFor($campaign->fresh()->brief?->pageAnalysis()));

        $created = [];

        try {
            app(GooglePublisher::class)->create($campaign->fresh(), 'tester', $created);
        } catch (\Throwable) {
            // As above.
        }

        $assetCalls = collect(Http::recorded())
            ->filter(fn (array $pair): bool => str_contains((string) $pair[0]->url(), 'assets:mutate')
                || str_contains((string) $pair[0]->url(), 'campaignAssets:mutate'))
            ->count();

        $this->assertSame(0, $assetCalls, 'assets were created for a campaign nobody approved them on');
    }

    /**
     * A campaign with nothing to offer publishes without them, and still publishes.
     *
     * Attaching assets is not allowed to fail a publish: a campaign without its
     * extras works, and rolling the whole thing back for them would be worse.
     */
    public function test_a_page_with_no_links_still_publishes(): void
    {
        $this->fakeGoogle();

        $campaign = $this->campaign();
        $created = [];

        app(GooglePublisher::class)->create($campaign, 'tester', $created);

        $this->assertNotEmpty($created['campaign_id'] ?? null, 'the campaign must still be created');

        $sent = collect(Http::recorded())
            ->filter(fn (array $pair): bool => str_contains((string) $pair[0]->url(), 'campaignAssets:mutate'));

        $this->assertCount(0, $sent, 'nothing to attach means no call at all');
    }

    /**
     * Google's tracking template is sent, and the UTM is not sent twice.
     *
     * The template defines the click URL and TrackedUrl appends the same kind
     * of parameters to the final URL. Sending both tags every click twice, so
     * the final URL goes clean whenever a template is configured.
     */
    public function test_a_tracking_template_replaces_the_appended_utm(): void
    {
        config(['google-ads.tracking_url_template' => '{lpurl}?utm_source=google&utm_medium=cpc&cid={campaignid}']);
        $this->fakeGoogle();

        $campaign = $this->campaign(['utm' => 'utm_source=google&utm_medium=cpc']);
        $created = [];
        app(GooglePublisher::class)->create($campaign, 'tester', $created);

        $sent = $this->sent('campaigns:mutate')['operations'][0]['create'] ?? [];

        $this->assertSame(
            '{lpurl}?utm_source=google&utm_medium=cpc&cid={campaignid}',
            $sent['trackingUrlTemplate'] ?? null,
        );

        $ad = $this->sent('adGroupAds:mutate')['operations'][0]['create'] ?? [];
        $finalUrl = data_get($ad, 'ad.finalUrls.0', '');

        $this->assertStringNotContainsString('utm_source', (string) $finalUrl,
            'the template already tags the click, so the final URL must go clean');
    }

    /** With no template configured, nothing changes: the UTM is appended as before. */
    public function test_without_a_template_the_utm_is_still_appended(): void
    {
        config(['google-ads.tracking_url_template' => '']);
        $this->fakeGoogle();

        $campaign = $this->campaign(['utm' => 'utm_source=google&utm_medium=cpc']);
        $created = [];
        app(GooglePublisher::class)->create($campaign, 'tester', $created);

        $sent = $this->sent('campaigns:mutate')['operations'][0]['create'] ?? [];
        $this->assertArrayNotHasKey('trackingUrlTemplate', $sent, 'Google rejects an empty template');

        $ad = $this->sent('adGroupAds:mutate')['operations'][0]['create'] ?? [];
        $this->assertStringContainsString('utm_source', (string) data_get($ad, 'ad.finalUrls.0', ''));
    }

    /** A template that drops the landing page would send every click to one URL. */
    public function test_a_template_without_lpurl_is_refused(): void
    {
        config(['google-ads.tracking_url_template' => 'https://tracker.example/click?cid={campaignid}']);
        $this->fakeGoogle();

        $campaign = $this->campaign();
        $created = [];

        try {
            app(GooglePublisher::class)->create($campaign, 'tester', $created);
            $this->fail('A template with no {lpurl} must not be published.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('{lpurl}', $exception->getMessage());
        }

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