<?php

namespace Tests\Feature;

use App\Campaigns\LaunchFlow;
use App\Campaigns\PublishGate;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/**
 * A Google Search campaign asks for its keywords.
 *
 * The publish gate has always refused a Search campaign with no keyword - "a
 * Google Search campaign needs at least one selected keyword or a landing-page
 * keyword" - but nothing ever asked for one. set_search_keywords was
 * registered, named in no step and in no instruction, and the standing rule
 * said "never ask the user for keywords". So a buyer answered every question
 * the chat had, pressed publish, and met a refusal with no step to go back to.
 *
 * The seeding is unchanged: terms still come from the landing page and the
 * model still invents none. What changed is that the buyer now sees them, with
 * match types and exclusions, which is what SERP-1834 asks for and what
 * set_search_keywords was built to do - "Review or replace ... show current
 * terms and landing-page suggestions".
 *
 * Search only. Display and Performance Max have no keyword list, and Meta and
 * LinkedIn have no business seeing the step at all.
 */
class AGoogleSearchCampaignIsAskedForKeywordsTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

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

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

    private function campaign(string $platform, ?string $type, array $attributes = []): Campaign
    {
        return Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Probe',
            'platform' => $platform,
            'status' => 'draft',
            'campaign_type' => $type,
            'landing_url' => 'https://example.com/offer',
            'objective' => $platform === 'google' ? 'LEADS' : 'OUTCOME_LEADS',
            'locations' => ['countries' => ['US']],
            'budget' => 50,
            'budget_mode' => 'daily',
            'audience' => ['devices' => ['mobile']],
            'placements' => [$platform === 'google' ? 'search' : 'facebook'],
            ...$attributes,
        ]);
    }

    /** @return list<string> */
    private function steps(Campaign $campaign): array
    {
        $keys = [];

        foreach (app(LaunchFlow::class)->progress($campaign->fresh()) as $step) {
            if (is_array($step) && isset($step['key'])) {
                $keys[] = $step['key'];
            }
        }

        return $keys;
    }

    // ------------------------------------------------------------ it is asked

    public function test_a_google_search_campaign_is_asked_for_keywords(): void
    {
        $this->assertContains('search_keywords', $this->steps($this->campaign('google', 'search')));
    }

    /**
     * Before budget and creative, with the other targeting questions.
     *
     * Keywords are who the campaign reaches, so they belong where the rest of
     * the targeting is decided - not bolted on after the money and the copy.
     */
    public function test_it_is_asked_with_the_other_targeting_questions(): void
    {
        $steps = $this->steps($this->campaign('google', 'search'));

        $this->assertLessThan(
            array_search('budget', $steps, true),
            array_search('search_keywords', $steps, true),
            'keywords are asked after the budget',
        );
        $this->assertGreaterThan(
            array_search('countries', $steps, true),
            array_search('search_keywords', $steps, true),
            'keywords are asked before the countries they run in',
        );
    }

    /** The step names the tool, which is how the model is told to call it. */
    public function test_the_step_names_the_tool_that_answers_it(): void
    {
        $step = collect(app(LaunchFlow::class)->steps($this->campaign('google', 'search')))
            ->firstWhere('key', 'search_keywords');

        $this->assertNotNull($step);
        $this->assertSame('set_search_keywords', $step['tool']);
    }

    // ------------------------------------------------------- and only there

    public function test_performance_max_is_not_asked(): void
    {
        $this->assertNotContains('search_keywords', $this->steps($this->campaign('google', 'performance_max')));
    }

    public function test_display_is_not_asked(): void
    {
        $this->assertNotContains('search_keywords', $this->steps($this->campaign('google', 'display')));
    }

    public function test_meta_is_not_asked(): void
    {
        $this->assertNotContains('search_keywords', $this->steps($this->campaign('meta', null)));
    }

    /** A campaign with no type stated is a Search campaign, which is the Google default. */
    public function test_a_google_campaign_with_no_type_is_treated_as_search(): void
    {
        $this->assertContains('search_keywords', $this->steps($this->campaign('google', null)));
    }

    // ------------------------------------------------- it does not self-answer

    /**
     * The gate accepts a landing-page keyword, so criteria() can be non-empty
     * before anybody has been asked anything. If the step completed on that, it
     * would tick itself and the buyer would never see the terms their money is
     * spent on - which is the bug, not the fix.
     */
    public function test_landing_page_keywords_alone_do_not_complete_the_step(): void
    {
        $campaign = $this->campaignWithPageKeywords();

        // The distinction this test exists for: the page gave terms, so the
        // gate would pass, but nobody has been asked.
        $this->assertNotSame([], app(SearchKeywordSelections::class)->criteria($campaign->fresh()),
            'the fixture produced no landing-page keywords, so this proves nothing');
        $this->assertFalse(app(SearchKeywordSelections::class)->hasExplicitSelection($campaign->fresh()));

        $step = collect(app(LaunchFlow::class)->progress($campaign->fresh()))
            ->firstWhere('key', 'search_keywords');

        $this->assertNotNull($step, 'the step disappeared once the page supplied keywords');
        $this->assertFalse((bool) ($step['done'] ?? false), 'landing-page keywords ticked the step on the buyer\'s behalf');
    }

    /** A Search campaign whose brief already carries keywords read off the page. */
    private function campaignWithPageKeywords(): Campaign
    {
        $brief = Brief::create([
            'user_id' => $this->user->id,
            'landing_url' => 'https://example.com/offer',
            'page_analysis' => [
                'url' => 'https://example.com/offer',
                'title' => 'Car insurance quotes',
                'keywords' => ['car insurance quotes', 'cheap car cover'],
            ],
        ]);

        $campaign = $this->campaign('google', 'search');
        $campaign->forceFill(['brief_id' => $brief->id])->save();

        return $campaign->fresh();
    }

    /** And once the buyer has settled on a set, the step is done. */
    public function test_an_explicit_selection_completes_the_step(): void
    {
        $campaign = $this->campaign('google', 'search');

        // Through the real save path: a fresh campaign has no targeting set at
        // all, so writing the option straight onto it writes onto nothing.
        app(SearchKeywordSelections::class)->save($campaign, [
            ['text' => 'car insurance quotes', 'match_type' => 'PHRASE', 'negative' => false],
        ], 0);
        $campaign->unsetRelation('targetingSet');

        $done = collect(app(LaunchFlow::class)->progress($campaign->fresh()))
            ->firstWhere('key', 'search_keywords');

        $this->assertTrue((bool) ($done['done'] ?? false), 'the step did not complete on an explicit selection');
    }

    // ------------------------------------------------------------- the gate

    /** The refusal this step exists to prevent the buyer ever reaching. */
    public function test_the_publish_gate_still_refuses_a_search_campaign_with_no_keyword(): void
    {
        config([
            'platforms.guardrails.allowed_ad_accounts' => ['*'],
            'services.google_ads.refresh_token' => 'test',
            'services.google_ads.customer_id' => '3460855874',
        ]);

        $campaign = $this->campaign('google', 'search', [
            'ad_account_id' => '3460855874',
            'bid_strategy' => 'MAXIMIZE_CONVERSIONS',
        ]);

        $this->assertTrue(
            collect(app(PublishGate::class)->check($campaign->fresh()))
                ->contains(fn (string $reason): bool => str_contains($reason, 'keyword')),
            'the gate no longer refuses a Search campaign with no keyword',
        );
    }
}
