<?php

namespace Tests\Feature;

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

/**
 * The keywords on a running Google ad group can be changed.
 *
 * Nothing could do this. SearchKeywordSelections::save refuses a published
 * campaign outright - "available for draft Google Search campaigns only" - and
 * every other write to adGroupCriteria lived inside the publish path. So once a
 * Search campaign went live nobody could add a term, drop one, change a match
 * type or add a negative, which is the most ordinary thing a buyer does to a
 * running Search campaign.
 *
 * Applied as a difference rather than a replacement. A keyword criterion
 * carries its own history and quality score, so removing and recreating one
 * that did not change would throw that away and start it again at nothing. That
 * is the property most of this file is about.
 *
 * Identity is text, match type and negative together, because Google cannot
 * update any of the three in place: a change to any of them is a removal and an
 * addition, not an edit.
 */
class AGoogleAdGroupsKeywordsCanBeChangedLiveTest 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-keywords');
        app(Workspace::class)->ownedBy($this->user);

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['3460855874'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            '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',
            'campaign_type' => 'search',
            '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 terms live on the ad group: one included, one excluded. */
    private function fakeGoogle(?array $live = null): void
    {
        $live ??= [
            ['text' => 'car insurance', 'matchType' => 'PHRASE', 'negative' => false, 'id' => '11'],
            ['text' => 'free', 'matchType' => 'BROAD', 'negative' => true, 'id' => '22'],
        ];

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

                if (str_contains($query, 'FROM ad_group_criterion')) {
                    return Http::response([['results' => array_map(
                        static fn (array $k): array => ['adGroup' => ['id' => '333'], 'adGroupCriterion' => [
                            'resourceName' => 'customers/3460855874/adGroupCriteria/333~'.$k['id'],
                            'keyword' => ['text' => $k['text'], 'matchType' => $k['matchType']],
                            'negative' => $k['negative'],
                        ]],
                        $live,
                    )]]);
                }

                $rows = match (true) {
                    str_contains($query, 'FROM ad_group_ad') => [[
                        'adGroupAd' => ['status' => 'ENABLED', 'ad' => ['id' => '444', 'name' => 'RSA']],
                        'adGroup' => ['id' => '333', 'name' => 'Brand'],
                    ]],
                    str_contains($query, 'FROM ad_group') => [[
                        'adGroup' => ['id' => '333', 'name' => 'Brand', 'status' => 'ENABLED'],
                        'campaign' => ['advertisingChannelType' => 'SEARCH'],
                    ]],
                    default => [],
                };

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

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

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

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

    /** @return list<array<string,mixed>> every keyword criterion created */
    private function created(): array
    {
        $out = [];

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

            foreach ((array) ($request->data()['operations'] ?? []) as $operation) {
                if (($create = $operation['create'] ?? null) !== null) {
                    $out[] = (array) $create;
                }
            }
        }

        return $out;
    }

    /** @return list<string> every criterion resource removed */
    private function removed(): array
    {
        $out = [];

        foreach (Http::recorded() as [$request]) {
            foreach ((array) ($request->data()['operations'] ?? []) as $operation) {
                if (($remove = $operation['remove'] ?? null) !== null) {
                    $out[] = (string) $remove;
                }
            }
        }

        return $out;
    }

    private function keywords(array $terms): array
    {
        return ['entity_type' => 'ad_group', 'id' => '333', 'keywords' => $terms];
    }

    // ---------------------------------------------------- the thing that was missing

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

        $result = $this->edit($this->keywords([
            ['text' => 'car insurance', 'match_type' => 'PHRASE', 'negative' => false],
            ['text' => 'free', 'match_type' => 'BROAD', 'negative' => true],
            ['text' => 'cheap car cover', 'match_type' => 'EXACT', 'negative' => false],
        ]));

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['added' => 1, 'removed' => 0, 'unchanged' => 2], $result['keywords']);
        $this->assertSame([['text' => 'cheap car cover', 'matchType' => 'EXACT']], array_column($this->created(), 'keyword'));
    }

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

        $result = $this->edit($this->keywords([
            ['text' => 'car insurance', 'match_type' => 'PHRASE', 'negative' => false],
        ]));

        $this->assertSame(['added' => 0, 'removed' => 1, 'unchanged' => 1], $result['keywords']);
        $this->assertSame(['customers/3460855874/adGroupCriteria/333~22'], $this->removed());
    }

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

        $this->edit($this->keywords([
            ['text' => 'car insurance', 'match_type' => 'PHRASE', 'negative' => false],
            ['text' => 'free', 'match_type' => 'BROAD', 'negative' => true],
            ['text' => 'jobs', 'match_type' => 'BROAD', 'negative' => true],
        ]));

        $this->assertSame(
            [['text' => 'jobs', 'matchType' => 'BROAD']],
            array_column($this->created(), 'keyword'),
        );
        $this->assertSame([true], array_column($this->created(), 'negative'));
    }

    // ------------------------------------------------------- history is preserved

    /**
     * The property this is really about.
     *
     * A keyword that did not change is not touched, so it keeps the history and
     * quality score it has built up. Replacing the whole set would reset every
     * term to nothing, which is invisible in the chat and expensive in the
     * auction.
     */
    public function test_unchanged_keywords_are_left_completely_alone(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->edit($this->keywords([
            ['text' => 'car insurance', 'match_type' => 'PHRASE', 'negative' => false],
            ['text' => 'free', 'match_type' => 'BROAD', 'negative' => true],
        ]));

        $this->assertSame(['added' => 0, 'removed' => 0, 'unchanged' => 2], $result['keywords']);
        $this->assertSame([], $this->created(), 'an unchanged keyword was recreated, losing its history');
        $this->assertSame([], $this->removed(), 'an unchanged keyword was removed');
    }

    /** Matching ignores case and stray spacing, so neither rewrites a term. */
    public function test_the_same_term_in_different_case_is_not_rewritten(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->edit($this->keywords([
            ['text' => '  Car   Insurance ', 'match_type' => 'PHRASE', 'negative' => false],
            ['text' => 'free', 'match_type' => 'BROAD', 'negative' => true],
        ]));

        $this->assertSame(['added' => 0, 'removed' => 0, 'unchanged' => 2], $result['keywords']);
        $this->assertSame([], $this->created());
    }

    /**
     * A match type change is a removal and an addition.
     *
     * Google cannot update the match type of an existing criterion, so the old
     * one has to go and a new one take its place.
     */
    public function test_changing_a_match_type_replaces_the_criterion(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->edit($this->keywords([
            ['text' => 'car insurance', 'match_type' => 'EXACT', 'negative' => false],
            ['text' => 'free', 'match_type' => 'BROAD', 'negative' => true],
        ]));

        $this->assertSame(['added' => 1, 'removed' => 1, 'unchanged' => 1], $result['keywords']);
        $this->assertSame(['customers/3460855874/adGroupCriteria/333~11'], $this->removed());
        $this->assertSame([['text' => 'car insurance', 'matchType' => 'EXACT']], array_column($this->created(), 'keyword'));
    }

    /** Removals go out before additions. */
    public function test_removals_are_sent_before_additions(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $this->edit($this->keywords([
            ['text' => 'car insurance', 'match_type' => 'EXACT', 'negative' => false],
            ['text' => 'free', 'match_type' => 'BROAD', 'negative' => true],
        ]));

        $order = [];

        foreach (Http::recorded() as [$request]) {
            foreach ((array) ($request->data()['operations'] ?? []) as $operation) {
                if (isset($operation['remove'])) {
                    $order[] = 'remove';
                } elseif (isset($operation['create'])) {
                    $order[] = 'create';
                }
            }
        }

        $this->assertSame(['remove', 'create'], $order);
    }

    // ------------------------------------------------------------- the guards

    /**
     * An edit cannot leave an ad group with nothing to match on.
     *
     * The draft path already refuses this; the live path reuses the same rules
     * rather than having its own, because here there is no step to go back to.
     */
    public function test_removing_every_included_keyword_is_refused(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->edit($this->keywords([
            ['text' => 'free', 'match_type' => 'BROAD', 'negative' => true],
        ]));

        $this->assertFalse($result['ok']);
        // The floor, which is all that is left: the twenty-keyword ceiling was
        // this product's own and has been removed. See
        // NoProductCapOnSearchKeywordsTest.
        $this->assertStringContainsString('at least one included', $result['error']);
        $this->assertSame([], $this->created());
        $this->assertSame([], $this->removed());
    }

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

        $result = $this->edit($this->keywords([
            ['text' => 'car insurance', 'match_type' => 'SOMETHING', 'negative' => false],
        ]));

        $this->assertFalse($result['ok']);
        $this->assertSame([], $this->created());
        $this->assertSame([], $this->removed());
    }

    /** The same term twice, once included and once excluded, is refused. */
    public function test_a_term_cannot_be_both_included_and_excluded(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->edit($this->keywords([
            ['text' => 'car insurance', 'match_type' => 'PHRASE', 'negative' => false],
            ['text' => 'car insurance', 'match_type' => 'EXACT', 'negative' => true],
        ]));

        $this->assertFalse($result['ok']);
        $this->assertSame([], $this->created());
    }

    /** An ad group outside the campaign is refused before anything is read. */
    public function test_an_ad_group_outside_the_campaign_is_refused(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->edit([
            'entity_type' => 'ad_group',
            'id' => '999',
            'keywords' => [['text' => 'car insurance', 'match_type' => 'PHRASE', 'negative' => false]],
        ]);

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

    /**
     * Keywords are applied before the rename.
     *
     * A refusal after the rename had gone through would leave half an edit and
     * a message saying nothing happened.
     */
    public function test_a_refused_keyword_set_does_not_rename_the_ad_group(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->edit([
            'entity_type' => 'ad_group',
            'id' => '333',
            'name' => 'Renamed',
            'keywords' => [['text' => 'free', 'match_type' => 'BROAD', 'negative' => true]],
        ]);

        $this->assertFalse($result['ok']);

        $renamed = collect(Http::recorded())
            ->contains(fn (array $pair): bool => str_contains($pair[0]->url(), '/adGroups:mutate'));

        $this->assertFalse($renamed, 'the ad group was renamed even though its keywords were refused');
    }

    /** A name and a keyword set can still be changed together. */
    public function test_a_name_and_keywords_can_change_in_one_call(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->edit([
            'entity_type' => 'ad_group',
            'id' => '333',
            'name' => 'Brand exact',
            'keywords' => [
                ['text' => 'car insurance', 'match_type' => 'PHRASE', 'negative' => false],
                ['text' => 'free', 'match_type' => 'BROAD', 'negative' => true],
                ['text' => 'car cover', 'match_type' => 'EXACT', 'negative' => false],
            ],
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['name', 'keywords'], $result['changed']);
        $this->assertSame(1, $result['keywords']['added']);
        $this->assertTrue(collect(Http::recorded())
            ->contains(fn (array $pair): bool => str_contains($pair[0]->url(), '/adGroups:mutate')));
    }

    // -------------------------------------------------------------- reading them

    /** The current set is readable, which is what makes a complete set answerable. */
    public function test_the_current_keywords_are_listed_with_the_ad_group(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t): bool => $t->name() === 'campaign__list_campaign_structure');

        $result = json_decode((string) $tool->handle(new Request([])), true);

        $this->assertSame([
            ['text' => 'car insurance', 'match_type' => 'PHRASE', 'negative' => false],
            ['text' => 'free', 'match_type' => 'BROAD', 'negative' => true],
        ], $result['ad_groups'][0]['keywords']);
    }

    /**
     * A bid refused under Smart Bidding does not report the keywords as unchanged.
     *
     * Keywords are replaced first, then the ad group fields are sent. One catch
     * covered both and said "The ad group is unchanged", which on a Maximize
     * Conversions campaign is untrue in the worst direction: Google refuses
     * cpc_bid with OPERATION_NOT_PERMITTED_FOR_CONTEXT, so the keywords had
     * already been rewritten - and the quality-score history of the ones
     * removed is gone - while the buyer was told nothing happened and would
     * reasonably send the same edit again.
     */
    public function test_a_refused_bid_still_reports_the_keywords_that_were_changed(): void
    {
        $this->campaign();
        Http::fake(['*adGroups:mutate' => Http::response([
            'error' => ['message' => 'OPERATION_NOT_PERMITTED_FOR_CONTEXT'],
        ], 400)]);
        $this->fakeGoogle();

        $result = $this->edit([
            'entity_type' => 'ad_group',
            'id' => '333',
            'keywords' => [
                ['text' => 'van insurance', 'match_type' => 'phrase'],
                ['text' => 'lorry insurance', 'match_type' => 'exact'],
            ],
            'cpc_bid' => 1.5,
        ]);

        $this->assertFalse($result['ok']);
        $this->assertArrayHasKey('keywords', $result, 'the keywords went through and must be reported');
        $this->assertStringNotContainsString('ad group is unchanged', (string) $result['note']);
        $this->assertStringContainsString('keywords were changed', (string) $result['note']);
        $this->assertStringContainsString('do not send them again', (string) $result['note']);
    }

    /** A keyword failure before anything was written still reports nothing changed. */
    public function test_a_keyword_failure_reports_the_ad_group_as_unchanged(): void
    {
        $this->campaign();
        Http::fake(['*adGroupCriteria:mutate' => Http::response([
            'error' => ['message' => 'refused'],
        ], 400)]);
        $this->fakeGoogle();

        $result = $this->edit([
            'entity_type' => 'ad_group',
            'id' => '333',
            'keywords' => [['text' => 'van insurance', 'match_type' => 'phrase']],
            'cpc_bid' => 1.5,
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('ad group is unchanged', (string) $result['note']);
    }

    /**
     * The cooldown and the daily cap apply to a Google ad group edit.
     *
     * The class docblock says addressing objects individually must not be a way
     * around them, and the Meta and LinkedIn paths both call
     * assertChangeAllowed. This path called neither it nor CampaignChange, so
     * the cap could not even count these edits against later ones.
     */
    public function test_an_ad_group_edit_is_counted_and_rate_limited(): void
    {
        config(['platforms.guardrails.change_cooldown_seconds' => 3600]);

        $campaign = $this->campaign();
        $this->fakeGoogle();

        $first = $this->edit(['entity_type' => 'ad_group', 'id' => '333', 'name' => 'Brand renamed']);
        $this->assertTrue($first['ok'], $first['error'] ?? '');

        $this->assertSame(1, CampaignChange::where('campaign_id', $campaign->id)->count(),
            'the edit must leave an audit row, as Meta and LinkedIn do');
        $this->assertSame('applied', CampaignChange::where('campaign_id', $campaign->id)->first()->state);

        $second = $this->edit(['entity_type' => 'ad_group', 'id' => '333', 'name' => 'Brand again']);

        $this->assertFalse($second['ok'], 'the cooldown must refuse the second edit');
    }
}
