<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Publisher;
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 Laravel\Ai\Tools\Request;
use RuntimeException;
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;

    private string $googleStatus = 'PAUSED';

    private int $budgetMicros = 25000000;

    private bool $confirmWrites = true;

    private bool $confirmChildren = true;

    private string $adGroupStatus = 'PAUSED';

    private string $adStatus = 'PAUSED';

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

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

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['3460855874'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.max_daily_budget' => 1000,
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '3460855874',
        ]);
        $this->actingAs($this->user);
        app(Workspace::class)->bindTo('google-status-chat');
        app(Workspace::class)->ownedBy($this->user);
    }

    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
    {
        $this->adGroupStatus = $adGroupStatus;
        $this->adStatus = $adStatus;
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => function (ClientRequest $request) use ($assetGroups) {
                $query = (string) ($request->data()['query'] ?? '');

                $rows = match (true) {
                    str_contains($query, 'FROM campaign') => [[
                        'campaign' => ['id' => '222', 'name' => 'Google live name', 'status' => $this->googleStatus],
                        'campaignBudget' => ['amountMicros' => (string) $this->budgetMicros],
                        'customer' => ['currencyCode' => 'USD'],
                    ]],
                    str_contains($query, 'FROM ad_group_criterion') => [],
                    str_contains($query, 'FROM ad_group_ad') => [[
                        'adGroupAd' => ['status' => $this->adStatus, 'ad' => ['id' => '444', 'name' => 'RSA']],
                        'adGroup' => ['id' => '333', 'name' => 'Brand'],
                    ]],
                    str_contains($query, 'FROM ad_group') => $this->adGroupStatus === 'NONE' ? [] : [[
                        'adGroup' => ['id' => '333', 'name' => 'Brand', 'status' => $this->adGroupStatus],
                        'campaign' => ['advertisingChannelType' => 'SEARCH'],
                    ]],
                    str_contains($query, 'FROM asset_group') => $assetGroups,
                    default => [],
                };

                return Http::response([['results' => $rows]]);
            },
            '*:mutate' => function (ClientRequest $request) {
                if ($this->confirmWrites && str_contains($request->url(), '/campaigns:mutate')) {
                    $this->googleStatus = $request['operations'][0]['update']['status'];
                }
                if ($this->confirmWrites && $this->confirmChildren && str_contains($request->url(), '/adGroups:mutate')) {
                    $this->adGroupStatus = $request['operations'][0]['update']['status'];
                }
                if ($this->confirmWrites && $this->confirmChildren && str_contains($request->url(), '/adGroupAds:mutate')) {
                    $this->adStatus = $request['operations'][0]['update']['status'];
                }

                return 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 must not cause paused children to be restarted. */
    public function test_an_unreadable_platform_does_not_start_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']]]),
        ]);

        try {
            app(GooglePublisher::class)->activate($this->campaign(), 'tester');
            $this->fail('Activation must not guess child statuses.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('child statuses could not be read', $exception->getMessage());
        }
        $this->assertSame([], $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');
    }

    public function test_chat_can_enable_and_pause_an_incomplete_workspace_record_using_google_state(): void
    {
        $this->fakeGoogle('ENABLED', 'PAUSED');
        $campaign = $this->campaign();
        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);
        $tools = collect(app(ToolRegistry::class)->resolve());
        $requestTool = $tools->first(fn ($tool) => $tool->name() === 'campaign__request_activation');
        $activate = $tools->first(fn ($tool) => $tool->name() === 'campaign__activate_campaign');
        $pause = $tools->first(fn ($tool) => $tool->name() === 'campaign__pause_campaign');

        $review = json_decode((string) $requestTool->handle(new Request), true);
        $this->assertTrue($review['ok'], $review['error'] ?? '');
        $this->assertSame('25.000000', $review['summary']['budget']);
        $this->assertSame('USD', $review['summary']['currency']);
        $request = new Request([], 'google-activate');
        $this->assertNotNull($activate->shouldRequestApproval($request));
        $result = json_decode((string) $activate->handle($request), true);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('ENABLED', $this->googleStatus);

        $result = json_decode((string) $pause->handle(new Request), true);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('PAUSED', $this->googleStatus);
        $this->assertSame(['campaigns', 'campaigns'], $this->mutated());
    }

    public function test_google_budget_change_after_approval_blocks_activation(): void
    {
        $this->fakeGoogle('ENABLED', 'PAUSED');
        $campaign = $this->campaign();
        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);
        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($tool) => $tool->name() === 'campaign__activate_campaign');
        $request = new Request([], 'google-stale-budget');
        $this->assertNotNull($tool->shouldRequestApproval($request));
        $this->budgetMicros = 50000000;

        $result = json_decode((string) $tool->handle($request), true);
        $this->assertFalse($result['ok']);
        $this->assertSame([], $this->mutated());
    }

    public function test_chat_first_activation_confirms_the_recorded_children(): void
    {
        $this->fakeGoogle('PAUSED', 'PAUSED');
        $campaign = $this->campaign();
        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);
        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($tool) => $tool->name() === 'campaign__activate_campaign');
        $request = new Request([], 'google-first-start');
        $this->assertNotNull($tool->shouldRequestApproval($request));

        $result = json_decode((string) $tool->handle($request), true);
        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('ENABLED', $this->adGroupStatus);
        $this->assertSame('ENABLED', $this->adStatus);
        $this->assertSame(['adGroupAds', 'adGroups', 'campaigns'], $this->mutated());
    }

    public function test_google_pause_is_not_reported_as_success_without_confirmed_readback(): void
    {
        $this->fakeGoogle('ENABLED', 'ENABLED');
        $this->googleStatus = 'ENABLED';
        $this->confirmWrites = false;
        $campaign = $this->campaign();
        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);
        $pause = collect(app(ToolRegistry::class)->resolve())->first(fn ($tool) => $tool->name() === 'campaign__pause_campaign');

        $result = json_decode((string) $pause->handle(new Request), true);
        $this->assertFalse($result['ok']);
        $this->assertNull($result['running']);
        $this->assertStringContainsString('may have occurred', $result['error']);
    }

    public function test_child_status_change_after_approval_blocks_activation(): void
    {
        $this->fakeGoogle('ENABLED', 'PAUSED');
        $campaign = $this->campaign();
        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);
        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($tool) => $tool->name() === 'campaign__activate_campaign');
        $request = new Request([], 'google-stale-child');
        $this->assertNotNull($tool->shouldRequestApproval($request));
        $this->adGroupStatus = 'PAUSED';

        $result = json_decode((string) $tool->handle($request), true);
        $this->assertFalse($result['ok']);
        $this->assertSame([], $this->mutated());
    }

    public function test_google_activation_is_not_reported_as_success_without_confirmed_readback(): void
    {
        $this->fakeGoogle('ENABLED', 'PAUSED');
        $this->confirmWrites = false;
        $campaign = $this->campaign();
        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);
        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($tool) => $tool->name() === 'campaign__activate_campaign');
        $request = new Request([], 'google-unconfirmed');
        $this->assertNotNull($tool->shouldRequestApproval($request));

        $result = json_decode((string) $tool->handle($request), true);
        $this->assertFalse($result['ok']);
        $this->assertNull($result['running']);
        $this->assertStringContainsString('may have occurred', $result['error']);
        $this->assertNull($campaign->fresh()->activated_at);
    }

    public function test_first_activation_requires_child_status_readback(): void
    {
        $this->fakeGoogle('PAUSED', 'PAUSED');
        $this->confirmChildren = false;
        $campaign = $this->campaign();
        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);
        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($tool) => $tool->name() === 'campaign__activate_campaign');
        $request = new Request([], 'google-unconfirmed-child');
        $this->assertNotNull($tool->shouldRequestApproval($request));

        $result = json_decode((string) $tool->handle($request), true);
        $this->assertFalse($result['ok']);
        $this->assertNull($result['running']);
        $this->assertSame('ENABLED', $this->googleStatus);
        $this->assertStringContainsString('did not confirm an enabled child', $result['error']);
    }

    public function test_google_live_budget_above_ceiling_blocks_activation(): void
    {
        $this->fakeGoogle('ENABLED', 'PAUSED');
        $this->budgetMicros = 1000000001;
        $problems = app(Publisher::class)->activationProblems($this->campaign());
        $this->assertStringContainsString('exceeds', implode(' ', $problems));
        $this->assertSame([], $this->mutated());
    }
}
