<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Tools\Campaign\SetEntityStatus;
use App\Agent\Workspace;
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 Tests\TestCase;

/**
 * set_entity_status pauses and restarts Google ad groups and ads.
 *
 * It was Meta-only - "Pausing a single ad set or ad is only available on Meta" -
 * so a Google buyer could stop the whole campaign and nothing smaller.
 *
 * The level underneath had never worked. setLiveStatus posted an ad's status to
 * ads:mutate while naming an adGroupAds resource, and built that name as
 * adGroupAds/<adId>. Google keys an AdGroupAd by both ids, confirmed against
 * the live account, which returns adGroupAds/191986261905~795772820090; and
 * status is a field of AdGroupAd rather than Ad, so ads:mutate could not have
 * set it under any name. Mutations throw and that level ran first, so every
 * call carrying an ad id - which activate() makes on every Google campaign -
 * threw before the ad group or campaign was touched.
 *
 * Both halves are tested here: that the right resource is written, and that
 * writing one ad does not write its ad group. The ad's name needs the ad group
 * id, and handing that to setLiveStatus would have paused the ad group too.
 */
class AGoogleAdGroupOrAdCanBePausedTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

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

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

        app(Workspace::class)->bindTo('conv-google-status');
        app(Workspace::class)->ownedBy($this->user);

        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
    {
        $campaign = 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'],
        ]);

        app(Workspace::class)->produced($campaign);
        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    /** Two ad groups, one ad in each, so an ad can be told from its parent. */
    private function fakeGoogle(array $assetGroups = [], ?array $adGroups = null): void
    {
        $adGroups ??= [
            ['adGroup' => ['id' => '333', 'name' => 'Brand', 'status' => 'ENABLED'],
                'campaign' => ['advertisingChannelType' => 'SEARCH']],
            ['adGroup' => ['id' => '334', 'name' => 'Generic', 'status' => 'ENABLED'],
                'campaign' => ['advertisingChannelType' => 'SEARCH']],
        ];

        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => function (ClientRequest $request) use ($assetGroups, $adGroups) {
                $query = (string) ($request->data()['query'] ?? '');

                $rows = match (true) {
                    str_contains($query, 'FROM ad_group_criterion') => [],
                    str_contains($query, 'FROM ad_group_ad') => [
                        ['adGroupAd' => ['status' => 'ENABLED', 'ad' => ['id' => '444', 'name' => 'RSA one']],
                            'adGroup' => ['id' => '333', 'name' => 'Brand']],
                        ['adGroupAd' => ['status' => 'ENABLED', 'ad' => ['id' => '555', 'name' => 'RSA two']],
                            'adGroup' => ['id' => '334', 'name' => 'Generic']],
                    ],
                    str_contains($query, 'FROM ad_group') => $adGroups,
                    str_contains($query, 'FROM asset_group') => $assetGroups,
                    default => [],
                };

                return Http::response([['results' => $rows]]);
            },
            '*:mutate' => Http::response(['results' => [['resourceName' => 'x']]]),
        ]);
    }

    private function set(array $arguments): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t): bool => $t->name() === 'campaign__set_entity_status');

        $this->assertNotNull($tool, 'campaign__set_entity_status is not registered');

        return json_decode((string) $tool->handle(new Request($arguments)), true);
    }

    /** @return list<string> the resource names actually written */
    private function written(): 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;
    }

    // ------------------------------------------------------------- ad groups

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

        $result = $this->set(['entity_type' => 'ad_group', 'ids' => ['333'], 'status' => 'PAUSED']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['customers/3460855874/adGroups/333'], $this->written());
    }

    /** Meta's word for the level still works, since the model may reach for it. */
    public function test_ad_set_is_accepted_as_a_name_for_an_ad_group(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->set(['entity_type' => 'ad_set', 'ids' => ['333'], 'status' => 'PAUSED']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['customers/3460855874/adGroups/333'], $this->written());
    }

    /** And Google's word for live, which is what a model reading a structure sees. */
    public function test_enabled_is_accepted_as_a_name_for_active(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->set(['entity_type' => 'ad_group', 'ids' => ['333'], 'status' => 'ENABLED']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('ENABLED', $result['status']);
    }

    // ------------------------------------------------------------------- ads

    /**
     * An ad is named by its ad group and itself, as Google keys it.
     *
     * The shape verified against the live account. adGroupAds/444 would be
     * refused, and that is what this sent.
     */
    public function test_an_ad_is_written_with_the_compound_resource_name(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->set(['entity_type' => 'ad', 'ids' => ['444'], 'status' => 'PAUSED']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['customers/3460855874/adGroupAds/333~444'], $this->written());
    }

    /**
     * The ad group of the ad, not of the campaign.
     *
     * external_ids holds one ad group and one ad, so a campaign with two of
     * either cannot be answered from it. Ad 555 belongs to ad group 334, while
     * external_ids says 333.
     */
    public function test_the_ads_own_ad_group_is_used_not_the_campaigns(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $this->set(['entity_type' => 'ad', 'ids' => ['555'], 'status' => 'PAUSED']);

        $this->assertSame(['customers/3460855874/adGroupAds/334~555'], $this->written());
    }

    /** Pausing one ad does not pause the ad group it sits in. */
    public function test_pausing_an_ad_does_not_touch_its_ad_group(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $this->set(['entity_type' => 'ad', 'ids' => ['444'], 'status' => 'PAUSED']);

        $this->assertSame(
            ['customers/3460855874/adGroupAds/333~444'],
            $this->written(),
            'pausing one ad also wrote its ad group, stopping the whole group',
        );
    }

    /** Several at once, each written separately. */
    public function test_more_than_one_ad_can_be_paused_at_once(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->set(['entity_type' => 'ad', 'ids' => ['444', '555'], 'status' => 'PAUSED']);

        $this->assertSame(['444', '555'], $result['changed']);
        $this->assertSame([
            'customers/3460855874/adGroupAds/333~444',
            'customers/3460855874/adGroupAds/334~555',
        ], $this->written());
    }

    // ------------------------------------------------------------- refusals

    /** An id not in the campaign is refused before anything is written. */
    public function test_an_unknown_id_is_refused_without_writing(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->set(['entity_type' => 'ad', 'ids' => ['444', '999'], 'status' => 'PAUSED']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('999', $result['error']);
        $this->assertSame([], $this->written(), 'a valid id in the list was written before the bad one was refused');
    }

    /** An ad group id passed as an ad is not in the ad list, so it is refused. */
    public function test_an_ad_group_id_given_as_an_ad_is_refused(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->set(['entity_type' => 'ad', 'ids' => ['333'], 'status' => 'PAUSED']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Ad(s) 333 not in this campaign', $result['error']);
        $this->assertSame([], $this->written());
    }

    /**
     * Performance Max has no ad group or ad, and now says where to look.
     *
     * This asserted the refusal pointed at pause_campaign, because setLiveStatus
     * had an ad, ad-group and campaign level and nothing for an asset group, so
     * offering to pause one would have been a promise nothing could keep. The
     * asset group is addressable now, so the refusal names it instead of
     * sending the buyer up to the whole campaign.
     */
    public function test_performance_max_refuses_ad_group_and_points_at_the_asset_group(): void
    {
        $this->campaign();
        $this->fakeGoogle(
            assetGroups: [['assetGroup' => ['id' => '555', 'name' => 'Winter', 'status' => 'ENABLED']]],
            adGroups: [],
        );

        $result = $this->set(['entity_type' => 'ad_group', 'ids' => ['555'], 'status' => 'PAUSED']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Performance Max', $result['error']);
        $this->assertStringContainsString('asset_group', $result['error']);
        $this->assertSame([], $this->written());
    }

    /** An unreadable platform changes nothing and says it changed nothing. */
    public function test_an_unreadable_platform_writes_nothing(): void
    {
        $this->campaign();

        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' => 'x']]]),
        ]);

        $result = $this->set(['entity_type' => 'ad', 'ids' => ['444'], 'status' => 'PAUSED']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('nothing was changed', $result['note']);
        $this->assertSame([], $this->written());
    }

    /** An unpublished campaign has nothing underneath it to change. */
    public function test_an_unpublished_campaign_is_refused(): void
    {
        $campaign = $this->campaign();
        $campaign->forceFill(['status' => 'draft', 'external_campaign_id' => null])->save();

        Http::fake();

        $result = $this->set(['entity_type' => 'ad', 'ids' => ['444'], 'status' => 'PAUSED']);

        $this->assertFalse($result['ok']);
        Http::assertNothingSent();
    }

    /**
     * ENABLED is ACTIVE, to the approval gate as well as to Google.
     *
     * needsApproval() compared the raw argument against ACTIVE while handle()
     * translated ENABLED into it, so the one word this tool teaches the model
     * for Google walked past the gate and restarted a live ad group with no
     * card shown. The gate is the only thing between a model call and live
     * spend, so both words have to mean the same thing to it.
     */
    public function test_enabled_asks_for_approval_exactly_as_active_does(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $tool = app(SetEntityStatus::class);
        $gate = new \ReflectionMethod($tool, 'needsApproval');
        $asked = fn (string $word): bool => $gate->invoke($tool, new Request([
            'entity_type' => 'ad_group', 'ids' => ['333'], 'status' => $word,
        ])) !== false;

        $this->assertTrue($asked('ACTIVE'), 'ACTIVE must ask');
        $this->assertTrue($asked('ENABLED'), 'ENABLED restarts spend just as ACTIVE does, so it must ask');
        $this->assertTrue($asked('enabled'), 'the word is not case sensitive to Google and must not be here');
        $this->assertFalse($asked('PAUSED'), 'pausing spends nothing and is never gated');
    }

    /**
     * A platform this cannot serve is refused by name.
     *
     * This asserted LinkedIn was refused, which stopped being true: LinkedIn
     * grew its own branch here while the Google work sat unmerged, so the
     * assertion was testing the gap between the two rather than anything the
     * product promises. What it was really protecting is that an unservable
     * platform is named rather than silently answered, so it now uses one.
     */
    public function test_a_platform_this_cannot_serve_is_refused_by_name(): void
    {
        $campaign = $this->campaign();
        $campaign->forceFill(['platform' => 'tiktok'])->save();

        Http::fake();

        $result = $this->set(['entity_type' => 'ad', 'ids' => ['444'], 'status' => 'PAUSED']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Tiktok', $result['error']);
        Http::assertNothingSent();
    }

    // --------------------------------------------- performance max asset groups

    /**
     * A Performance Max asset group can be switched on.
     *
     * It is created PAUSED, and nothing in the product could reach it:
     * setLiveStatus wrote only adGroupAds, adGroups and campaigns, and this
     * tool refused Performance Max outright. activate() therefore enabled the
     * campaign and left the only thing that can serve switched off, while
     * isLive() read the campaign as ENABLED and called it live - a campaign
     * serving nothing, indistinguishable from one losing every auction.
     */
    public function test_an_asset_group_can_be_enabled(): void
    {
        $this->campaign();
        $this->fakeGoogle(
            assetGroups: [['assetGroup' => ['id' => '888', 'name' => 'PMax assets', 'status' => 'PAUSED']]],
            adGroups: [],
        );

        $result = $this->set(['entity_type' => 'asset_group', 'ids' => ['888'], 'status' => 'ACTIVE']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('asset_group', $result['entity_type']);
        $this->assertSame('ENABLED', $result['status']);
        $this->assertSame(['customers/3460855874/assetGroups/888'], $this->written());
    }

    /** And paused again, without touching the campaign above it. */
    public function test_an_asset_group_can_be_paused_on_its_own(): void
    {
        $this->campaign();
        $this->fakeGoogle(
            assetGroups: [['assetGroup' => ['id' => '888', 'name' => 'PMax assets', 'status' => 'ENABLED']]],
            adGroups: [],
        );

        $result = $this->set(['entity_type' => 'asset_group', 'ids' => ['888'], 'status' => 'PAUSED']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['customers/3460855874/assetGroups/888'], $this->written());
    }

    /** An id that is not in this campaign is refused, as at every other level. */
    public function test_an_asset_group_from_another_campaign_is_refused(): void
    {
        $this->campaign();
        $this->fakeGoogle(
            assetGroups: [['assetGroup' => ['id' => '888', 'name' => 'PMax assets', 'status' => 'PAUSED']]],
            adGroups: [],
        );

        $result = $this->set(['entity_type' => 'asset_group', 'ids' => ['999'], 'status' => 'ACTIVE']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Asset group(s) 999', $result['error']);
        $this->assertSame([], $this->written());
    }
}
