<?php

namespace Tests\Feature;

use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

/**
 * Two campaigns for the same page on the same day.
 *
 * Google refuses a campaign whose name an active or paused campaign on the
 * account already has - DUPLICATE_CAMPAIGN_NAME at operations.create.name -
 * and the generated name is <page>_<user>-u<id>_<PLATFORM>_<date>. Nothing in
 * that tells two campaigns apart, so a buyer publishing a second campaign for
 * the same landing page on the same day could not publish at all, and the
 * error they met does not say that renaming it is the fix.
 *
 * Found by publishing one: a verification campaign for iblockads.org was
 * refused because iblockads_shyam-u4_GOOGLE_2026-10-21 already existed.
 *
 * The name is settled before anything is sent rather than by retrying the
 * refusal, because the budget is created before the campaign and retrying the
 * whole operation would leave an orphan budget behind every time.
 */
class ASecondCampaignForTheSamePageCanPublishTest extends TestCase
{
    use RefreshDatabase;

    /** @var list<string> */
    private array $createdNames = [];

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

        config([
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['google:1234567890'],
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '123-456-7890',
        ]);
    }

    /** @param  list<string>  $existing  names already on the account */
    private function fakeGoogle(array $existing): void
    {
        $this->createdNames = [];

        Http::fake(function (Request $request) use ($existing) {
            if (str_contains($request->url(), 'oauth2.googleapis.com')) {
                return Http::response(['access_token' => 'token', 'expires_in' => 3600]);
            }

            if (str_contains($request->url(), 'googleAds:searchStream')) {
                $query = (string) ($request->data()['query'] ?? '');

                if (str_contains($query, 'campaign.name') && str_contains($query, 'FROM campaign')) {
                    return Http::response([[
                        'results' => array_map(
                            static fn (string $name): array => ['campaign' => ['name' => $name]],
                            $existing,
                        ),
                    ]]);
                }

                return Http::response([['results' => []]]);
            }

            if (str_contains($request->url(), 'campaignBudgets:mutate')) {
                return Http::response(['results' => [['resourceName' => 'customers/1234567890/campaignBudgets/1']]]);
            }

            if (str_contains($request->url(), 'campaigns:mutate')) {
                $this->createdNames[] = (string) data_get($request->data(), 'operations.0.create.name', '');

                return Http::response(['results' => [['resourceName' => 'customers/1234567890/campaigns/2']]]);
            }

            if (str_contains($request->url(), 'adGroups:mutate')) {
                return Http::response(['results' => [['resourceName' => 'customers/1234567890/adGroups/3']]]);
            }

            if (str_contains($request->url(), 'adGroupAds:mutate')) {
                return Http::response(['results' => [['resourceName' => 'customers/1234567890/adGroupAds/3~4']]]);
            }

            return Http::response(['results' => []]);
        });
    }

    /** @return array<string,mixed> */
    private function publish(string $name): array
    {
        $created = [];

        return app(GoogleAdsService::class)->createPausedCampaign(
            GoogleAdsConnection::shared(),
            [
                'name' => $name,
                'campaign_type' => 'search',
                'daily_budget' => 10,
                'final_url' => 'https://iblockads.org/extension/landing',
                'headlines' => ['Headline one', 'Headline two', 'Headline three'],
                'descriptions' => ['Description one here', 'Description two here'],
                'keyword_criteria' => [['text' => 'ad blocker', 'match_type' => 'PHRASE', 'negative' => false]],
                'geo_targets' => ['geoTargetConstants/2840'],
                'ad_group_name' => 'Ad group 1',
            ],
            $created,
        );
    }

    /** A free name goes out exactly as asked. */
    public function test_a_name_nobody_is_using_is_sent_unchanged(): void
    {
        $this->fakeGoogle(['something else entirely']);

        $ids = $this->publish('iblockads_shyam-u4_GOOGLE_2026-10-21');

        $this->assertSame(['iblockads_shyam-u4_GOOGLE_2026-10-21'], $this->createdNames);
        $this->assertSame('iblockads_shyam-u4_GOOGLE_2026-10-21', $ids['name']);
    }

    /** The reported case: the name is taken, so the next free one is used. */
    public function test_a_taken_name_publishes_as_the_next_free_variation(): void
    {
        $this->fakeGoogle(['iblockads_shyam-u4_GOOGLE_2026-10-21']);

        $ids = $this->publish('iblockads_shyam-u4_GOOGLE_2026-10-21');

        $this->assertSame(['iblockads_shyam-u4_GOOGLE_2026-10-21 #2'], $this->createdNames);
        $this->assertSame('iblockads_shyam-u4_GOOGLE_2026-10-21 #2', $ids['name']);
    }

    /** And it keeps counting rather than stopping at two. */
    public function test_it_finds_the_first_free_number(): void
    {
        $this->fakeGoogle([
            'iblockads_shyam-u4_GOOGLE_2026-10-21',
            'iblockads_shyam-u4_GOOGLE_2026-10-21 #2',
            'iblockads_shyam-u4_GOOGLE_2026-10-21 #3',
        ]);

        $this->publish('iblockads_shyam-u4_GOOGLE_2026-10-21');

        $this->assertSame(['iblockads_shyam-u4_GOOGLE_2026-10-21 #4'], $this->createdNames);
    }

    /** Google's uniqueness ignores case, so this has to as well. */
    public function test_the_match_ignores_case(): void
    {
        $this->fakeGoogle(['IBLOCKADS_SHYAM-U4_GOOGLE_2026-10-21']);

        $this->publish('iblockads_shyam-u4_GOOGLE_2026-10-21');

        $this->assertSame(['iblockads_shyam-u4_GOOGLE_2026-10-21 #2'], $this->createdNames);
    }

    /**
     * A removed campaign does not hold its name.
     *
     * The query asks for the ones that are not removed, so a name freed by a
     * removal is reused rather than skipped - which is what a buyer who just
     * deleted a campaign and rebuilt it expects.
     */
    public function test_the_query_ignores_removed_campaigns(): void
    {
        $this->fakeGoogle([]);

        $this->publish('iblockads_shyam-u4_GOOGLE_2026-10-21');

        $queries = [];

        foreach (Http::recorded() as [$request]) {
            if (str_contains((string) $request->url(), 'googleAds:searchStream')) {
                $queries[] = (string) ($request->data()['query'] ?? '');
            }
        }

        $this->assertNotSame([], $queries);
        $this->assertStringContainsString("campaign.status != 'REMOVED'", $queries[0]);
    }
}
