<?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 Tests\TestCase;

/**
 * "AI suggestion for keywords can be added only in phrase match, need option
 * to add as broad and exact."
 *
 * The suggestions are generated as phrase matches and were offered with that
 * one match type on them, so the only route to broad or exact was to retype
 * the same term into the Other box in Google's shorthand - a strange thing to
 * ask of someone looking at the term on screen.
 *
 * The question now carries the match types it can be taken in, and a row
 * sends the type the buyer set on it. Sent as the type itself rather than as
 * Google's [brackets], because an unmarked term already means something here -
 * the match type the suggestion was offered with - and one payload cannot mean
 * that and broad both. Typed terms keep the shorthand, which is what the box's
 * own hint promises and where that parsing already lives.
 */
class AKeywordCanBeTakenAsBroadOrExactTest 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' => '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('keyword-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 array<string,string> keyword text to its saved match type */
    private function saved(): array
    {
        return collect(app(SearchKeywordSelections::class)->criteria($this->campaign->fresh()))
            ->mapWithKeys(fn (array $k): array => [$k['text'] => $k['match_type'].($k['negative'] ? ' NEGATIVE' : '')])
            ->all();
    }

    /** The question has to say which match types are on offer. */
    public function test_the_question_carries_the_match_types(): void
    {
        $offer = $this->ask();

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

    /** What the screen offers and what the save accepts are one list. */
    public function test_every_offered_match_type_is_one_the_save_accepts(): void
    {
        // Asked again each time round: a save moves the revision, and a click
        // made against the one before it is meant to be refused.
        foreach ($this->ask()['keyword_form']['match_types'] as $type) {
            $this->ask();

            $this->assertTrue(app(Answers::class)->apply('google_search_keywords', [
                ['text' => 'rome city break', 'match_type' => $type],
            ]), $type.' was offered but refused on save');

            $this->assertSame($type, $this->saved()['rome city break'] ?? null);
        }
    }

    /** A suggestion taken as exact, which is the reported case. */
    public function test_a_suggestion_can_be_taken_as_exact(): void
    {
        $this->ask();

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

    /** And as broad, which the suggestions never were. */
    public function test_a_suggestion_can_be_taken_as_broad(): void
    {
        $this->ask();

        $this->assertTrue(app(Answers::class)->apply('google_search_keywords', [
            ['text' => 'rome city break', 'match_type' => 'BROAD'],
        ]));
        $this->assertSame('BROAD', $this->saved()['rome city break'] ?? null);
    }

    /** Different match types in one click, because a buyer sets them per row. */
    public function test_each_keyword_keeps_its_own_match_type(): void
    {
        $this->ask();

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

        $saved = $this->saved();

        $this->assertSame('EXACT', $saved['rome city break'] ?? null);
        $this->assertSame('PHRASE', $saved['milan weekend break'] ?? null);
        $this->assertSame('BROAD', $saved['cheap flights to italy'] ?? null);
    }

    /**
     * An unmarked suggestion still arrives as the one it was offered with.
     *
     * The old payload - the bare option value - has to keep meaning what it
     * meant, because a click from a page loaded before this change sends it.
     */
    public function test_the_previous_payload_still_means_phrase(): void
    {
        $offer = $this->ask();

        $this->assertSame('PHRASE', $offer['options'][0]['arguments']['match_type'] ?? null);

        $this->assertTrue(app(Answers::class)->apply(
            'google_search_keywords',
            [$offer['options'][0]['value']],
        ));
        $this->assertSame('PHRASE', $this->saved()[$offer['options'][0]['value']] ?? null);
    }

    /** The markers are what the buyer set, not part of the keyword. */
    public function test_the_markers_are_not_saved_as_text(): void
    {
        $this->ask();

        app(Answers::class)->apply('google_search_keywords', ['[rome city break]']);

        $saved = $this->saved();

        $this->assertArrayNotHasKey('[rome city break]', $saved);
        $this->assertArrayHasKey('rome city break', $saved);
    }

    /** Negatives still come from the typed box, which is where they are explained. */
    public function test_negatives_still_arrive_from_the_typed_box(): void
    {
        $this->ask();

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

        $saved = $this->saved();

        $this->assertSame('EXACT', $saved['rome city break'] ?? null);
        $this->assertSame('BROAD NEGATIVE', $saved['free'] ?? null);
        $this->assertSame('BROAD NEGATIVE', $saved['cheap'] ?? null);
    }
}
