<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Platforms\GoogleRules;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

class SearchKeywordSelectionTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(string $type = 'search'): Campaign
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Keyword test',
            'platform' => 'google',
            'campaign_type' => $type,
            'status' => 'draft',
            'ad_account_id' => '1234567890',
            'locations' => ['countries' => ['US']],
        ]);
        app(Workspace::class)->bindTo('keyword-conversation');
        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    public function test_main_chat_saves_exact_keywords_and_rejects_a_stale_revision(): void
    {
        $campaign = $this->campaign();
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__set_search_keywords');

        $this->assertNotNull($tool);
        $review = json_decode((string) $tool->handle(new Request([])), true);
        $this->assertSame(0, $review['revision']);

        $keywords = [
            ['text' => 'seo services', 'match_type' => 'EXACT', 'negative' => false],
            ['text' => 'free seo', 'match_type' => 'PHRASE', 'negative' => true],
        ];
        $saved = json_decode((string) $tool->handle(new Request([
            'keywords' => $keywords, 'expected_revision' => 0,
        ])), true);

        $this->assertTrue($saved['ok']);
        $this->assertSame('EXACT', $saved['keywords'][0]['match_type']);
        $this->assertTrue($saved['keywords'][1]['negative']);
        $this->assertSame(['US'], app(TargetingSelections::class)->countries($campaign->fresh()));

        $stale = json_decode((string) $tool->handle(new Request([
            'keywords' => [['text' => 'other', 'match_type' => 'BROAD']],
            'expected_revision' => 0,
        ])), true);

        $this->assertFalse($stale['ok']);
        $this->assertSame($saved['keywords'], app(SearchKeywordSelections::class)->criteria($campaign->fresh()));
    }

    public function test_invalid_or_conflicting_keywords_do_not_change_targeting(): void
    {
        $campaign = $this->campaign();
        $selections = app(SearchKeywordSelections::class);

        foreach ([
            [['text' => 'free seo', 'match_type' => 'PHRASE', 'negative' => true]],
            [
                ['text' => 'seo services', 'match_type' => 'EXACT'],
                ['text' => 'SEO SERVICES', 'match_type' => 'PHRASE', 'negative' => true],
            ],
            [['text' => 'seo services', 'match_type' => 'FUZZY']],
        ] as $keywords) {
            try {
                $selections->save($campaign, $keywords, 0);
                $this->fail('Invalid keywords were saved.');
            } catch (\RuntimeException) {
                $this->assertNull($campaign->fresh()->targetingSet);
            }
        }
    }

    public function test_display_campaign_cannot_save_search_keywords(): void
    {
        $campaign = $this->campaign('display');
        $result = json_decode((string) collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__set_search_keywords')
            ->handle(new Request(['keywords' => [['text' => 'seo', 'match_type' => 'PHRASE']], 'expected_revision' => 0])), true);

        $this->assertFalse($result['ok']);
        $this->assertNull($campaign->fresh()->targetingSet);
    }

    public function test_switching_away_from_search_blocks_stale_keywords_until_they_are_cleared(): void
    {
        $campaign = $this->campaign();
        app(SearchKeywordSelections::class)->save($campaign, [
            ['text' => 'seo services', 'match_type' => 'EXACT'],
        ], 0);
        $campaign->update(['campaign_type' => 'display']);

        $problems = app(GoogleRules::class)->additionalProblems($campaign);
        $this->assertStringContainsString('saved Google Search keywords require a Search campaign', implode('; ', $problems));

        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__set_search_keywords');
        $cleared = json_decode((string) $tool->handle(new Request(['clear' => true, 'expected_revision' => 2])), true);

        $this->assertTrue($cleared['ok']);
        $this->assertFalse(app(SearchKeywordSelections::class)->hasExplicitSelection($campaign));
        $this->assertStringNotContainsString('saved Google Search keywords require a Search campaign',
            implode('; ', app(GoogleRules::class)->additionalProblems($campaign)));
    }
}
