<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Targeting\GoogleKeywordIdeas;
use App\Campaigns\Targeting\LocationDiscovery;
use App\Models\AllowedAdAccount;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Models\Location;
use App\Models\User;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use InvalidArgumentException;
use Laravel\Ai\Tools\Request as ToolRequest;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

class GoogleLocationSearchTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    public function test_keyword_ideas_use_campaign_account_and_verified_country_instead_of_global_defaults(): void
    {
        $this->configuredConnection();
        $this->seedVerifiedCountries();
        $user = User::factory()->create();
        $brief = Brief::create([
            'user_id' => $user->getKey(), 'conversation_id' => 'keyword-ideas',
            'landing_url' => 'https://example.com/',
            'page_analysis' => [
                'url' => 'https://example.com/', 'title' => 'Example', 'description' => 'Example',
                'headings' => ['Example'], 'text' => 'Example', 'keywords' => ['seo service'],
            ],
        ]);
        $campaign = Campaign::create([
            'user_id' => $user->getKey(), 'brief_id' => $brief->getKey(),
            'name' => 'Research', 'platform' => 'google', 'campaign_type' => 'search',
            'status' => 'draft', 'ad_account_id' => '1234567890',
            'locations' => ['countries' => ['US']],
        ]);

        Http::preventStrayRequests();
        Http::fake([
            'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'token']),
            'https://googleads.googleapis.com/*:generateKeywordIdeas' => Http::response([
                'results' => [['text' => 'seo agency', 'keywordIdeaMetrics' => ['avgMonthlySearches' => '100', 'competition' => 'MEDIUM']]],
            ]),
        ]);

        $us = app(GoogleKeywordIdeas::class)->forCampaign($campaign);
        $this->assertSame(['geoTargetConstants/2840'], $us['geo_targets']);
        $this->assertSame('seo agency', $us['ideas'][0]['text']);

        $campaign->update(['locations' => ['countries' => ['GB']]]);
        $gb = app(GoogleKeywordIdeas::class)->forCampaign($campaign->fresh());
        $this->assertSame(['geoTargetConstants/2826'], $gb['geo_targets']);

        $requests = Http::recorded(fn (Request $request): bool => str_contains($request->url(), ':generateKeywordIdeas'))->values();
        $this->assertCount(2, $requests);
        $this->assertSame(['geoTargetConstants/2840'], $requests[0][0]->data()['geoTargetConstants']);
        $this->assertSame(['geoTargetConstants/2826'], $requests[1][0]->data()['geoTargetConstants']);

        // An account nobody permitted is still refused before any research is
        // sent, but by the allow list rather than by a comparison against the
        // configured customer. That comparison pre-dated the chat asking which
        // child of the manager to use: once it asks, refusing every answer but
        // the default contradicts the question, which is the same defect the
        // publisher and the entity tools had. What may be touched is the allow
        // list's decision, and it still makes it.
        $campaign->update(['ad_account_id' => '9999999999']);
        try {
            app(GoogleKeywordIdeas::class)->forCampaign($campaign->fresh());
            $this->fail('Research ran against an account nobody permitted.');
        } catch (\RuntimeException $exception) {
            $this->assertStringContainsString('9999999999 is not on the allowed list', $exception->getMessage());
            $this->assertCount(2, Http::recorded(fn (Request $request): bool => str_contains($request->url(), ':generateKeywordIdeas')));
        }
    }

    private function configuredConnection(): GoogleAdsConnection
    {
        AllowedAdAccount::factory()->google('1234567890')->create();
        config([
            'services.google_ads.refresh_token' => 'test-refresh-token',
            'services.google_ads.customer_id' => '1234567890',
            'services.google_ads.oauth_client_id' => 'test-client',
            'services.google_ads.oauth_client_secret' => 'test-secret',
            'services.google_ads.developer_token' => 'test-developer-token',
        ]);

        return GoogleAdsConnection::shared();
    }

    public function test_city_search_keeps_ambiguous_locations_distinct_and_filters_unsupported_results(): void
    {
        $connection = $this->configuredConnection();
        Http::preventStrayRequests();
        Http::fake([
            'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'test-access-token']),
            'https://googleads.googleapis.com/*' => Http::response([['results' => [
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/1', 'name' => 'Springfield', 'canonicalName' => 'Springfield, Illinois, United States', 'countryCode' => 'US', 'targetType' => 'City', 'status' => 'ENABLED']],
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/2', 'name' => 'Springfield', 'canonicalName' => 'Springfield, Missouri, United States', 'countryCode' => 'US', 'targetType' => 'City', 'status' => 'ENABLED']],
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/3', 'name' => 'Springfield', 'countryCode' => 'CA', 'targetType' => 'City', 'status' => 'ENABLED']],
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/4', 'name' => 'Springfield', 'countryCode' => 'US', 'targetType' => 'City', 'status' => 'REMOVAL_PLANNED']],
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/5', 'name' => 'Springfield', 'countryCode' => 'US', 'targetType' => 'City', 'status' => 'ENABLED']],
            ]]]),
        ]);

        $results = app(GoogleAdsService::class)->geoTargetCandidates($connection, 'city', 'US', 'Springfield');

        $this->assertSame(['geoTargetConstants/1', 'geoTargetConstants/2'], array_column($results, 'id'));
        $this->assertSame(['Springfield, Illinois, United States', 'Springfield, Missouri, United States'], array_column($results, 'label'));
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), 'googleAds:searchStream')
            && str_contains((string) ($request->data()['query'] ?? ''), "geo_target_constant.country_code = 'US'")
            && str_contains((string) ($request->data()['query'] ?? ''), "geo_target_constant.name LIKE '%Springfield%'")
            && str_contains((string) ($request->data()['query'] ?? ''), "geo_target_constant.target_type IN ('City')"));
    }

    public function test_google_catalog_import_queries_all_enabled_dma_markets_in_a_country(): void
    {
        $connection = $this->configuredConnection();
        Http::preventStrayRequests();
        Http::fake([
            'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'test-access-token']),
            'https://googleads.googleapis.com/*' => Http::response([['results' => [
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/200501', 'name' => 'New York',
                    'canonicalName' => 'New York DMA, United States', 'countryCode' => 'US',
                    'targetType' => 'DMA Region', 'status' => 'ENABLED', 'parentGeoTarget' => 'geoTargetConstants/2840']],
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/200502', 'name' => 'Old Market',
                    'canonicalName' => 'Old Market, United States', 'countryCode' => 'US',
                    'targetType' => 'DMA Region', 'status' => 'REMOVAL_PLANNED', 'parentGeoTarget' => 'geoTargetConstants/2840']],
            ]]]),
        ]);

        $results = app(GoogleAdsService::class)->geoTargetCatalog($connection, 'dma', 'US', '1234567890');

        $this->assertSame(['geoTargetConstants/200501'], array_column($results, 'external_id'));
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), 'googleAds:searchStream')
            && str_contains((string) ($request->data()['query'] ?? ''), "geo_target_constant.target_type IN ('DMA Region')")
            && ! str_contains((string) ($request->data()['query'] ?? ''), 'geo_target_constant.name LIKE'));
    }

    public function test_invalid_search_is_rejected_before_a_provider_call(): void
    {
        $connection = $this->configuredConnection();
        Http::fake();

        $this->expectException(InvalidArgumentException::class);
        try {
            app(GoogleAdsService::class)->geoTargetCandidates($connection, 'city', 'US', "Austin' OR status='ENABLED");
        } finally {
            Http::assertNothingSent();
        }
    }

    public function test_city_search_can_be_narrowed_by_state_and_selected_by_exact_id(): void
    {
        $this->configuredConnection();
        Location::factory()->create(['iso_code' => 'US', 'country_code' => 'US', 'source_key' => 'US']);
        Http::preventStrayRequests();
        Http::fake([
            'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'test-access-token']),
            'https://googleads.googleapis.com/*' => Http::response([['results' => [
                ['geoTargetConstant' => [
                    'resourceName' => 'geoTargetConstants/123',
                    'name' => 'Springfield',
                    'canonicalName' => 'Springfield, Illinois, United States',
                    'countryCode' => 'US',
                    'targetType' => 'City',
                    'status' => 'ENABLED',
                    'parentGeoTarget' => 'geoTargetConstants/21137',
                ]],
            ]]]),
        ]);

        $discovery = app(LocationDiscovery::class);
        $matches = $discovery->search('google', 'city', 'US', 'Springfield, Illinois', '1234567890');

        $this->assertSame(['geoTargetConstants/123'], array_column($matches, 'external_id'));
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), 'googleAds:searchStream')
            && str_contains((string) ($request->data()['query'] ?? ''), "geo_target_constant.name LIKE '%Springfield%'")
            && str_contains((string) ($request->data()['query'] ?? ''), "geo_target_constant.canonical_name LIKE '%Illinois%'"));

        $selected = $discovery->select('google', 'city', 'US', 'Springfield, Illinois', 'geoTargetConstants/123', '1234567890');

        $this->assertSame('geoTargetConstants/123', $selected->external_id);
        $this->assertSame('geoTargetConstants/21137', $selected->parent_external_id);
        $this->assertSame('google', $selected->platform);
    }

    public function test_google_chat_offers_ambiguous_places_and_saves_the_chosen_one(): void
    {
        $this->configuredConnection();
        Location::factory()->create(['iso_code' => 'US', 'country_code' => 'US', 'source_key' => 'US']);
        $user = User::factory()->create();
        $this->actingAs($user);
        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Google local',
            'platform' => 'google',
            'status' => 'draft',
            'ad_account_id' => '1234567890',
            'locations' => ['countries' => ['US']],
        ]);
        app(Workspace::class)->bindTo('conv-google-local');
        app(Workspace::class)->focusOn($campaign);

        Http::preventStrayRequests();
        Http::fake([
            'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'test-access-token']),
            'https://googleads.googleapis.com/*' => Http::response([['results' => [
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/111', 'name' => 'Springfield', 'canonicalName' => 'Springfield, Illinois, United States', 'countryCode' => 'US', 'targetType' => 'City', 'status' => 'ENABLED']],
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/222', 'name' => 'Springfield', 'canonicalName' => 'Springfield, Missouri, United States', 'countryCode' => 'US', 'targetType' => 'City', 'status' => 'ENABLED']],
            ]]]),
        ]);

        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($candidate): bool => $candidate->name() === 'campaign__choose_location');
        $this->assertNotNull($tool);
        $search = json_decode((string) $tool->handle(new ToolRequest(['country_code' => 'US', 'kind' => 'city', 'query' => 'Springfield'])), true);

        $this->assertTrue($search['ok']);
        $this->assertSame('google_location', app(Choices::class)->all()[0]['field']);
        $this->assertSame(['Springfield, Illinois, United States', 'Springfield, Missouri, United States'], array_column(app(Choices::class)->all()[0]['options'], 'label'));

        $selected = json_decode((string) $tool->handle(new ToolRequest([
            'country_code' => 'US', 'kind' => 'city', 'query' => 'Springfield',
            'external_id' => 'geoTargetConstants/222', 'expected_revision' => $search['revision'],
        ])), true);

        $this->assertTrue($selected['ok']);
        $this->assertSame('geoTargetConstants/222', $campaign->fresh()->targetingSet->locations()->where('kind', 'city')->first()->platformLocation->external_id);
    }

    public function test_google_search_selects_only_an_exact_verified_us_dma_in_main_chat(): void
    {
        $this->configuredConnection();
        Location::factory()->create(['iso_code' => 'US', 'country_code' => 'US', 'source_key' => 'US']);
        $user = User::factory()->create();
        $this->actingAs($user);
        $campaign = Campaign::create([
            'user_id' => $user->getKey(), 'name' => 'Market research', 'platform' => 'google',
            'status' => 'draft', 'ad_account_id' => '1234567890', 'locations' => ['countries' => ['US']],
        ]);
        app(Workspace::class)->bindTo('conv-google-dma');
        app(Workspace::class)->focusOn($campaign);

        Http::preventStrayRequests();
        Http::fake([
            'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'test-access-token']),
            'https://googleads.googleapis.com/*' => Http::response([['results' => [
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/200501', 'name' => 'New York', 'canonicalName' => 'New York, United States', 'countryCode' => 'US', 'targetType' => 'DMA Region', 'status' => 'ENABLED', 'parentGeoTarget' => 'geoTargetConstants/2840']],
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/501', 'name' => 'New York', 'canonicalName' => 'New York, United States', 'countryCode' => 'US', 'targetType' => 'City', 'status' => 'ENABLED', 'parentGeoTarget' => 'geoTargetConstants/2840']],
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/200502', 'name' => 'New York', 'canonicalName' => 'New York, United States', 'countryCode' => 'US', 'targetType' => 'DMA Region', 'status' => 'REMOVAL_PLANNED', 'parentGeoTarget' => 'geoTargetConstants/2840']],
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/200503', 'name' => 'New York', 'canonicalName' => 'New York, United States', 'countryCode' => 'CA', 'targetType' => 'DMA Region', 'status' => 'ENABLED', 'parentGeoTarget' => 'geoTargetConstants/2124']],
                ['geoTargetConstant' => ['resourceName' => 'geoTargetConstants/200504', 'name' => 'New York', 'canonicalName' => 'New York, United States', 'countryCode' => 'US', 'targetType' => 'DMA Region', 'status' => 'ENABLED']],
            ]]]),
        ]);

        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($candidate): bool => $candidate->name() === 'campaign__choose_location');
        $result = json_decode((string) $tool->handle(new ToolRequest(['country_code' => 'US', 'kind' => 'dma', 'query' => 'New York'])), true);

        $this->assertTrue($result['ok']);
        $this->assertSame(1, $result['matches']);
        $this->assertSame('geoTargetConstants/200501', app(Choices::class)->all()[0]['options'][0]['value']);
        $this->assertNull($campaign->fresh()->targetingSet);
        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), 'googleAds:searchStream')
            && str_contains((string) ($request->data()['query'] ?? ''), "geo_target_constant.target_type IN ('DMA Region')"));

        $selection = json_decode((string) $tool->handle(new ToolRequest([
            'country_code' => 'US', 'kind' => 'dma', 'query' => 'New York',
            'external_id' => 'geoTargetConstants/200501', 'expected_revision' => $result['revision'],
        ])), true);
        $this->assertTrue($selection['ok']);
        $saved = $campaign->fresh()->targetingSet->locations()->where('kind', 'dma')->first();
        $this->assertSame('geoTargetConstants/200501', $saved->platformLocation->external_id);
        $this->assertSame('geoTargetConstants/2840', $saved->platformLocation->parent_external_id);
        $this->assertSame('US', $saved->country_code);

        $wrongOperation = json_decode((string) $tool->handle(new ToolRequest([
            'country_code' => 'US', 'kind' => 'dma', 'operation' => 'exclude', 'query' => 'New York',
        ])), true);
        $this->assertFalse($wrongOperation['ok']);
    }

    public function test_dma_lookup_rejects_non_us_country_before_provider_call(): void
    {
        $connection = $this->configuredConnection();
        Http::fake();

        $this->expectException(InvalidArgumentException::class);
        try {
            app(GoogleAdsService::class)->geoTargetCandidates($connection, 'dma', 'CA', 'Toronto');
        } finally {
            Http::assertNothingSent();
        }
    }

    /**
     * A search with no account behind it is refused before any provider call.
     *
     * This used to assert that any customer other than the configured one was
     * refused, which is the assumption that stopped every campaign on every
     * other account from narrowing its targeting: a geoTargetConstant is not
     * account-scoped, and which of the manager's children the campaign runs on
     * is now a question the flow asks. See
     * LocationsReadTheCampaignsAccountNotTheConfiguredOneTest.
     *
     * What is kept is the half that is still true. A refusal must not cost an
     * API call, and an account nobody has verified is still a refusal.
     */
    public function test_google_location_discovery_refuses_an_unverified_account_before_provider_call(): void
    {
        $this->configuredConnection();
        Http::fake();

        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('Verify the Google Ads account');
        try {
            app(LocationDiscovery::class)->search('google', 'dma', 'US', 'New York', null);
        } finally {
            Http::assertNothingSent();
        }
    }

    public function test_google_search_radius_requires_confirmed_coordinates_and_supports_review_and_removal(): void
    {
        $this->configuredConnection();
        Location::factory()->create(['iso_code' => 'US', 'country_code' => 'US', 'source_key' => 'US']);
        $user = User::factory()->create();
        $this->actingAs($user);
        $campaign = Campaign::create([
            'user_id' => $user->getKey(), 'name' => 'Radius research', 'platform' => 'google',
            'status' => 'draft', 'ad_account_id' => '1234567890', 'locations' => ['countries' => ['US']],
        ]);
        app(Workspace::class)->bindTo('conv-google-radius');
        app(Workspace::class)->focusOn($campaign);
        Http::fake();

        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($candidate): bool => $candidate->name() === 'campaign__choose_location');
        $listed = json_decode((string) $tool->handle(new ToolRequest(['country_code' => 'US', 'kind' => 'radius'])), true);
        $this->assertSame(0, $listed['revision']);

        $radius = [
            'country_code' => 'US', 'kind' => 'radius', 'latitude' => 40.712776,
            'longitude' => -74.005974, 'radius' => 10, 'radius_unit' => 'mi',
            'expected_revision' => 0,
        ];
        $unconfirmed = json_decode((string) $tool->handle(new ToolRequest($radius)), true);
        $this->assertTrue($unconfirmed['ok']);
        $this->assertTrue($unconfirmed['needs_confirmation']);
        $this->assertNull($campaign->fresh()->targetingSet);

        $early = json_decode((string) $tool->handle(new ToolRequest([...$radius, 'confirmed_center' => true])), true);
        $this->assertFalse($early['ok']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->all());

        $changed = json_decode((string) $tool->handle(new ToolRequest([...$radius, 'radius' => 12, 'confirmed_center' => true])), true);
        $this->assertFalse($changed['ok']);

        $saved = json_decode((string) $tool->handle(new ToolRequest([...$radius, 'confirmed_center' => true])), true);
        $this->assertTrue($saved['ok'], (string) ($saved['error'] ?? ''));
        $this->assertSame(1, $saved['revision']);
        $this->assertSame('Radius 10.00 mi around 40.712776, -74.005974 (US)', $saved['selected'][0]['label']);
        $this->assertSame(1, $campaign->fresh()->targetingSet->locations()->where('kind', 'radius')->count());

        $removed = json_decode((string) $tool->handle(new ToolRequest([
            'country_code' => 'US', 'kind' => 'radius',
            'remove_selection_id' => $saved['selected'][0]['selection_id'], 'expected_revision' => 1,
        ])), true);
        $this->assertTrue($removed['ok']);
        $this->assertSame(0, $campaign->fresh()->targetingSet->locations()->where('kind', 'radius')->count());
        Http::assertNothingSent();
    }

    public function test_google_search_presence_requires_an_offered_choice_and_revision(): void
    {
        $this->configuredConnection();
        Location::factory()->create(['iso_code' => 'US', 'country_code' => 'US', 'source_key' => 'US']);
        $user = User::factory()->create();
        $this->actingAs($user);
        $campaign = Campaign::create([
            'user_id' => $user->getKey(), 'name' => 'Presence research', 'platform' => 'google',
            'status' => 'draft', 'ad_account_id' => '1234567890', 'locations' => ['countries' => ['US']],
        ]);
        app(Workspace::class)->bindTo('conv-google-presence');
        app(Workspace::class)->focusOn($campaign);
        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($candidate): bool => $candidate->name() === 'campaign__choose_location');

        $unoffered = json_decode((string) $tool->handle(new ToolRequest([
            'country_code' => 'US', 'kind' => 'presence', 'presence_mode' => 'PRESENCE_OR_INTEREST', 'expected_revision' => 0,
        ])), true);
        $this->assertFalse($unoffered['ok']);

        $offer = json_decode((string) $tool->handle(new ToolRequest(['country_code' => 'US', 'kind' => 'presence'])), true);
        $this->assertTrue($offer['ok']);
        $this->assertSame('PRESENCE', $offer['current']);
        $this->assertSame(['PRESENCE', 'PRESENCE_OR_INTEREST'], array_column(app(Choices::class)->all()[0]['options'], 'value'));
        app(Workspace::class)->rememberChoices(app(Choices::class)->all());

        $saved = json_decode((string) $tool->handle(new ToolRequest([
            'country_code' => 'US', 'kind' => 'presence', 'presence_mode' => 'PRESENCE_OR_INTEREST', 'expected_revision' => $offer['revision'],
        ])), true);
        $this->assertTrue($saved['ok'], (string) ($saved['error'] ?? ''));
        $this->assertSame('PRESENCE_OR_INTEREST', $campaign->fresh()->targetingSet->options['google_presence']);
    }
}
