<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
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;

/**
 * An ad group or an ad that is already on Google can be copied.
 *
 * Nothing smaller than a campaign could be copied on any platform.
 * duplicate_campaign copies a whole campaign into a new local draft and sends
 * nothing to a platform, which is right for starting again from something that
 * worked, and is not what a buyer means by "another one like that ad group" -
 * they want a second ad group beside the first, on the campaign already
 * running, keeping the keywords they settled on.
 *
 * Google has no copy operation, so this is a read of the source followed by
 * creates. Three things are easy to get wrong and are pinned here: everything
 * lands PAUSED, negatives stay negative, and the source bid is only carried
 * where Google will accept it.
 */
class AGoogleAdGroupOrAdCanBeCopiedTest 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-copy');
        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(string $platform = 'google', string $status = 'published'): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Knowledgedom',
            'platform' => $platform,
            'status' => $status,
            'ad_account_id' => '3460855874',
            'external_campaign_id' => $status === 'published' ? '222' : null,
            'external_ids' => ['campaign_id' => '222', 'ad_group_id' => '333', 'ad_id' => '444'],
        ]);

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

        return $campaign;
    }

    /**
     * @param  string  $bidding  the campaign's bid strategy, which decides whether a bid may be copied
     */
    private function fakeGoogle(
        string $bidding = 'MANUAL_CPC',
        ?array $keywords = null,
        bool $createsFail = false,
        bool $removalFails = false,
        ?array $ads = null,
        bool $adReadbackMismatch = false,
    ): void {
        $keywords ??= [
            ['adGroupCriterion' => ['keyword' => ['text' => 'car insurance', 'matchType' => 'PHRASE'], 'negative' => false]],
            ['adGroupCriterion' => ['keyword' => ['text' => 'free', 'matchType' => 'BROAD'], 'negative' => true]],
        ];

        $rsa = [
            'adGroupAd' => ['ad' => [
                'id' => '444',
                'name' => 'RSA one',
                'finalUrls' => ['https://example.com/offer'],
                'responsiveSearchAd' => [
                    'headlines' => [['text' => 'Cheap car cover', 'pinnedField' => 'HEADLINE_1'], ['text' => 'Fast quotes']],
                    'descriptions' => [['text' => 'Compare and save today.']],
                    'path1' => 'insurance',
                ],
            ]],
            'adGroup' => ['resourceName' => 'customers/3460855874/adGroups/333'],
        ];

        $newGroup = null;
        $newAd = null;
        Http::fake([
            'oauth2.googleapis.com/*' => Http::response(['access_token' => 'token', 'expires_in' => 3600]),
            '*googleAds:searchStream' => function (ClientRequest $request) use ($bidding, $keywords, $rsa, $ads, $adReadbackMismatch, &$newGroup, &$newAd) {
                $query = (string) ($request->data()['query'] ?? '');
                if (str_contains($query, 'ad_group_ad.ad.id = 888') && $newAd !== null) {
                    $readback = $newAd;
                    if ($adReadbackMismatch) {
                        $readback['ad']['finalUrls'] = ['https://wrong.example.com'];
                    }

                    return Http::response([['results' => [['adGroupAd' => $readback, 'adGroup' => ['resourceName' => $newAd['adGroup']]]]]]);
                }
                if (str_contains($query, 'FROM ad_group WHERE ad_group.id = 999') && $newGroup !== null) {
                    return Http::response([['results' => [['adGroup' => $newGroup]]]]);
                }
                $criterionGroup = str_contains($query, 'ad_group.id = 999') ? '999' : '333';

                $rows = match (true) {
                    str_contains($query, 'FROM ad_group_asset'), str_contains($query, 'FROM ad_group_customizer'), str_contains($query, 'FROM ad_group_bid_modifier') => [],
                    str_contains($query, "IN ('AGE_RANGE'") => [],
                    str_starts_with($query, 'SELECT ad_group_criterion.type FROM') => array_map(
                        fn (array $row): array => ['adGroupCriterion' => ['type' => 'KEYWORD']], $keywords,
                    ),
                    str_contains($query, "ad_group_criterion.type = 'KEYWORD'") => array_map(
                        fn (array $row, int $index): array => ['adGroup' => ['id' => $criterionGroup], 'adGroupCriterion' => [
                            'resourceName' => 'customers/3460855874/adGroupCriteria/'.$criterionGroup.'~'.($index + 1), 'status' => 'ENABLED', ...$row['adGroupCriterion'],
                        ]], $keywords, array_keys($keywords),
                    ),
                    str_contains($query, 'FROM ad_group_criterion') => array_map(
                        fn (array $row): array => ['adGroup' => ['id' => $criterionGroup], ...$row], $keywords,
                    ),
                    // The copy read asks for the campaign's bid strategy; the
                    // structure read does not, which is how they are told apart.
                    str_contains($query, 'campaign.bidding_strategy_type') => [[
                        'adGroup' => [
                            'id' => '333', 'name' => 'Brand terms', 'type' => 'SEARCH_STANDARD',
                            'cpcBidMicros' => '1500000', 'campaign' => 'customers/3460855874/campaigns/222',
                        ],
                        'campaign' => ['biddingStrategyType' => $bidding],
                    ]],
                    str_contains($query, 'FROM ad_group_ad') => $ads ?? [$rsa],
                    str_contains($query, 'FROM ad_group') => [[
                        'adGroup' => ['id' => '333', 'name' => 'Brand terms', 'status' => 'ENABLED'],
                        'campaign' => ['advertisingChannelType' => 'SEARCH'],
                    ]],
                    default => [],
                };

                return Http::response([['results' => $rows]]);
            },
            '*adGroups:mutate' => function (ClientRequest $request) use ($removalFails, &$newGroup) {
                $removing = (bool) data_get($request->data(), 'operations.0.remove');

                if ($removing) {
                    return $removalFails
                        ? Http::response(['error' => ['message' => 'Removal refused.']], 403)
                        : Http::response(['results' => [['resourceName' => 'x']]]);
                }

                $newGroup = $request['operations'][0]['create'];

                return Http::response(['results' => [['resourceName' => 'customers/3460855874/adGroups/999']]]);
            },
            '*adGroupCriteria:mutate' => $createsFail
                ? Http::response(['error' => ['message' => 'Keyword refused.']], 403)
                : Http::response(['results' => [['resourceName' => 'x']]]),
            '*adGroupAds:mutate' => function (ClientRequest $request) use ($removalFails, &$newAd) {
                if (isset($request['operations'][0]['remove']) && $removalFails) {
                    return Http::response(['error' => ['message' => 'Removal refused.']], 403);
                }
                if (isset($request['operations'][0]['create'])) {
                    $newAd = $request['operations'][0]['create'];
                    $newAd['ad']['id'] = '888';
                }

                $group = basename($newAd['adGroup']);

                return Http::response(['results' => [['resourceName' => 'customers/3460855874/adGroupAds/'.$group.'~888']]]);
            },
        ]);
    }

    /** @return list<string> every resource a remove operation was sent for */
    private function removed(): array
    {
        $names = [];

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

        return $names;
    }

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

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

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

    /** @return list<array<string,mixed>> every create payload sent */
    private function created(string $collection): array
    {
        $payloads = [];

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

            // Every operation, not just the first: keyword criteria are sent as
            // one batched call, so reading index zero would see one keyword
            // however many were copied.
            foreach ((array) ($request->data()['operations'] ?? []) as $operation) {
                if (($create = $operation['create'] ?? null) !== null) {
                    $payloads[] = (array) $create;
                }
            }
        }

        return $payloads;
    }

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

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

        $result = $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('999', $result['ad_group_id']);
        $this->assertSame('333', $result['copied_from']);
    }

    /** Paused, so a copy never starts spending on its own. */
    public function test_the_copy_is_created_paused(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertSame('PAUSED', $this->created('adGroups')[0]['status']);
    }

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

        $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertSame('Brand terms (copy)', $this->created('adGroups')[0]['name']);
    }

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

        $this->copy(['entity_type' => 'ad_group', 'id' => '333', 'name' => 'Brand exact']);

        $this->assertSame('Brand exact', $this->created('adGroups')[0]['name']);
    }

    /** The keywords come with it, which is the point of copying an ad group. */
    public function test_the_keywords_come_with_it(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertSame(2, $result['keywords']);
        $this->assertSame(
            [['text' => 'car insurance', 'matchType' => 'PHRASE'], ['text' => 'free', 'matchType' => 'BROAD']],
            array_column($this->created('adGroupCriteria'), 'keyword'),
        );
    }

    /**
     * A negative stays negative.
     *
     * The worst way for this to be wrong: an exclusion silently copied as a
     * target spends the budget on the terms the buyer ruled out.
     */
    public function test_a_negative_keyword_is_not_copied_as_a_target(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertSame([false, true], array_column($this->created('adGroupCriteria'), 'negative'));
    }

    // ---------------------------------------------------------------- the bid

    /** Under manual CPC the source bid is carried. */
    public function test_the_bid_is_copied_under_manual_cpc(): void
    {
        $this->campaign();
        $this->fakeGoogle(bidding: 'MANUAL_CPC');

        $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertSame('1500000', $this->created('adGroups')[0]['cpcBidMicros']);
    }

    /**
     * And under Smart Bidding it is not, because Google refuses the field.
     *
     * The publish path records the error it gets:
     * OPERATION_NOT_PERMITTED_FOR_CONTEXT. A copy is the one place a stale bid
     * would be carried over from a source that predates a bidding change.
     */
    public function test_the_bid_is_not_copied_under_smart_bidding(): void
    {
        $this->campaign();
        $this->fakeGoogle(bidding: 'MAXIMIZE_CONVERSIONS');

        $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertArrayNotHasKey('cpcBidMicros', $this->created('adGroups')[0]);
    }

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

    /** Its ads come too, unless told otherwise. */
    public function test_the_ads_are_copied_with_the_ad_group(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertSame(['888'], $result['ads']);
        $this->assertCount(1, $this->created('adGroupAds'));
    }

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

        $result = $this->copy(['entity_type' => 'ad_group', 'id' => '333', 'include_ads' => false]);

        $this->assertSame([], $result['ads']);
        $this->assertSame([], $this->created('adGroupAds'));
    }

    /** A single ad can be copied on its own, into its own ad group. */
    public function test_one_ad_can_be_copied_on_its_own(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->copy(['entity_type' => 'ad', 'id' => '444']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('888', $result['ad_id']);
        $this->assertSame('customers/3460855874/adGroups/333', $this->created('adGroupAds')[0]['adGroup']);
    }

    public function test_failed_ad_copy_cleanup_never_claims_that_nothing_was_created(): void
    {
        $this->campaign();
        $this->fakeGoogle(removalFails: true, adReadbackMismatch: true);
        $result = $this->copy(['entity_type' => 'ad', 'id' => '444']);
        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Cleanup is incomplete', $result['error']);
        $this->assertStringContainsString('customers/3460855874/adGroupAds/333~888', $result['error']);
        $this->assertStringNotContainsString('Nothing was copied', $result['note']);
    }

    /**
     * A pinned headline stays pinned.
     *
     * A pin decides where Google may show that headline, so dropping it on a
     * copy quietly changes what the ad is allowed to look like.
     */
    public function test_a_pinned_headline_keeps_its_pin(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $this->copy(['entity_type' => 'ad', 'id' => '444']);

        $this->assertSame(
            [['text' => 'Cheap car cover', 'pinnedField' => 'HEADLINE_1'], ['text' => 'Fast quotes']],
            data_get($this->created('adGroupAds')[0], 'ad.responsiveSearchAd.headlines'),
        );
    }

    /** And the display path, which is part of what the ad shows. */
    public function test_the_display_path_is_carried(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $this->copy(['entity_type' => 'ad', 'id' => '444']);

        $this->assertSame('insurance', data_get($this->created('adGroupAds')[0], 'ad.responsiveSearchAd.path1'));
    }

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

        $this->copy(['entity_type' => 'ad', 'id' => '444']);

        $this->assertSame('PAUSED', $this->created('adGroupAds')[0]['status']);
    }

    // -------------------------------------------------------- half-built copies

    /**
     * A copy that failed part way is taken back.
     *
     * An ad group with no keywords is worse than no ad group: it looks like a
     * working thing in the Google UI and serves nothing.
     */
    public function test_a_failure_after_the_ad_group_exists_removes_it(): void
    {
        $this->campaign();
        $this->fakeGoogle(createsFail: true);

        $result = $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('partly built copy was removed', $result['error']);
        $this->assertSame(['customers/3460855874/adGroups/999'], $this->removed(),
            'the ad group was left behind after its keywords failed');
    }

    /** And if it cannot be taken back, the buyer is told what is still there. */
    public function test_an_ad_group_that_cannot_be_removed_is_named(): void
    {
        $this->campaign();
        $this->fakeGoogle(createsFail: true, removalFails: true);

        $result = $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('still on the account', $result['error']);
        $this->assertStringContainsString('customers/3460855874/adGroups/999', $result['error']);
    }

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

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

        $result = $this->copy(['entity_type' => 'ad_group', 'id' => '999']);

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

    /** An ad cannot be copied into another campaign's ad group. */
    public function test_a_destination_outside_the_campaign_is_refused(): void
    {
        $this->campaign();
        $this->fakeGoogle();

        $result = $this->copy(['entity_type' => 'ad', 'id' => '444', 'ad_group_id' => '777']);

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

    public function test_an_unpublished_campaign_is_refused(): void
    {
        $this->campaign(status: 'draft');
        Http::fake();

        $result = $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

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

    /** Meta is pointed at the tool that does work for it. */
    public function test_meta_is_refused_and_pointed_at_duplicate_campaign(): void
    {
        $this->campaign(platform: 'meta');
        Http::fake();

        $result = $this->copy(['entity_type' => 'ad_set', 'id' => '333']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('only available on Google', $result['error']);
        $this->assertStringContainsString('duplicate_campaign', $result['note']);
        Http::assertNothingSent();
    }

    /**
     * An ad group of a kind this cannot copy is refused before anything is made.
     *
     * copyResponsiveSearchAds asks only for responsive_search_ad fields, so a
     * responsive display ad, a call-only ad or a dynamic search ad reads back
     * with no headlines and createCopiedAd throws - after the new ad group
     * already exists. The copy was built, torn down by undo(), and the buyer
     * was told their ad had "no readable headlines" about a copy that could
     * never have worked. One read up front makes the refusal true.
     */
    public function test_an_ad_group_with_no_responsive_search_ads_is_refused_before_anything_is_created(): void
    {
        $this->campaign();
        $this->fakeGoogle(ads: [[
            'adGroupAd' => ['ad' => [
                'id' => '444',
                'name' => 'Display ad',
                'finalUrls' => ['https://example.com/offer'],
            ]],
            'adGroup' => ['resourceName' => 'customers/3460855874/adGroups/333'],
        ]]);

        $result = $this->copy(['entity_type' => 'ad_group', 'id' => '333']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('unsupported creative format', $result['error']);
        $this->assertSame([], $this->created('adGroups'), 'nothing may be created when the copy cannot work');
    }

    /** Copying without its ads is still allowed for such an ad group. */
    public function test_the_same_ad_group_can_still_be_copied_without_its_ads(): void
    {
        $this->campaign();
        $this->fakeGoogle(ads: [[
            'adGroupAd' => ['ad' => ['id' => '444', 'name' => 'Display ad']],
            'adGroup' => ['resourceName' => 'customers/3460855874/adGroups/333'],
        ]]);

        $result = $this->copy(['entity_type' => 'ad_group', 'id' => '333', 'include_ads' => false]);

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