<?php

namespace Tests\Feature;

use App\Campaigns\Targeting\BrandTerms;
use App\DTOs\LandingPageAnalysis;
use Tests\TestCase;

/**
 * Two things media buyers asked for after testing Google on production.
 *
 * "keywords should be generic and non brand" - page keywords are read off the
 * page, so the advertiser's own name is usually the most repeated term on it
 * and led every suggestion list. Somebody searching the advertiser by name has
 * already found them, so those clicks mostly pay for traffic that was coming
 * anyway.
 *
 * "ability to select multiple events and optimise on them" - narrowConversionGoals
 * took one conversion action and switched every other category off, so a
 * campaign could optimise toward exactly one thing. Google allows several.
 */
class KeywordsAreGenericAndEventsCanBeMultipleTest extends TestCase
{
    private function page(string $url, string $title): LandingPageAnalysis
    {
        return new LandingPageAnalysis(
            url: $url, title: $title, description: '', headings: [], text: '', keywords: [],
        );
    }

    public function test_the_brand_is_taken_from_the_title_and_the_host(): void
    {
        $brand = new BrandTerms;

        $this->assertSame(
            ['iblockads'],
            $brand->forPage($this->page('https://iblockads.org/extension', 'iblockads | Browse Without Ads')),
            'the title and the host agree here, so one token is right',
        );

        $this->assertContains(
            'lucos',
            $brand->forPage($this->page('https://lucos.com/landing', 'Compare Insurance Quotes')),
            'a title that is pure marketing copy still has the host to go on',
        );
    }

    /**
     * A descriptive title is not a name, and used to be read as one.
     *
     * businessName() returns the whole title where there is no separator in it,
     * and the first heading where there is no title at all. Both counted as
     * brand, so a page titled "Flights to Italy" made "flights" and "italy"
     * brand terms and threw away "cheap flights to italy" - the best keyword
     * the page had - as the advertiser's own name. On a landing page, which is
     * usually titled with a sentence about the product, that quietly removed
     * most of the list.
     *
     * A title word now has to be the host as well to count.
     */
    public function test_a_descriptive_title_is_not_treated_as_the_brand(): void
    {
        $brand = new BrandTerms;
        $page = $this->page('https://example.com/flights', 'Flights to Italy');
        $tokens = $brand->forPage($page);

        $this->assertNotContains('flights', $tokens);
        $this->assertNotContains('italy', $tokens);

        $this->assertSame(
            ['cheap flights to italy', 'rome city break', 'flights to milan'],
            $brand->withoutBrand(['cheap flights to italy', 'rome city break', 'flights to milan'], $tokens),
        );
    }

    /**
     * And a heading is not a name either.
     *
     * With no title, businessName() falls back to the first heading, so on
     * iblockads.org that was "Browse the Web Without Ads" and "browse", "ads"
     * and "trackers" all became the brand.
     */
    public function test_a_heading_standing_in_for_a_title_is_not_the_brand(): void
    {
        $brand = new BrandTerms;
        $tokens = $brand->forPage(new LandingPageAnalysis(
            url: 'https://iblockads.org/extension',
            title: '',
            description: '',
            headings: ['Browse the Web Without Ads and Trackers'],
            text: '',
            keywords: [],
        ));

        $this->assertNotContains('browse', $tokens);
        $this->assertNotContains('trackers', $tokens);
        $this->assertContains('iblockads', $tokens, 'the host is still the brand');
    }

    /**
     * A domain that is itself a description must not become generic brand.
     *
     * stockprices.com is one token, "stockprices". Splitting it into "stock"
     * and "prices" would take out "stock analysis", "stock market" and most of
     * what that account exists to bid on - which is exactly the list its buyer
     * typed in by hand. The whole host still catches "stock prices today".
     */
    public function test_a_descriptive_domain_does_not_make_its_words_brand(): void
    {
        $brand = new BrandTerms;
        $page = $this->page('https://stockprices.com/landing', 'Stock Prices, Charts and Analysis');
        $tokens = $brand->forPage($page);

        $this->assertSame(['stockprices'], $tokens);

        // The five a buyer typed for that account, all kept.
        $typed = ['stock', 'stock market', 'stocks', 'stock analysis', 'stock traders'];
        $this->assertSame($typed, $brand->withoutBrand($typed, $tokens));

        // And the host written as words is still the brand.
        $this->assertTrue($brand->isBrand('stock prices today', $tokens));
    }

    public function test_the_advertisers_own_name_is_dropped_and_generic_terms_are_kept(): void
    {
        $brand = new BrandTerms;
        $tokens = $brand->forPage($this->page('https://iblockads.org/extension', 'iblockads | Browse Without Ads'));

        foreach (['iblockads', 'iblockads extension', 'download iblockads'] as $branded) {
            $this->assertTrue($brand->isBrand($branded, $tokens), "{$branded} is the advertiser's own name");
        }

        foreach (['ad blocker extension', 'block online trackers', 'free ad blocker', 'browse without ads'] as $generic) {
            $this->assertFalse($brand->isBrand($generic, $tokens), "{$generic} is intent worth buying");
        }
    }

    /**
     * A substring is not a brand match.
     *
     * "ads" sits inside "iblockads", and matching on substrings would take out
     * every keyword containing it - which on an ad blocker is most of the list.
     */
    public function test_a_word_inside_the_brand_does_not_count_as_the_brand(): void
    {
        $brand = new BrandTerms;
        $tokens = $brand->forPage($this->page('https://iblockads.org/x', 'iblockads'));

        $this->assertFalse($brand->isBrand('block ads', $tokens));
        $this->assertFalse($brand->isBrand('ads blocker', $tokens));
    }

    /** Words that appear in half of all business names are not brands. */
    public function test_generic_words_in_a_name_are_not_treated_as_the_brand(): void
    {
        $brand = new BrandTerms;
        $tokens = $brand->forPage($this->page('https://theshoponline.com/x', 'The Shop Online | Best Store'));

        $this->assertNotContains('shop', $tokens);
        $this->assertNotContains('online', $tokens);
        $this->assertNotContains('store', $tokens);
        $this->assertNotContains('best', $tokens);
    }

    /**
     * A list that is entirely brand comes back whole.
     *
     * Filtering to nothing would leave the buyer with no keywords and no
     * explanation, which is worse than a brand-heavy list they can edit.
     */
    public function test_a_list_that_is_all_brand_is_returned_rather_than_emptied(): void
    {
        $brand = new BrandTerms;
        $tokens = $brand->forPage($this->page('https://iblockads.org/x', 'iblockads'));

        $this->assertSame(
            ['iblockads', 'iblockads extension'],
            $brand->withoutBrand(['iblockads', 'iblockads extension'], $tokens),
        );
    }

    public function test_the_generic_terms_survive_a_mixed_list(): void
    {
        $brand = new BrandTerms;
        $tokens = $brand->forPage($this->page('https://iblockads.org/x', 'iblockads'));

        $this->assertSame(
            ['ad blocker extension', 'block trackers'],
            $brand->withoutBrand(['iblockads', 'ad blocker extension', 'iblockads download', 'block trackers'], $tokens),
        );
    }
}
