<?php

namespace Tests\Feature;

use App\Campaigns\Publishing\GooglePublisher;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request as ClientRequest;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

/**
 * Restarting a Google campaign leaves deliberately paused children alone.
 *
 * activate() was one line: setLiveStatus(ids, 'ENABLED'), where ids carries the
 * campaign, its ad group and its ad. That is right the first time - both
 * children are created PAUSED, so enabling the campaign alone produces a
 * campaign that is live and serves nothing - and wrong every time after.
 *
 * pause() deliberately stops at the campaign, so the pair was not symmetric. A
 * buyer who turned off one ad, then paused and restarted the campaign, got the
 * ad they had switched off back, and nothing said so. They would be spending on
 * it.
 *
 * Meta guards this with nothingIsRunning(), and this is the same guard against
 * the same hazard: children are enabled only when none of them is already
 * enabled, which is what a campaign straight out of publishing looks like.
 */
class GoogleRestartDoesNotResurrectPausedChildrenTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

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

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

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['3460855874'],
            'platforms.guardrails.paused' => false,
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '3460855874',
        ]);
    }

    private function campaign(): Campaign
    {
        return Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Knowledgedom',
            'platform' => 'google',
            'status' => 'published',
            'ad_account_id' => '3460855874',
            'external_campaign_id' => '222',
            'external_ids' => ['campaign_id' => '222', 'ad_group_id' => '333', 'ad_id' => '444'],
        ]);
    }

    /**
     * @param  string  $adGroupStatus  what Google says the ad group is
     * @param  string  $adStatus  what Google says the ad is
     */
    private function fakeGoogle(string $adGroupStatus, string $adStatus, array $assetGroups = []): void
    {
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => function (ClientRequest $request) use ($adGroupStatus, $adStatus, $assetGroups) {
                $query = (string) ($request->data()['query'] ?? '');

                $rows = match (true) {
                    str_contains($query, 'FROM ad_group_criterion') => [],
                    str_contains($query, 'FROM ad_group_ad') => [[
                        'adGroupAd' => ['status' => $adStatus, 'ad' => ['id' => '444', 'name' => 'RSA']],
                        'adGroup' => ['id' => '333', 'name' => 'Brand'],
                    ]],
                    str_contains($query, 'FROM ad_group') => $adGroupStatus === 'NONE' ? [] : [[
                        'adGroup' => ['id' => '333', 'name' => 'Brand', 'status' => $adGroupStatus],
                        'campaign' => ['advertisingChannelType' => 'SEARCH'],
                    ]],
                    str_contains($query, 'FROM asset_group') => $assetGroups,
                    default => [],
                };

                return Http::response([['results' => $rows]]);
            },
            '*:mutate' => Http::response(['results' => [['resourceName' => 'customers/3460855874/campaigns/222']]]),
        ]);
    }

    /** @return list<string> the resource collections actually written to */
    private function mutated(): array
    {
        $written = [];

        foreach (Http::recorded() as [$request]) {
            if (! str_contains($request->url(), ':mutate')) {
                continue;
            }

            foreach (['campaigns', 'adGroups', 'adGroupAds'] as $collection) {
                if (str_contains($request->url(), '/'.$collection.':mutate')) {
                    $written[] = $collection;
                }
            }
        }

        sort($written);

        return $written;
    }

    // ------------------------------------------------------- the first start

    /**
     * Nothing running, so everything is started.
     *
     * The behaviour that was always right and must not be lost: a campaign
     * straight out of publishing has a paused ad group and a paused ad, and
     * enabling only the campaign would serve nothing.
     */
    public function test_a_campaign_with_nothing_running_starts_its_children_too(): void
    {
        $this->fakeGoogle(adGroupStatus: 'PAUSED', adStatus: 'PAUSED');

        app(GooglePublisher::class)->activate($this->campaign(), 'tester');

        $this->assertSame(['adGroupAds', 'adGroups', 'campaigns'], $this->mutated());
    }

    /**
     * And the ad is named the way Google keys it.
     *
     * Asserted on the resource name, not just on which collection was written:
     * this level used to post adGroupAds/<adId> to ads:mutate, and a test that
     * only counted collections would pass on adGroupAds/444 - a name Google
     * refuses. The live account returns
     * customers/3460855874/adGroupAds/191986261905~795772820090.
     */
    public function test_the_ad_is_enabled_under_its_compound_resource_name(): void
    {
        $this->fakeGoogle(adGroupStatus: 'PAUSED', adStatus: 'PAUSED');

        app(GooglePublisher::class)->activate($this->campaign(), 'tester');

        $this->assertContains('customers/3460855874/adGroupAds/333~444', $this->writtenNames());
    }

    /** @return list<string> the resource names actually written */
    private function writtenNames(): array
    {
        $names = [];

        foreach (Http::recorded() as [$request]) {
            if (str_contains($request->url(), ':mutate')) {
                $names[] = (string) data_get($request->data(), 'operations.0.update.resourceName');
            }
        }

        return $names;
    }

    // ------------------------------------------------------- the restart

    /** The defect: an ad the buyer had paused came back enabled. */
    public function test_a_paused_ad_is_not_restarted_when_the_ad_group_is_running(): void
    {
        $this->fakeGoogle(adGroupStatus: 'ENABLED', adStatus: 'PAUSED');

        app(GooglePublisher::class)->activate($this->campaign(), 'tester');

        $this->assertSame(['campaigns'], $this->mutated(), 'a child was re-enabled on a restart');
    }

    /** And the same the other way round. */
    public function test_a_paused_ad_group_is_not_restarted_when_an_ad_is_running(): void
    {
        $this->fakeGoogle(adGroupStatus: 'PAUSED', adStatus: 'ENABLED');

        app(GooglePublisher::class)->activate($this->campaign(), 'tester');

        $this->assertSame(['campaigns'], $this->mutated());
    }

    /** The campaign itself is always enabled, which is what was asked for. */
    public function test_the_campaign_is_enabled_either_way(): void
    {
        $this->fakeGoogle(adGroupStatus: 'ENABLED', adStatus: 'ENABLED');

        app(GooglePublisher::class)->activate($this->campaign(), 'tester');

        $this->assertContains('campaigns', $this->mutated());
    }

    /**
     * A running Performance Max asset group counts as running.
     *
     * PMax has no ad groups, so a check that looked only at those would call
     * every live PMax campaign idle and re-enable children under it.
     */
    public function test_a_running_asset_group_counts_as_running(): void
    {
        $this->fakeGoogle(adGroupStatus: 'NONE', adStatus: 'PAUSED', assetGroups: [
            ['assetGroup' => ['id' => '555', 'name' => 'Winter', 'status' => 'ENABLED']],
        ]);

        app(GooglePublisher::class)->activate($this->campaign(), 'tester');

        $this->assertSame(['campaigns'], $this->mutated());
    }

    /**
     * An unreadable platform fails towards starting everything.
     *
     * The same direction Meta's guard fails in, and for the same reason: with
     * no evidence anything is running, a campaign that will not serve is a
     * worse outcome than one that restarts a child somebody had paused.
     */
    public function test_an_unreadable_platform_starts_the_children(): void
    {
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => Http::response(['error' => ['message' => 'Backend error.']], 500),
            '*:mutate' => Http::response(['results' => [['resourceName' => 'customers/3460855874/campaigns/222']]]),
        ]);

        app(GooglePublisher::class)->activate($this->campaign(), 'tester');

        $this->assertSame(['adGroupAds', 'adGroups', 'campaigns'], $this->mutated());
    }

    /** Pausing still stops at the campaign, which is what makes the pair work. */
    public function test_pausing_still_touches_only_the_campaign(): void
    {
        $this->fakeGoogle(adGroupStatus: 'ENABLED', adStatus: 'ENABLED');

        app(GooglePublisher::class)->pause($this->campaign(), 'tester');

        $this->assertSame(['campaigns'], $this->mutated());
    }

    /**
     * Pause then restart leaves the campaign where it started.
     *
     * The round trip is the thing that was broken, so it is asserted as a round
     * trip rather than only as its two halves.
     */
    public function test_a_pause_and_restart_round_trip_changes_no_child(): void
    {
        $campaign = $this->campaign();

        // One ad deliberately off, the ad group still running.
        $this->fakeGoogle(adGroupStatus: 'ENABLED', adStatus: 'PAUSED');

        app(GooglePublisher::class)->pause($campaign, 'tester');
        app(GooglePublisher::class)->activate($campaign, 'tester');

        $this->assertSame(['campaigns', 'campaigns'], $this->mutated());
    }

    /**
     * Activating Performance Max switches on the thing that serves.
     *
     * PMax keeps its creative in an asset group and has no ad group or ad, and
     * the asset group is created PAUSED. setLiveStatus wrote adGroupAds,
     * adGroups and campaigns and nothing else, so activate() enabled the
     * campaign and left the asset group off. isLive() then read the campaign as
     * ENABLED and reported the campaign live - a campaign serving nothing,
     * which on a reporting screen is indistinguishable from one losing every
     * auction.
     */
    public function test_activating_performance_max_enables_its_asset_group(): void
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Knowledgedom PMax',
            'platform' => 'google',
            'status' => 'published',
            'ad_account_id' => '3460855874',
            'external_campaign_id' => '222',
            'external_ids' => ['campaign_id' => '222', 'asset_group_id' => '888'],
        ]);

        // NONE, because Performance Max has no ad groups at all. With one
        // present, readCampaignStructure does not read asset groups and this
        // would pass without ever proving anything.
        $this->fakeGoogle('NONE', 'PAUSED', assetGroups: [
            ['assetGroup' => ['id' => '888', 'name' => 'PMax assets', 'status' => 'PAUSED']],
        ]);

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

        $this->assertContains('customers/3460855874/assetGroups/888', $this->writtenNames(),
            'the asset group is the only thing that can serve, so activating must enable it');
        $this->assertContains('customers/3460855874/campaigns/222', $this->writtenNames());
    }

    /** An asset group somebody left running is not re-enabled behind them. */
    public function test_a_running_asset_group_stops_activate_touching_the_children(): void
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Knowledgedom PMax',
            'platform' => 'google',
            'status' => 'published',
            'ad_account_id' => '3460855874',
            'external_campaign_id' => '222',
            'external_ids' => ['campaign_id' => '222', 'asset_group_id' => '888'],
        ]);

        $this->fakeGoogle('NONE', 'PAUSED', assetGroups: [
            ['assetGroup' => ['id' => '888', 'name' => 'PMax assets', 'status' => 'ENABLED']],
        ]);

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

        $this->assertSame(['customers/3460855874/campaigns/222'], $this->writtenNames(),
            'something is already running, so only the campaign is touched');
    }
}
