<?php

namespace Tests\Feature;

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

/**
 * Sitelinks and callouts, which no Google campaign here has ever had.
 *
 * Both are listed in SERP-1834 and neither existed, so every campaign this
 * product published went out with the bare ad. They are among the cheapest
 * things a Search campaign can carry: more of the results page, more ways in,
 * no extra cost.
 *
 * The content is read off the landing page rather than written. A sitelink is
 * another page on the advertiser's site with the label the advertiser gave it,
 * and a callout is one of their own short claims. An ad asset is published
 * copy, and the product has no business inventing it.
 */
class GoogleCampaignsCarrySitelinksAndCalloutsTest extends TestCase
{
    private function page(array $overrides = []): LandingPageAnalysis
    {
        return new LandingPageAnalysis(
            url: $overrides['url'] ?? 'https://iblockads.org/extension/landing',
            title: 'iblockads',
            description: '',
            headings: $overrides['headings'] ?? [],
            text: '',
            keywords: [],
            subheadings: $overrides['subheadings'] ?? [],
            callsToAction: $overrides['callsToAction'] ?? [],
            sameHostLinks: $overrides['sameHostLinks'] ?? [],
        );
    }

    public function test_sitelinks_come_from_the_pages_own_links(): void
    {
        $sitelinks = app(GoogleAdAssets::class)->sitelinksFor($this->page([
            'sameHostLinks' => [
                ['url' => 'https://iblockads.org/features', 'label' => 'Features'],
                ['url' => 'https://iblockads.org/pricing', 'label' => 'Pricing'],
                ['url' => 'https://iblockads.org/compare', 'label' => 'Compare Plans'],
                // Support is help furniture, not somewhere worth buying a click
                // to. It joined the excluded list after a live ad went out with
                // "Terms of Use" and "Login to continue" as assets.
                ['url' => 'https://iblockads.org/support', 'label' => 'Support'],
            ],
        ]));

        $this->assertSame([
            ['text' => 'Features', 'final_url' => 'https://iblockads.org/features'],
            ['text' => 'Pricing', 'final_url' => 'https://iblockads.org/pricing'],
            ['text' => 'Compare Plans', 'final_url' => 'https://iblockads.org/compare'],
        ], $sitelinks);
    }

    /**
     * What a page that lists things does to this.
     *
     * stockprices.com lists its tickers as links, so the page's own same-host
     * links included "PRSO Peraso Inc. +54.13%" - and it went out as a sitelink
     * on a live ad, alongside "Login to continue". A blocklist of labels cannot
     * catch a row of data; its shape can.
     */
    public function test_a_row_of_data_is_not_a_sitelink(): void
    {
        $sitelinks = app(GoogleAdAssets::class)->sitelinksFor($this->page([
            'sameHostLinks' => [
                ['url' => 'https://stockprices.com/q/prso', 'label' => 'PRSO Peraso Inc. +54.13%'],
                ['url' => 'https://stockprices.com/q/brze', 'label' => 'BRZE Braze, Inc. +51.70%'],
                ['url' => 'https://stockprices.com/login', 'label' => 'Login to continue'],
                ['url' => 'https://stockprices.com/screener', 'label' => 'Stock Screener'],
                ['url' => 'https://stockprices.com/watchlist', 'label' => 'Build A Watchlist'],
            ],
        ]));

        $this->assertSame([
            ['text' => 'Stock Screener', 'final_url' => 'https://stockprices.com/screener'],
            ['text' => 'Build A Watchlist', 'final_url' => 'https://stockprices.com/watchlist'],
        ], $sitelinks);
    }

    /** The callouts from that same live ad. */
    public function test_an_instruction_to_sign_in_is_not_a_callout(): void
    {
        $callouts = app(GoogleAdAssets::class)->calloutsFor($this->page([
            'callsToAction' => ['Login to continue', 'Subscribe Now', 'Continue', 'Learn more'],
            'subheadings' => ['Real-Time Market Data', 'Advanced Charting', 'Terms of Use'],
        ]));

        foreach (['Login to continue', 'Subscribe Now', 'Continue', 'Learn more', 'Terms of Use'] as $rejected) {
            $this->assertNotContains($rejected, $callouts);
        }

        $this->assertContains('Real-Time Market Data', $callouts);
        $this->assertContains('Advanced Charting', $callouts);
    }

    /** Navigation furniture is not a destination worth buying a click to. */
    public function test_boilerplate_links_are_left_out(): void
    {
        $sitelinks = app(GoogleAdAssets::class)->sitelinksFor($this->page([
            'sameHostLinks' => [
                ['url' => 'https://iblockads.org/privacy', 'label' => 'Privacy Policy'],
                ['url' => 'https://iblockads.org/terms', 'label' => 'Terms'],
                ['url' => 'https://iblockads.org/login', 'label' => 'Log in'],
                ['url' => 'https://iblockads.org/features', 'label' => 'Features'],
                ['url' => 'https://iblockads.org/pricing', 'label' => 'Pricing'],
            ],
        ]));

        $this->assertSame(['Features', 'Pricing'], array_column($sitelinks, 'text'));
    }

    /**
     * Google will not serve a lone sitelink, so one is worse than none.
     *
     * It is published, it occupies the account, and it never shows.
     */
    public function test_a_single_sitelink_is_dropped_rather_than_published(): void
    {
        $sitelinks = app(GoogleAdAssets::class)->sitelinksFor($this->page([
            'sameHostLinks' => [['url' => 'https://iblockads.org/features', 'label' => 'Features']],
        ]));

        $this->assertSame([], $sitelinks);
    }

    /** Google refuses link text over 25 characters, so it is dropped not cut. */
    public function test_text_over_googles_limit_is_dropped_not_truncated(): void
    {
        $sitelinks = app(GoogleAdAssets::class)->sitelinksFor($this->page([
            'sameHostLinks' => [
                ['url' => 'https://iblockads.org/a', 'label' => 'Everything You Could Possibly Want To Know'],
                ['url' => 'https://iblockads.org/features', 'label' => 'Features'],
                ['url' => 'https://iblockads.org/pricing', 'label' => 'Pricing'],
            ],
        ]));

        $this->assertSame(['Features', 'Pricing'], array_column($sitelinks, 'text'));
    }

    /** The landing page itself is not a sitelink to the landing page. */
    public function test_the_landing_page_is_not_linked_to_itself(): void
    {
        $sitelinks = app(GoogleAdAssets::class)->sitelinksFor($this->page([
            'sameHostLinks' => [
                ['url' => 'https://iblockads.org/extension/landing', 'label' => 'Home'],
                ['url' => 'https://iblockads.org/features', 'label' => 'Features'],
                ['url' => 'https://iblockads.org/pricing', 'label' => 'Pricing'],
            ],
        ]));

        $this->assertSame(['Features', 'Pricing'], array_column($sitelinks, 'text'));
    }

    public function test_callouts_come_from_the_pages_own_claims(): void
    {
        $callouts = app(GoogleAdAssets::class)->calloutsFor($this->page([
            'callsToAction' => ['Install Free'],
            'subheadings' => ['Blocks Trackers', 'No Account Needed'],
        ]));

        $this->assertSame(['Install Free', 'Blocks Trackers', 'No Account Needed'], $callouts);
    }

    /** A callout is a claim, not a question or an instruction to the reader. */
    public function test_questions_and_form_instructions_are_not_callouts(): void
    {
        $callouts = app(GoogleAdAssets::class)->calloutsFor($this->page([
            'subheadings' => ['Why Choose Us?', 'Enter your email', 'Blocks Trackers', 'No Account Needed'],
        ]));

        $this->assertSame(['Blocks Trackers', 'No Account Needed'], $callouts);
    }

    public function test_a_single_callout_is_dropped(): void
    {
        $this->assertSame([], app(GoogleAdAssets::class)->calloutsFor($this->page([
            'subheadings' => ['Blocks Trackers'],
        ])));
    }

    public function test_a_page_with_nothing_to_offer_yields_nothing(): void
    {
        $assets = app(GoogleAdAssets::class);

        $this->assertSame([], $assets->sitelinksFor($this->page()));
        $this->assertSame([], $assets->calloutsFor($this->page()));
        $this->assertSame([], $assets->sitelinksFor(null));
        $this->assertSame([], $assets->calloutsFor(null));
    }

    // ------------------------------------------------- structured snippets

    /**
     * A snippet needs the page to say what kind of list it is offering.
     *
     * Google's header is not free text - it accepts a fixed list - and a header
     * that does not describe its values reads worse than no snippet at all.
     * "Amenities: Ad Blocker, Tracker Blocking" is a wrong answer dressed as a
     * feature, so nothing is emitted unless the page's own words imply one.
     */
    public function test_a_snippet_header_is_taken_from_the_pages_own_words(): void
    {
        $snippet = app(GoogleAdAssets::class)->structuredSnippetFor($this->page([
            'headings' => ['Our Services'],
            'subheadings' => ['Ad Blocking', 'Tracker Removal', 'Private Browsing'],
        ]));

        $this->assertSame('Service catalog', $snippet['header']);
        $this->assertSame(['Ad Blocking', 'Tracker Removal', 'Private Browsing'], $snippet['values']);
    }

    /** A page that implies no header gets no snippet, rather than a guessed one. */
    public function test_no_header_means_no_snippet(): void
    {
        $this->assertNull(app(GoogleAdAssets::class)->structuredSnippetFor($this->page([
            'headings' => ['Welcome'],
            'subheadings' => ['Fast', 'Private', 'Free'],
        ])));
    }

    /** Google needs three values; two is not a snippet. */
    public function test_fewer_than_three_values_is_not_a_snippet(): void
    {
        $this->assertNull(app(GoogleAdAssets::class)->structuredSnippetFor($this->page([
            'headings' => ['Our Services'],
            'subheadings' => ['Ad Blocking', 'Tracker Removal'],
        ])));
    }

    /** A caller may name the header, but only one Google accepts. */
    public function test_an_explicit_header_is_honoured_only_if_google_takes_it(): void
    {
        $assets = app(GoogleAdAssets::class);
        $page = $this->page(['subheadings' => ['Ad Blocking', 'Tracker Removal', 'Private Browsing']]);

        $this->assertSame('Types', $assets->structuredSnippetFor($page, 'Types')['header']);
        $this->assertSame('Brands', $assets->structuredSnippetFor($page, 'brands')['header'], 'case is not the buyer\'s problem');
        $this->assertNull($assets->structuredSnippetFor($page, 'Our Lovely Features'), 'Google would refuse this header');
    }

    /**
     * The send path refuses a header Google would not take.
     *
     * acceptsHeader is checked at both ends on purpose. attachCampaignAssets is
     * public, so a caller that built a snippet some other way would otherwise
     * have Google refuse it mid-batch - taking the sitelinks in the same
     * campaignAssets call down with it.
     */
    public function test_the_header_list_is_enforced_at_the_send_path_too(): void
    {
        $this->assertTrue(GoogleAdAssets::acceptsHeader('Types'));
        $this->assertTrue(GoogleAdAssets::acceptsHeader('service catalog'), 'case is not the caller\'s problem');
        $this->assertFalse(GoogleAdAssets::acceptsHeader('Our Lovely Features'));
        $this->assertFalse(GoogleAdAssets::acceptsHeader(''));
    }
}
