<?php

namespace Tests\Feature;

use App\Campaigns\Targeting\SearchKeywordSelections;
use App\DTOs\LandingPageAnalysis;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\User;
use App\Services\Keywords\AiLandingPageKeywords;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Ai;
use Laravel\Ai\StructuredAnonymousAgent;
use Tests\TestCase;

/**
 * How many keyword suggestions a page may offer: as many as it yields.
 *
 * Three numbers decided this and all three were ours. The page's own phrases
 * were cut to ten, the AI overlay stopped at fifteen, and the offer sliced at
 * twenty - which never bit, because it could only ever trim a list already
 * capped below it. So a page with thirty good searches in it offered fifteen,
 * and the buyer never knew the rest existed.
 *
 * Removed on the same reasoning as the twenty-keyword save cap: the numbers
 * were invented here, and the one that matters belongs to Google, which
 * refuses what it will not take in its own words. Nothing in Google decides
 * how many phrases a page contains, so there is nothing to defer to on this
 * side of it - the list is simply what the page and the model give.
 *
 * What remains is what a keyword is rather than how many: at most 80
 * characters and at most ten words, which are Google's own, and the brand
 * filter, which is a separate ask - "keywords should be generic and non
 * brand".
 */
class NoCapOnKeywordSuggestionsTest extends TestCase
{
    use RefreshDatabase;

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

        // Off in phpunit.xml, which is right for every other test: the real
        // keys are restricted and the deterministic phrases are the floor.
        config(['google-ads.ai_landing_page_keywords' => true]);
    }

    /** @param list<string> $keywords */
    private function aiReturns(array $keywords): void
    {
        Ai::fakeAgent(StructuredAnonymousAgent::class, [['keywords' => $keywords]]);
    }

    private function analysis(): LandingPageAnalysis
    {
        return new LandingPageAnalysis(
            url: 'https://stockprices.com/landing',
            title: 'Stock Analysis Tools',
            description: 'Real-time market data and AI insights.',
            headings: ['Track every ticker'],
            text: 'Track every ticker in real time with charts and AI insights.',
            keywords: [],
        );
    }

    /** @return list<string> */
    private function manyPhrases(int $count): array
    {
        $phrases = [];

        for ($i = 0; $i < $count; $i++) {
            $phrases[] = 'stock analysis phrase '.$i;
        }

        return $phrases;
    }

    /** Thirty from the model, thirty offered. */
    public function test_the_ai_overlay_keeps_everything_the_model_returns(): void
    {
        $this->aiReturns($this->manyPhrases(30));

        $this->assertCount(30, app(AiLandingPageKeywords::class)->forPage($this->analysis()));
    }

    /** Well past the old fifteen, to show there is no new number behind it. */
    public function test_a_hundred_suggestions_survive(): void
    {
        $this->aiReturns($this->manyPhrases(100));

        $this->assertCount(100, app(AiLandingPageKeywords::class)->forPage($this->analysis()));
    }

    /** Google's own keyword rules still apply to each one. */
    public function test_googles_own_limits_are_still_enforced(): void
    {
        $this->aiReturns([
            'stock analysis platform',
            // Eleven words, which Google refuses.
            'one two three four five six seven eight nine ten eleven',
            str_repeat('a', 81),
            // One word is a search a buyer makes, so it is kept now.
            'stocks',
        ]);

        $kept = app(AiLandingPageKeywords::class)->forPage($this->analysis());

        $this->assertContains('stock analysis platform', $kept);
        $this->assertContains('stocks', $kept);
        $this->assertNotContains('one two three four five six seven eight nine ten eleven', $kept);
        $this->assertNotContains(str_repeat('a', 81), $kept);
    }

    /** Duplicates are still one keyword. */
    public function test_duplicates_are_still_collapsed(): void
    {
        $this->aiReturns(['stock analysis', 'Stock Analysis', 'stock analysis']);

        $this->assertSame(['stock analysis'], app(AiLandingPageKeywords::class)->forPage($this->analysis()));
    }

    /** Every suggestion the brief carries reaches the buyer. */
    public function test_the_offer_does_not_trim_the_list(): void
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $brief = Brief::create([
            'user_id' => $user->getKey(),
            'landing_url' => 'https://stockprices.com/landing',
            'page_analysis' => [
                'url' => 'https://stockprices.com/landing',
                'title' => 'Stock Analysis Tools',
                'keywords' => $this->manyPhrases(45),
            ],
        ]);

        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Suggestions',
            'platform' => 'google',
            'campaign_type' => 'search',
            'status' => 'draft',
            'ad_account_id' => '3460855874',
            'objective' => 'SALES',
            'landing_url' => 'https://stockprices.com/landing',
            'brief_id' => $brief->id,
        ]);

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