<?php

namespace Tests\Feature;

use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use RuntimeException;
use Tests\TestCase;

/**
 * There is no product cap on how many Search keywords a campaign may have.
 *
 * "The draft accepts at most 20 included keywords, so the 33 combinations
 * weren't saved." Reported as soon as the match types shipped: eleven terms at
 * all three is thirty-three criteria, and the save refused it, so he typed
 * combinations by hand and published eleven phrase-match keywords.
 *
 * The twenty was this product's own, not Google's, and the ask was to remove
 * it rather than to change what it counts. Google's limit is the one that
 * applies now: it takes thousands of keywords in an ad group, and whatever it
 * refuses it refuses for itself, with its own message.
 *
 * What is left is the shape of a keyword set rather than its size. At least
 * one included keyword, because a Search campaign with none cannot run and the
 * publish gate refuses it anyway. No duplicate criterion. Nothing both
 * included and excluded. And a backstop at Google's documented ad-group
 * ceiling, which exists so a runaway payload fails on our side with a sentence
 * rather than somewhere inside a provider error.
 */
class NoProductCapOnSearchKeywordsTest extends TestCase
{
    use RefreshDatabase;

    private Campaign $campaign;

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

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

        $this->campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Keyword ceiling',
            'platform' => 'google',
            'campaign_type' => 'search',
            'status' => 'draft',
            'ad_account_id' => '3460855874',
            'objective' => 'SALES',
            'landing_url' => 'https://stockprices.com/landing',
            'locations' => ['countries' => ['US']],
        ]);

        app(TargetingSelections::class)->saveCampaignCountries($this->campaign, ['US']);
        app(TargetingSelections::class)->chooseWholeCountries($this->campaign->fresh());
        $this->campaign = $this->campaign->fresh();
    }

    /**
     * @param  list<string>  $matchTypes
     * @return list<array{text: string, match_type: string, negative: bool}>
     */
    private function terms(int $count, array $matchTypes, bool $negative = false): array
    {
        $criteria = [];

        for ($i = 0; $i < $count; $i++) {
            foreach ($matchTypes as $matchType) {
                $criteria[] = ['text' => 'stock term '.$i, 'match_type' => $matchType, 'negative' => $negative];
            }
        }

        return $criteria;
    }

    /** @return list<array{text: string, match_type: string, negative: bool}> */
    private function negatives(int $count): array
    {
        $criteria = [];

        for ($i = 0; $i < $count; $i++) {
            $criteria[] = ['text' => 'exclude me '.$i, 'match_type' => 'BROAD', 'negative' => true];
        }

        return $criteria;
    }

    /** @param list<array<string,mixed>> $criteria */
    private function save(array $criteria): void
    {
        app(SearchKeywordSelections::class)->save(
            $this->campaign,
            $criteria,
            (int) ($this->campaign->targetingSet()->value('revision') ?? 0),
        );
    }

    /** His exact case: eleven terms at all three match types. */
    public function test_eleven_terms_at_three_match_types_is_saved(): void
    {
        $this->save($this->terms(11, ['BROAD', 'PHRASE', 'EXACT']));

        $this->assertCount(33, app(SearchKeywordSelections::class)->criteria($this->campaign->fresh()));
    }

    /** Well past the old twenty, which is the point of removing it. */
    public function test_a_hundred_and_twenty_terms_are_saved(): void
    {
        $this->save($this->terms(120, ['PHRASE']));

        $this->assertCount(120, app(SearchKeywordSelections::class)->criteria($this->campaign->fresh()));
    }

    /** And past the old criteria backstop, in both dimensions at once. */
    public function test_eighty_terms_at_three_match_types_are_saved(): void
    {
        $this->save($this->terms(80, ['BROAD', 'PHRASE', 'EXACT']));

        $this->assertCount(240, app(SearchKeywordSelections::class)->criteria($this->campaign->fresh()));
    }

    /** Negatives are not capped either. */
    public function test_many_negatives_are_saved(): void
    {
        $this->save([
            ...$this->terms(30, ['BROAD', 'PHRASE', 'EXACT']),
            ...$this->negatives(30),
        ]);

        $this->assertCount(120, app(SearchKeywordSelections::class)->criteria($this->campaign->fresh()));
    }

    /** A Search campaign still needs at least one keyword to run on. */
    public function test_a_set_with_no_included_keyword_is_refused(): void
    {
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('at least one included');

        $this->save($this->negatives(3));
    }

    /** The shape rules that are not about size still hold. */
    public function test_a_duplicate_criterion_is_still_refused(): void
    {
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('duplicated');

        $this->save([
            ['text' => 'stock analysis', 'match_type' => 'PHRASE', 'negative' => false],
            ['text' => 'stock analysis', 'match_type' => 'PHRASE', 'negative' => false],
        ]);
    }

    /**
     * Google's own ceiling is the only number left.
     *
     * Documented at 20,000 keywords per ad group rather than measured here -
     * publishing twenty thousand to find out is not a test anyone should run.
     * It is a backstop on a runaway payload, not a limit a buyer can meet.
     */
    public function test_the_only_remaining_bound_is_googles(): void
    {
        $this->assertSame(20000, SearchKeywordSelections::MOST_CRITERIA);
        $this->assertFalse(
            defined(SearchKeywordSelections::class.'::MOST_INCLUDED_TERMS'),
            'the product cap is back',
        );
    }
}
