<?php

namespace Tests\Feature;

use App\Agent\Answers;
use App\Agent\Choices;
use App\Agent\Tools\Campaign\SetSearchKeywords;
use App\Agent\Workspace;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Tests\TestCase;

/**
 * "Need options to choose 1, 2 or all 3 match types in keyword selection."
 *
 * One match type per keyword was a limit this product invented. Google treats
 * "ad blocker" broad, "ad blocker" phrase and "ad blocker" exact as three
 * separate criteria and runs all three in one ad group - confirmed by
 * publishing them to 346-085-5874 and reading keyword_view back, which
 * returned BROAD, PHRASE and EXACT for the one text.
 *
 * Two things stood in the way. The row offered the match types as one choice,
 * and normalise() keyed its duplicate check on the keyword text alone, so a
 * second match type for the same word was refused as "a Search keyword cannot
 * be duplicated". The key is the criterion - text and match type together -
 * which is what Google counts as one keyword.
 *
 * Including and excluding the same text is still refused, whatever the match
 * types: that is a contradiction rather than a pair of criteria.
 */
class AKeywordCanBeTakenAtSeveralMatchTypesTest extends TestCase
{
    use RefreshDatabase;

    private Campaign $campaign;

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

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

        $brief = Brief::create([
            'user_id' => $user->getKey(),
            'landing_url' => 'https://example.com/flights',
            'page_analysis' => [
                'url' => 'https://example.com/flights',
                'title' => 'Weekend Breaks',
                'keywords' => ['rome city break', 'milan weekend break'],
            ],
        ]);

        $this->campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Several match types',
            'platform' => 'google',
            'campaign_type' => 'search',
            'status' => 'draft',
            'ad_account_id' => '3460855874',
            'objective' => 'SALES',
            'landing_url' => 'https://example.com/flights',
            'locations' => ['countries' => ['US']],
            'brief_id' => $brief->id,
        ]);

        app(Workspace::class)->bindTo('several-match-types');
        app(Workspace::class)->focusOn($this->campaign);
        app(TargetingSelections::class)->chooseWholeCountries($this->campaign);
        $this->campaign = $this->campaign->fresh();
    }

    private function ask(): array
    {
        app(SetSearchKeywords::class)->handle(new Request([]));
        $offered = app(Choices::class)->drain();
        app(Workspace::class)->rememberChoices($offered);

        return collect($offered)->firstWhere('field', 'google_search_keywords') ?? [];
    }

    /** @return list<string> each saved criterion as "text MATCH_TYPE" */
    private function saved(): array
    {
        return collect(app(SearchKeywordSelections::class)->criteria($this->campaign->fresh()))
            ->map(fn (array $k): string => $k['text'].' '.$k['match_type'].($k['negative'] ? ' NEGATIVE' : ''))
            ->sort()
            ->values()
            ->all();
    }

    /** The question says more than one may be chosen per keyword. */
    public function test_the_question_offers_the_match_types_as_several(): void
    {
        $offer = $this->ask();

        $this->assertTrue($offer['keyword_form']['several_match_types'] ?? false);
        $this->assertSame(['BROAD', 'PHRASE', 'EXACT'], $offer['keyword_form']['match_types']);
    }

    /** All three for one keyword, which is what Google accepts. */
    public function test_one_keyword_can_be_taken_at_all_three_match_types(): void
    {
        $this->ask();

        $this->assertTrue(app(Answers::class)->apply('google_search_keywords', [
            ['text' => 'rome city break', 'match_type' => 'BROAD'],
            ['text' => 'rome city break', 'match_type' => 'PHRASE'],
            ['text' => 'rome city break', 'match_type' => 'EXACT'],
        ]));

        $this->assertSame([
            'rome city break BROAD',
            'rome city break EXACT',
            'rome city break PHRASE',
        ], $this->saved());
    }

    /** Two of the three, which is the middle of what he asked for. */
    public function test_two_match_types_for_one_keyword(): void
    {
        $this->ask();

        $this->assertTrue(app(Answers::class)->apply('google_search_keywords', [
            ['text' => 'rome city break', 'match_type' => 'PHRASE'],
            ['text' => 'rome city break', 'match_type' => 'EXACT'],
        ]));

        $this->assertSame(['rome city break EXACT', 'rome city break PHRASE'], $this->saved());
    }

    /** Different keywords keep their own sets. */
    public function test_each_keyword_carries_its_own_set_of_match_types(): void
    {
        $this->ask();

        $this->assertTrue(app(Answers::class)->apply('google_search_keywords', [
            ['text' => 'rome city break', 'match_type' => 'BROAD'],
            ['text' => 'rome city break', 'match_type' => 'EXACT'],
            ['text' => 'milan weekend break', 'match_type' => 'PHRASE'],
        ]));

        $this->assertSame([
            'milan weekend break PHRASE',
            'rome city break BROAD',
            'rome city break EXACT',
        ], $this->saved());
    }

    /** The same criterion twice is still one keyword, not two. */
    public function test_the_same_text_and_match_type_twice_is_refused(): void
    {
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('duplicated');

        app(SearchKeywordSelections::class)->save($this->campaign, [
            ['text' => 'rome city break', 'match_type' => 'PHRASE', 'negative' => false],
            ['text' => 'rome city break', 'match_type' => 'PHRASE', 'negative' => false],
        ], (int) ($this->campaign->targetingSet()->value('revision') ?? 0));
    }

    /** Including and excluding the same word is still a contradiction. */
    public function test_the_same_text_included_and_excluded_is_refused(): void
    {
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('excluded');

        app(SearchKeywordSelections::class)->save($this->campaign, [
            ['text' => 'rome city break', 'match_type' => 'PHRASE', 'negative' => false],
            ['text' => 'rome city break', 'match_type' => 'EXACT', 'negative' => true],
        ], (int) ($this->campaign->targetingSet()->value('revision') ?? 0));
    }

    /** Negatives may still differ in match type among themselves. */
    public function test_a_negative_can_be_taken_at_two_match_types(): void
    {
        $this->ask();

        $this->assertTrue(app(Answers::class)->apply('google_search_keywords', [
            ['text' => 'rome city break', 'match_type' => 'PHRASE'],
            '-free, [-free]',
        ]));

        $saved = $this->saved();

        $this->assertContains('rome city break PHRASE', $saved);
        $this->assertContains('free BROAD NEGATIVE', $saved);
        $this->assertContains('free EXACT NEGATIVE', $saved);
    }

    /**
     * The twenty-term ceiling counts terms, not the criteria they produce.
     *
     * This file first asserted the opposite - that three match types for one
     * word counted as three against the ceiling, on the reasoning that a buyer
     * could otherwise quietly publish sixty keywords. Sixty is the point:
     * twenty themes at three match types each. Counting criteria capped a
     * campaign at six terms and was reported within the hour, "the draft
     * accepts at most 20 included keywords, so the 33 combinations weren't
     * saved". See TheKeywordCeilingCountsTermsNotMatchTypesTest.
     */
    public function test_the_ceiling_counts_terms_so_all_three_types_are_usable(): void
    {
        $criteria = [];

        for ($i = 0; $i < 11; $i++) {
            foreach (['BROAD', 'PHRASE', 'EXACT'] as $matchType) {
                $criteria[] = ['text' => 'keyword number '.$i, 'match_type' => $matchType, 'negative' => false];
            }
        }

        $this->assertCount(33, $criteria);

        app(SearchKeywordSelections::class)->save(
            $this->campaign,
            $criteria,
            (int) ($this->campaign->targetingSet()->value('revision') ?? 0),
        );

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