<?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\LaunchFlow;
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;

/**
 * "I gave my own custom keywords but still it is asking for keyword."
 *
 * Every question in the flow applies server-side on click, through the field
 * map in Answers. google_search_keywords was the one that did not: 54 fields
 * were mapped and this was not one of them, so a click only sent prose and the
 * answer depended on the model calling set_search_keywords itself, with a
 * complete set of structured criteria and the right revision. When it did not,
 * nothing was saved, hasExplicitSelection() stayed false, and LaunchFlow asked
 * the same question again.
 *
 * The usable Other box made that worse rather than better: the buyer could now
 * type several keywords in Google's shorthand and watch the step ignore them.
 */
class AKeywordClickLandsWithoutTheModelTest 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' => 'Keyword click',
            '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-click');
        app(Workspace::class)->focusOn($this->campaign);
        app(TargetingSelections::class)->chooseWholeCountries($this->campaign);
        $this->campaign = $this->campaign->fresh();
    }

    /** Offer the question and persist it, which is what ends a turn. */
    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') ?? [];
    }

    private function stepIsDone(): bool
    {
        return (bool) (collect(app(LaunchFlow::class)->progress($this->campaign->fresh()))
            ->firstWhere('key', 'search_keywords')['done'] ?? false);
    }

    public function test_the_field_is_wired_into_the_answer_map(): void
    {
        // The whole defect in one assertion.
        $this->assertTrue(app(Answers::class)->handles('google_search_keywords'));
    }

    public function test_the_question_carries_what_a_click_needs(): void
    {
        $offer = $this->ask();

        $this->assertNotSame([], $offer);

        foreach ($offer['options'] as $option) {
            // The revision the question was asked at, and the match type the
            // suggestion was offered with. Without both, a click cannot be
            // applied without asking the model to reconstruct them.
            $this->assertNotNull($option['revision']);
            $this->assertNotNull($option['arguments']['match_type'] ?? null);
        }
    }

    public function test_a_click_saves_the_keywords_and_completes_the_step(): void
    {
        $offer = $this->ask();
        $suggested = array_column($offer['options'], 'value');

        $this->assertFalse($this->stepIsDone());

        // Two suggestions ticked, and the buyer's own terms typed into Other in
        // the shorthand the box tells them to use.
        $landed = app(Answers::class)->apply('google_search_keywords', [
            ...$suggested,
            '[milan flights], "weekend in rome", -free',
        ]);

        $this->assertTrue($landed, 'the click did not reach set_search_keywords');
        $this->assertTrue($this->stepIsDone(), 'the step still asks for keywords');
        $this->assertTrue(app(SearchKeywordSelections::class)->hasExplicitSelection($this->campaign->fresh()));

        $saved = collect(app(SearchKeywordSelections::class)->criteria($this->campaign->fresh()))
            ->mapWithKeys(fn (array $k): array => [$k['text'] => $k['match_type'].($k['negative'] ? ' NEGATIVE' : '')])
            ->all();

        // A suggestion keeps the match type it was offered with; typed markers
        // are read by unmark(), which is where that parsing already lives.
        $this->assertSame('PHRASE', $saved['rome city break'] ?? null);
        $this->assertSame('EXACT', $saved['milan flights'] ?? null);
        $this->assertSame('PHRASE', $saved['weekend in rome'] ?? null);
        $this->assertSame('BROAD NEGATIVE', $saved['free'] ?? null);

        // The markers are not part of the keyword.
        $this->assertArrayNotHasKey('[milan flights]', $saved);
        $this->assertArrayNotHasKey('-free', $saved);
    }

    /** Typing alone is an answer; nothing has to be ticked. */
    public function test_typed_keywords_on_their_own_complete_the_step(): void
    {
        $this->ask();

        $this->assertTrue(app(Answers::class)->apply(
            'google_search_keywords',
            ['cheap flights to italy, "rome city break"'],
        ));
        $this->assertTrue($this->stepIsDone());
        $this->assertCount(2, app(SearchKeywordSelections::class)->criteria($this->campaign->fresh()));
    }

    /**
     * A click made against a selection that has since moved is refused.
     *
     * That is what the revision on the option is for. Applying it anyway would
     * overwrite whatever was chosen in between with what the buyer was looking
     * at before it changed.
     */
    public function test_a_stale_click_is_refused_rather_than_overwriting(): void
    {
        $offer = $this->ask();

        $keywords = app(SearchKeywordSelections::class);
        $keywords->save($this->campaign->fresh(), [
            ['text' => 'chosen in between', 'match_type' => 'PHRASE', 'negative' => false],
        ], (int) ($this->campaign->fresh()->targetingSet()->value('revision') ?? 0));

        $before = $keywords->criteria($this->campaign->fresh());

        $this->assertFalse(app(Answers::class)->apply(
            'google_search_keywords',
            array_column($offer['options'], 'value'),
        ));
        $this->assertSame($before, $keywords->criteria($this->campaign->fresh()));
    }

    /** Nothing picked is not an answer. */
    public function test_an_empty_click_changes_nothing(): void
    {
        $this->ask();

        $this->assertFalse(app(Answers::class)->apply('google_search_keywords', []));
        $this->assertFalse($this->stepIsDone());
    }
}
