<?php

namespace Tests\Feature;

use App\Agent\Answers;
use App\Agent\Choices;
use App\Agent\MarketingAgent;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\LaunchFlow;
use App\Campaigns\Targeting\LocationCatalog;
use App\Campaigns\Targeting\LocationDiscovery;
use App\Campaigns\Targeting\TargetingSelections;
use App\Http\Controllers\ChatController;
use App\Models\Campaign;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Ai\Tools\Request;
use Mockery;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

class CityStateChatFlowTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    private function campaign(string $platform = 'meta'): Campaign
    {
        $user = User::factory()->create();
        $this->actingAs($user);
        if (! Location::query()->where('type', 'country')->exists()) {
            $this->seedVerifiedCountries();
        }

        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Location draft',
            'platform' => $platform,
            'status' => 'draft',
            'ad_account_id' => $platform === 'meta' ? 'act_123' : '1234567890',
            'locations' => ['countries' => ['US']],
            'placements' => $platform === 'meta' ? ['facebook'] : [],
        ]);

        $workspace = app(Workspace::class);
        $workspace->bindTo('city-state-chat');
        $workspace->focusOn($campaign);

        return $campaign;
    }

    private function chooseLocation(array $arguments = []): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__choose_location');

        return json_decode((string) $tool->handle(new Request($arguments)), true);
    }

    public function test_meta_chat_offers_city_and_state_after_country_targeting(): void
    {
        $campaign = $this->campaign();
        $step = collect(app(LaunchFlow::class)->progress($campaign))->firstWhere('key', 'location_scope');

        $this->assertFalse($step['done']);
        $this->assertSame('choose_location', collect(app(LaunchFlow::class)->steps($campaign))->firstWhere('key', 'location_scope')['tool']);
        $this->assertTrue($this->chooseLocation()['ok']);
        $this->assertSame(['whole', 'city', 'region', 'dma', 'postal', 'list'], array_column(app(Choices::class)->all()[0]['options'], 'value'));
    }

    public function test_main_chat_controller_puts_the_city_and_state_choices_on_screen(): void
    {
        $campaign = $this->campaign();
        $campaign->update([
            'landing_url' => 'https://example.com',
            'budget' => 20,
            'budget_mode' => 'daily',
            'objective' => 'OUTCOME_TRAFFIC',
            'special_ad_categories' => ['NONE'],
            'page_id' => 'page-1',
            'audience' => ['devices' => ['mobile']],
            'bid_strategy' => 'LOWEST_COST_WITHOUT_CAP',
        ]);

        $this->assertSame('location_scope', app(LaunchFlow::class)->next($campaign->fresh())['key']);

        $controller = app(ChatController::class);
        (new \ReflectionMethod($controller, 'offerNextStep'))->invoke($controller);

        $choice = app(Choices::class)->all()[0];
        $this->assertSame('location_scope', $choice['field']);
        $this->assertSame(['whole', 'city', 'region', 'dma', 'postal', 'list'], array_column($choice['options'], 'value'));
    }

    public function test_a_later_page_offer_cannot_replace_meta_placements(): void
    {
        $campaign = $this->campaign();
        $campaign->update([
            'landing_url' => 'https://example.com',
            'objective' => 'OUTCOME_TRAFFIC',
            'special_ad_categories' => ['NONE'],
            'placements' => [],
        ]);

        app(Choices::class)->offer('page_id', 'Which Page?', [['value' => 'page-1', 'label' => 'Page']]);

        $controller = app(ChatController::class);
        (new \ReflectionMethod($controller, 'offerNextStep'))->invoke($controller);

        $this->assertSame(['placements'], array_column(app(Choices::class)->all(), 'field'));
    }

    public function test_a_later_country_offer_cannot_replace_instagram_identity(): void
    {
        $campaign = $this->campaign();
        $campaign->update([
            'landing_url' => 'https://example.com',
            'objective' => 'OUTCOME_TRAFFIC',
            'special_ad_categories' => ['NONE'],
            'page_id' => 'page-1',
            'placements' => ['instagram'],
            'audience' => ['devices' => ['mobile']],
        ]);

        app(Choices::class)->offer(
            'instagram_account_id', 'Which Instagram account?', [['value' => 'ig-1', 'label' => '@brand']],
        );

        $controller = app(ChatController::class);
        (new \ReflectionMethod($controller, 'offerNextStep'))->invoke($controller);

        $this->assertSame(['instagram_account_id'], array_column(app(Choices::class)->all(), 'field'));
    }

    public function test_an_explicit_budget_request_keeps_its_card_when_placements_are_next(): void
    {
        $campaign = $this->campaign();
        $campaign->update([
            'landing_url' => 'https://example.com',
            'objective' => 'OUTCOME_TRAFFIC',
            'special_ad_categories' => ['NONE'],
            'placements' => [],
        ]);
        app(Choices::class)->offer(
            'budget_amount', 'How much?', [['value' => '20', 'label' => '$20 per day']],
        );

        $controller = app(ChatController::class);
        (new \ReflectionMethod($controller, 'offerNextStep'))->invoke($controller, 'Set the budget to twenty dollars.');

        $this->assertSame(['budget_amount'], array_column(app(Choices::class)->all(), 'field'));
    }

    public function test_whole_country_choice_requires_an_offer_and_survives_a_country_change(): void
    {
        $campaign = $this->campaign();

        $this->assertFalse($this->chooseLocation(['scope' => 'whole', 'expected_revision' => 0])['ok']);
        $this->chooseLocation();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $this->assertTrue(app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'whole']])[0]['applied']);
        $this->assertTrue(collect(app(LaunchFlow::class)->progress($campaign->fresh()))->firstWhere('key', 'location_scope')['done']);
        $this->assertFalse($this->chooseLocation(['scope' => 'whole', 'expected_revision' => 0])['ok']);

        app(TargetingSelections::class)->saveCampaignCountries($campaign->fresh(), ['US'], 1);
        $this->assertTrue(collect(app(LaunchFlow::class)->progress($campaign->fresh()))->firstWhere('key', 'location_scope')['done']);

        app(TargetingSelections::class)->saveCampaignCountries($campaign->fresh(), ['US', 'GB'], 1);
        $saved = $campaign->fresh();
        $this->assertTrue(collect(app(LaunchFlow::class)->progress($saved))->firstWhere('key', 'location_scope')['done']);
        $this->assertSame('whole', $saved->targetingSet->options['geography_scope']);
    }

    public function test_choosing_a_country_defaults_whole_country_but_still_offers_scope(): void
    {
        $campaign = $this->campaign();

        app(TargetingSelections::class)->saveCampaignCountries($campaign->fresh(), ['GB']);

        $this->assertTrue(app(TargetingSelections::class)->hasChosenGeographyScope($campaign->fresh()));
        $this->assertTrue($this->chooseLocation()['ok']);
        $this->assertSame('location_scope', app(Choices::class)->all()[0]['field']);
        $this->assertFalse(collect(app(LaunchFlow::class)->progress($campaign->fresh()))
            ->firstWhere('key', 'location_scope')['done']);
    }

    public function test_specific_places_are_still_offered_when_requested(): void
    {
        $campaign = $this->campaign();
        app(TargetingSelections::class)->saveCampaignCountries($campaign->fresh(), ['GB']);

        $this->assertTrue($this->chooseLocation(['change_scope' => true])['ok']);

        $this->assertSame('location_scope', app(Choices::class)->all()[0]['field']);
    }

    public function test_a_verified_city_settles_the_step_without_a_whole_country_choice(): void
    {
        $campaign = $this->campaign();
        $city = Location::factory()->create(['type' => 'city', 'name' => 'Chicago', 'country_code' => 'US', 'iso_code' => null]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $city->getKey(), 'platform' => 'meta', 'provider_name' => 'Chicago, Illinois, US',
        ]);

        app(TargetingSelections::class)->addCampaignLocation($campaign, $mapping);

        $this->assertTrue(collect(app(LaunchFlow::class)->progress($campaign->fresh()))->firstWhere('key', 'location_scope')['done']);
    }

    public function test_choosing_whole_country_replaces_a_selected_city_and_does_not_repeat_the_question(): void
    {
        $campaign = $this->campaign();
        $city = Location::factory()->create(['type' => 'city', 'name' => 'New York', 'country_code' => 'US', 'iso_code' => null]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $city->getKey(), 'platform' => 'meta', 'external_id' => '2490299',
            'provider_name' => 'New York, New York, US',
        ]);
        app(TargetingSelections::class)->addCampaignLocation($campaign, $mapping);

        $this->assertTrue($this->chooseLocation()['ok']);
        $this->assertSame([], app(Choices::class)->all());

        $this->assertTrue($this->chooseLocation(['change_scope' => true])['ok']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $this->assertTrue(app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'whole']])[0]['applied']);

        $saved = $campaign->fresh();
        $this->assertSame([], app(TargetingSelections::class)->reviewedCampaignPlaces($saved));
        $this->assertSame('whole', $saved->targetingSet->options['geography_scope']);
        $this->assertTrue(app(TargetingSelections::class)->hasChosenGeographyScope($saved));

        app(Choices::class)->drain();
        $this->assertTrue($this->chooseLocation()['ok']);
        $this->assertSame([], app(Choices::class)->all());

        $this->assertTrue($this->chooseLocation(['change_scope' => true])['ok']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $this->assertTrue(app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'city']])[0]['applied']);
        $this->assertSame('override', $campaign->fresh()->targetingSet->options['place_intent_mode']);
        $this->assertSame('location_search', app(Choices::class)->all()[0]['field']);
    }

    public function test_google_and_linkedin_offer_only_their_supported_location_choices(): void
    {
        $google = $this->campaign('google');
        $this->assertContains('location_scope', array_column(app(LaunchFlow::class)->progress($google), 'key'));
        $this->assertTrue($this->chooseLocation()['ok']);
        $this->assertSame(['whole', 'city', 'region', 'dma', 'postal', 'list'], array_column(app(Choices::class)->all()[0]['options'], 'value'));

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $dma = app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'dma']]);
        $this->assertTrue($dma[0]['applied']);
        $this->assertSame('dma', app(Choices::class)->all()[0]['search']['kind']);
        $this->assertSame(['US'], app(Choices::class)->all()[0]['search']['countries']);

        $linkedin = $this->campaign('linkedin');
        $this->assertContains('location_scope', array_column(app(LaunchFlow::class)->progress($linkedin), 'key'));
        app(Choices::class)->drain();
        $this->assertTrue($this->chooseLocation()['ok']);
        $this->assertSame(['whole', 'dma'], array_column(app(Choices::class)->all()[0]['options'], 'value'));

        $linkedin->update(['locations' => ['countries' => ['DE']]]);
        $this->assertNotContains('location_scope', array_column(app(LaunchFlow::class)->progress($linkedin->fresh()), 'key'));
    }

    public function test_dma_choice_requires_us_and_a_supported_google_campaign_type(): void
    {
        $meta = $this->campaign();
        $this->chooseLocation();
        $this->assertContains('dma', array_column(app(Choices::class)->all()[0]['options'], 'value'));

        app(Choices::class)->drain();
        $google = $this->campaign('google');
        $google->update(['campaign_type' => 'display']);
        $this->chooseLocation();
        $this->assertNotContains('dma', array_column(app(Choices::class)->all()[0]['options'], 'value'));

        app(Choices::class)->drain();
        $google->update(['campaign_type' => 'search', 'locations' => ['countries' => ['GB']]]);
        $this->chooseLocation();
        $this->assertNotContains('dma', array_column(app(Choices::class)->all()[0]['options'], 'value'));
    }

    public function test_city_choice_opens_search_and_result_click_saves_the_exact_place(): void
    {
        $campaign = $this->campaign();
        $this->chooseLocation();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $scope = app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'city']]);

        $this->assertTrue($scope[0]['applied']);
        $searchChoice = app(Choices::class)->all()[0];
        $this->assertSame('location_search', $searchChoice['field']);
        $this->assertSame('city', $searchChoice['search']['kind']);
        $this->assertSame(['US'], $searchChoice['search']['countries']);
        $this->chooseLocation();
        $this->assertSame('location_search', app(Choices::class)->all()[0]['field']);
        $this->assertCount(1, app(Choices::class)->all());

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $city = Location::factory()->create(['type' => 'city', 'name' => 'Chicago', 'country_code' => 'US', 'iso_code' => null]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $city->getKey(), 'platform' => 'meta', 'external_id' => '123',
            'provider_name' => 'Chicago, Illinois, US',
        ]);
        $match = [
            'platform' => 'meta', 'external_id' => '123', 'kind' => 'city', 'name' => 'Chicago',
            'label' => 'Chicago, Illinois, US', 'country_code' => 'US', 'parent_external_id' => '101',
        ];
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->andReturn([$match]);
        $discovery->shouldReceive('select')->once()->andReturn($mapping);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $searched = app(Answers::class)->applyAll([['field' => 'location_search', 'value' => [
            'kind' => 'city', 'country_code' => 'US', 'query' => 'Chicago',
        ]]]);

        $this->assertTrue($searched[0]['applied']);
        $results = app(Choices::class)->all()[0];
        $this->assertSame('meta_location', $results['field']);
        $this->assertSame('Chicago, Illinois, US', $results['options'][0]['label']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $forged = app(Answers::class)->applyAll([['field' => 'meta_location', 'value' => 'not-offered']]);
        $this->assertFalse($forged[0]['applied']);
        $this->assertNull($campaign->fresh()->targetingSet);

        $selected = app(Answers::class)->applyAll([['field' => 'meta_location', 'value' => $results['options'][0]['value']]]);

        $this->assertTrue($selected[0]['applied']);
        $this->assertTrue(app(TargetingSelections::class)->hasChosenGeographyScope($campaign->fresh()));
    }

    /** @return array{0: PlatformLocation, 1: array<string, string|null>} */
    private function newYork(): array
    {
        $city = Location::factory()->create(['type' => 'city', 'name' => 'New York', 'country_code' => 'US', 'iso_code' => null]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $city->getKey(), 'platform' => 'meta', 'external_id' => '2490299',
            'provider_name' => 'New York, New York, US',
        ]);

        return [$mapping, [
            'platform' => 'meta', 'external_id' => '2490299', 'kind' => 'city', 'name' => 'New York',
            'label' => 'New York, New York, US', 'country_code' => 'US', 'parent_external_id' => '3875',
        ]];
    }

    public function test_exact_place_results_replace_the_scope_question_in_the_same_turn(): void
    {
        $this->campaign();
        [, $match] = $this->newYork();
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->andReturn([$match]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->chooseLocation();
        $this->chooseLocation(['country_code' => 'US', 'kind' => 'city', 'query' => 'New York']);

        $this->assertSame(['meta_location'], array_column(app(Choices::class)->all(), 'field'));
    }

    public function test_a_chosen_place_wins_over_whole_country_submitted_with_it(): void
    {
        $campaign = $this->campaign();
        [$mapping, $match] = $this->newYork();
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->andReturn([$match]);
        $discovery->shouldReceive('select')->once()->andReturn($mapping);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->chooseLocation();
        $scope = app(Choices::class)->drain();
        $this->chooseLocation(['country_code' => 'US', 'kind' => 'city', 'query' => 'New York']);
        $places = app(Choices::class)->drain();
        app(Workspace::class)->rememberChoices([...$scope, ...$places]);

        $applied = app(Answers::class)->applyAll([
            ['field' => 'location_scope', 'value' => 'whole'],
            ['field' => 'meta_location', 'value' => $places[0]['options'][0]['value']],
        ]);

        $this->assertSame([true, true], array_column($applied, 'applied'));
        $this->assertCount(1, app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh()));
    }

    public function test_state_choice_opens_region_search(): void
    {
        $this->campaign();
        $this->chooseLocation();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $scope = app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'region']]);

        $this->assertTrue($scope[0]['applied']);
        $this->assertSame('region', app(Choices::class)->all()[0]['search']['kind']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->with('meta', 'region', 'US', 'Illinois', 'act_123', 1)
            ->andReturn([[
                'platform' => 'meta', 'external_id' => '101', 'kind' => 'region', 'name' => 'Illinois',
                'label' => 'Illinois, US', 'country_code' => 'US', 'parent_external_id' => null,
            ]]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $searched = app(Answers::class)->applyAll([['field' => 'location_search', 'value' => [
            'kind' => 'region', 'country_code' => 'US', 'query' => 'Illinois',
        ]]]);

        $this->assertTrue($searched[0]['applied']);
        $this->assertSame('Illinois, US', app(Choices::class)->all()[0]['options'][0]['label']);
        $this->assertSame('Illinois, US', app(LocationCatalog::class)->choices('meta', 'region', 'US')[0]['label']);
    }

    public function test_database_city_checkboxes_save_multiple_exact_provider_cities(): void
    {
        $campaign = $this->campaign();
        $newYork = Location::factory()->create(['type' => 'city', 'name' => 'New York', 'country_code' => 'US', 'iso_code' => null]);
        $chicago = Location::factory()->create(['type' => 'city', 'name' => 'Chicago', 'country_code' => 'US', 'iso_code' => null]);
        $mappings = [
            'New York' => PlatformLocation::factory()->create(['location_id' => $newYork->id, 'platform' => 'meta', 'external_id' => '2490299', 'provider_name' => 'New York, New York, US']),
            'Chicago' => PlatformLocation::factory()->create(['location_id' => $chicago->id, 'platform' => 'meta', 'external_id' => '2420605', 'provider_name' => 'Chicago, Illinois, US']),
        ];
        PlatformLocation::factory()->create(['location_id' => $chicago->id, 'platform' => 'google', 'provider_name' => 'Chicago, Illinois, US']);
        $toronto = Location::factory()->create(['type' => 'city', 'name' => 'Toronto', 'country_code' => 'CA', 'iso_code' => null]);
        PlatformLocation::factory()->create(['location_id' => $toronto->id, 'platform' => 'meta', 'provider_name' => 'Toronto, Ontario, CA']);
        $this->chooseLocation();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'city']]);
        $searchChoice = app(Choices::class)->all()[0];

        $this->assertSame([
            ['id' => (string) $mappings['Chicago']->id, 'label' => 'Chicago, Illinois, US'],
            ['id' => (string) $mappings['New York']->id, 'label' => 'New York, New York, US'],
        ], $searchChoice['search']['catalog_places']['US']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $discovery = Mockery::mock(LocationDiscovery::class);
        foreach ($mappings as $name => $mapping) {
            $discovery->shouldReceive('select')->once()->with('meta', 'city', 'US', $name, $mapping->external_id, 'act_123')
                ->andReturn($mapping);
        }
        $this->app->instance(LocationDiscovery::class, $discovery);

        $applied = app(Answers::class)->applyAll([['field' => 'location_search', 'value' => [
            'kind' => 'city', 'country_code' => 'US', 'catalog_places' => [(string) $mappings['New York']->id, (string) $mappings['Chicago']->id],
        ]]]);

        $this->assertTrue($applied[0]['applied']);
        $this->assertCount(2, app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh()));
        $this->assertTrue(app(TargetingSelections::class)->hasChosenGeographyScope($campaign->fresh()));
    }

    public function test_database_region_checkbox_saves_a_verified_state(): void
    {
        $campaign = $this->campaign();
        $region = Location::factory()->create(['type' => 'region', 'name' => 'Illinois', 'country_code' => 'US', 'iso_code' => null]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $region->id, 'platform' => 'meta', 'external_id' => '101', 'provider_name' => 'Illinois, US',
        ]);
        $this->chooseLocation();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'region']]);

        $this->assertSame([['id' => (string) $mapping->id, 'label' => 'Illinois, US']],
            app(Choices::class)->all()[0]['search']['catalog_places']['US']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('select')->once()->with('meta', 'region', 'US', 'Illinois', '101', 'act_123')
            ->andReturn($mapping);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $result = $this->chooseLocation(['country_code' => 'US', 'kind' => 'region', 'catalog_places' => [(string) $mapping->id]]);

        $this->assertTrue($result['ok']);
        $this->assertSame('region', app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh())[0]['kind']);
    }

    private function savedIllinois(): Campaign
    {
        $campaign = $this->campaign();
        $region = Location::factory()->create(['type' => 'region', 'name' => 'Illinois', 'country_code' => 'US', 'iso_code' => null]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $region->id, 'platform' => 'meta', 'external_id' => '101', 'provider_name' => 'Illinois, US',
        ]);
        app(TargetingSelections::class)->addCampaignLocation($campaign, $mapping);

        return $campaign;
    }

    public function test_listing_saved_places_does_not_ask_which_to_remove(): void
    {
        $this->savedIllinois();

        $result = $this->chooseLocation(['country_code' => 'US', 'kind' => 'region']);

        $this->assertTrue($result['ok']);
        $this->assertSame([], app(Choices::class)->all());
    }

    public function test_removal_is_offered_when_the_user_asks_to_remove_a_place(): void
    {
        $this->savedIllinois();

        $this->chooseLocation(['country_code' => 'US', 'kind' => 'region', 'offer_removal' => true]);

        $this->assertSame('meta_location_include_removal', app(Choices::class)->all()[0]['field']);
    }

    public function test_searching_a_place_that_is_already_selected_does_not_offer_it_again(): void
    {
        $this->savedIllinois();
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->andReturn([[
            'platform' => 'meta', 'external_id' => '101', 'kind' => 'region', 'name' => 'Illinois',
            'label' => 'Illinois, US', 'country_code' => 'US', 'parent_external_id' => null,
        ]]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $result = $this->chooseLocation(['country_code' => 'US', 'kind' => 'region', 'query' => 'Illinois']);

        $this->assertTrue($result['ok']);
        $this->assertSame(['Illinois, US'], $result['already_selected']);
        $this->assertSame([], app(Choices::class)->all());
    }

    public function test_database_dma_checkbox_saves_a_verified_market(): void
    {
        $campaign = $this->campaign();
        $market = Location::factory()->create(['type' => 'dma', 'name' => 'New York', 'country_code' => 'US', 'iso_code' => null]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $market->id, 'platform' => 'meta', 'external_id' => 'COMSCORE_MARKET:501', 'provider_name' => 'New York, US',
        ]);
        $this->chooseLocation();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'dma']]);

        $this->assertSame([['id' => (string) $mapping->id, 'label' => 'New York, US']],
            app(Choices::class)->all()[0]['search']['catalog_places']['US']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('select')->once()->with('meta', 'dma', 'US', 'New York', 'COMSCORE_MARKET:501', 'act_123')
            ->andReturn($mapping);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $result = $this->chooseLocation(['country_code' => 'US', 'kind' => 'dma', 'catalog_places' => [(string) $mapping->id]]);

        $this->assertTrue($result['ok']);
        $this->assertSame('dma', app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh())[0]['kind']);
    }

    public function test_database_place_selection_rejects_an_unknown_id(): void
    {
        $campaign = $this->campaign();
        $city = Location::factory()->create(['type' => 'city', 'name' => 'Chicago', 'country_code' => 'US', 'iso_code' => null]);
        PlatformLocation::factory()->create(['location_id' => $city->id, 'platform' => 'meta', 'provider_name' => 'Chicago, Illinois, US']);
        $this->chooseLocation();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'city']]);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $result = $this->chooseLocation(['country_code' => 'US', 'kind' => 'city', 'catalog_places' => ['999999']]);

        $this->assertFalse($result['ok']);
        $this->assertSame([], app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh()));
    }

    public function test_typeahead_result_can_be_selected_after_the_original_choices_were_offered(): void
    {
        $campaign = $this->campaign();
        $this->chooseLocation();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'city']]);
        $this->assertSame([], app(Choices::class)->all()[0]['search']['catalog_places']['US']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $city = Location::factory()->create(['type' => 'city', 'name' => 'Denver', 'country_code' => 'US', 'iso_code' => null]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $city->id, 'platform' => 'meta', 'external_id' => '2431267',
            'provider_name' => 'Denver, Colorado, US',
        ]);
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('select')->once()->with('meta', 'city', 'US', 'Denver', '2431267', 'act_123')
            ->andReturn($mapping);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $result = $this->chooseLocation(['country_code' => 'US', 'kind' => 'city', 'catalog_places' => [(string) $mapping->id]]);

        $this->assertTrue($result['ok']);
        $this->assertCount(1, app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh()));
    }

    public function test_database_place_selection_rejects_a_stale_list(): void
    {
        $campaign = $this->campaign();
        $city = Location::factory()->create(['type' => 'city', 'name' => 'New York', 'country_code' => 'US', 'iso_code' => null]);
        $mapping = PlatformLocation::factory()->create(['location_id' => $city->id, 'platform' => 'meta', 'provider_name' => 'New York, New York, US']);
        $this->chooseLocation();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'city']]);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        app(TargetingSelections::class)->chooseWholeCountries($campaign);
        $result = $this->chooseLocation(['country_code' => 'US', 'kind' => 'city', 'catalog_places' => [(string) $mapping->id]]);

        $this->assertFalse($result['ok']);
        $this->assertSame([], app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh()));
    }

    public function test_database_place_selection_rechecks_the_provider_before_saving(): void
    {
        $campaign = $this->campaign();
        $city = Location::factory()->create(['type' => 'city', 'name' => 'New York', 'country_code' => 'US', 'iso_code' => null]);
        $mapping = PlatformLocation::factory()->create(['location_id' => $city->id, 'platform' => 'meta', 'provider_name' => 'New York, New York, US']);
        $this->chooseLocation();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        app(Answers::class)->applyAll([['field' => 'location_scope', 'value' => 'city']]);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('select')->once()->with('meta', 'city', 'US', 'New York', $mapping->external_id, 'act_123')
            ->andThrow(new \RuntimeException('The chosen location is no longer available.'));
        $this->app->instance(LocationDiscovery::class, $discovery);

        $result = $this->chooseLocation(['country_code' => 'US', 'kind' => 'city', 'catalog_places' => [(string) $mapping->id]]);

        $this->assertFalse($result['ok']);
        $this->assertSame([], app(TargetingSelections::class)->reviewedCampaignPlaces($campaign->fresh()));
    }

    public function test_main_chat_send_returns_search_then_exact_place_choices(): void
    {
        $campaign = $this->campaign();
        DB::table('agent_conversations')->insert([
            'id' => 'city-state-chat',
            'participant_type' => auth()->user()->getMorphClass(),
            'participant_id' => auth()->id(),
            'title' => 'Location search',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        MarketingAgent::fake(['Choose a place.', 'Select an exact match.']);
        $this->chooseLocation();
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $this->postJson(route('chat.send'), [
            'conversation' => 'city-state-chat',
            'message' => 'Search for cities.',
            'answers' => [['field' => 'location_scope', 'value' => 'city']],
        ])->assertOk()->assertJsonPath('choices.0.field', 'location_search');

        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->andReturn([[
            'platform' => 'meta', 'external_id' => '123', 'kind' => 'city', 'name' => 'Chicago',
            'label' => 'Chicago, Illinois, US', 'country_code' => 'US', 'parent_external_id' => '101',
        ]]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $this->postJson(route('chat.send'), [
            'conversation' => 'city-state-chat',
            'message' => 'Search for Chicago.',
            'answers' => [['field' => 'location_search', 'value' => [
                'kind' => 'city', 'country_code' => 'US', 'query' => 'Chicago',
            ]]],
        ])->assertOk()->assertJsonPath('choices.0.field', 'meta_location')
            ->assertJsonPath('choices.0.options.0.label', 'Chicago, Illinois, US');

        $this->assertFalse(app(TargetingSelections::class)->hasChosenGeographyScope($campaign->fresh()));
    }

    public function test_no_place_matches_keeps_the_search_field_available(): void
    {
        $this->campaign();
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->andReturn([]);
        $this->app->instance(LocationDiscovery::class, $discovery);

        $result = $this->chooseLocation(['kind' => 'region', 'country_code' => 'US', 'query' => 'No Match']);

        $this->assertFalse($result['ok']);
        $this->assertSame('location_search', app(Choices::class)->all()[0]['field']);
    }
}
