<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Targeting\LocationDiscovery;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\AllowedAdAccount;
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\Http;
use Laravel\Ai\Tools\Request as ToolRequest;
use Mockery;
use RuntimeException;
use Tests\TestCase;

class LocationDiscoveryTest extends TestCase
{
    use RefreshDatabase;

    private function fakeMetaCities(): void
    {
        AllowedAdAccount::factory()->meta('act_123')->create();
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.version' => 'v25.0']);
        Http::preventStrayRequests();
        Http::fake([
            'https://graph.facebook.com/v25.0/search*' => Http::response(['data' => [
                ['key' => '111', 'name' => 'Springfield', 'type' => 'city', 'country_code' => 'US', 'region' => 'Illinois', 'region_id' => 101],
                ['key' => '222', 'name' => 'Springfield', 'type' => 'city', 'country_code' => 'US', 'region' => 'Missouri', 'region_id' => 102],
                ['key' => '333', 'name' => 'Springfield', 'type' => 'city', 'country_code' => 'CA'],
                ['key' => '444', 'name' => '', 'type' => 'city', 'country_code' => 'US'],
            ]]),
        ]);
    }

    public function test_search_keeps_ambiguous_cities_distinct_and_saves_only_the_reverified_choice(): void
    {
        $this->fakeMetaCities();
        $country = Location::create([
            'type' => 'country',
            'name' => 'United States',
            'country_code' => 'US',
            'iso_code' => 'US',
            'source' => 'iso_3166_1',
            'source_key' => 'US',
        ]);
        $discovery = app(LocationDiscovery::class);

        $matches = $discovery->search('meta', 'city', 'US', 'Springfield', 'act_123');

        $this->assertSame(['111', '222'], array_column($matches, 'external_id'));
        $this->assertSame(['Springfield, Illinois, US', 'Springfield, Missouri, US'], array_column($matches, 'label'));
        $this->assertDatabaseCount('platform_locations', 0);

        $selected = $discovery->select('meta', 'city', 'US', 'Springfield', '222', 'act_123');

        $this->assertSame('222', $selected->external_id);
        $this->assertSame('102', $selected->parent_external_id);
        $this->assertSame('Springfield', $selected->location->name);
        $this->assertSame($country->getKey(), $selected->location->parent_id);
        $this->assertDatabaseCount('platform_locations', 1);
        $this->assertDatabaseCount('locations', 2);
    }

    public function test_selecting_a_place_just_searched_does_not_call_the_provider_again(): void
    {
        $this->fakeMetaCities();
        Location::factory()->create(['iso_code' => 'US', 'country_code' => 'US', 'source_key' => 'US']);
        $discovery = app(LocationDiscovery::class);

        $discovery->search('meta', 'city', 'US', 'Springfield', 'act_123');
        $discovery->select('meta', 'city', 'US', 'Springfield', '222', 'act_123');

        Http::assertSentCount(1);
    }

    public function test_unknown_provider_id_is_not_saved(): void
    {
        $this->fakeMetaCities();

        $this->expectException(RuntimeException::class);
        try {
            app(LocationDiscovery::class)->select('meta', 'city', 'US', 'Springfield', 'not-a-result', 'act_123');
        } finally {
            $this->assertDatabaseCount('platform_locations', 0);
        }
    }

    public function test_a_provider_id_whose_parent_label_changed_cannot_refresh_an_old_mapping(): void
    {
        $this->fakeMetaCities();
        Location::factory()->create(['iso_code' => 'US', 'country_code' => 'US', 'source_key' => 'US']);
        $discovery = app(LocationDiscovery::class);
        $mapping = $discovery->select('meta', 'city', 'US', 'Springfield', '222', 'act_123');
        $mapping->update(['provider_name' => 'Springfield, Illinois, US', 'verified_at' => now()->subDays(1)]);
        $verifiedAt = $mapping->fresh()->verified_at;

        try {
            $discovery->select('meta', 'city', 'US', 'Springfield', '222', 'act_123');
            $this->fail('A changed parent label must not be treated as the previously verified place.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('changed its name or parent', $exception->getMessage());
            $this->assertSame('Springfield, Illinois, US', $mapping->fresh()->provider_name);
            $this->assertEquals($verifiedAt, $mapping->fresh()->verified_at);
            $this->assertDatabaseCount('platform_locations', 1);
        }
    }

    public function test_a_provider_id_whose_parent_id_changed_cannot_refresh_an_old_mapping(): void
    {
        $this->fakeMetaCities();
        Location::factory()->create(['iso_code' => 'US', 'country_code' => 'US', 'source_key' => 'US']);
        $discovery = app(LocationDiscovery::class);
        $mapping = $discovery->select('meta', 'city', 'US', 'Springfield', '222', 'act_123');
        $mapping->update(['parent_external_id' => 'old-region']);

        try {
            $discovery->select('meta', 'city', 'US', 'Springfield', '222', 'act_123');
            $this->fail('A changed parent ID must not refresh the old verified place.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('changed its name or parent', $exception->getMessage());
            $this->assertSame('old-region', $mapping->fresh()->parent_external_id);
        }
    }

    public function test_linkedin_city_search_remains_unavailable_until_types_are_verified(): void
    {
        Http::fake();

        $this->expectException(RuntimeException::class);
        try {
            app(LocationDiscovery::class)->search('linkedin', 'city', 'US', 'Springfield');
        } finally {
            Http::assertNothingSent();
        }
    }

    public function test_main_chat_explains_why_linkedin_city_selection_is_unavailable(): void
    {
        $user = User::factory()->create();
        $this->actingAs($user);
        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'LinkedIn location draft',
            'platform' => 'linkedin',
            'status' => 'draft',
            'ad_account_id' => '123',
            'locations' => ['countries' => ['US']],
        ]);
        app(Workspace::class)->bindTo('conv-linkedin-location');
        app(Workspace::class)->focusOn($campaign);
        Http::fake();

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

        $this->assertFalse($response['ok']);
        $this->assertStringContainsString('does not confirm place type and parent', $response['error']);
        Http::assertNothingSent();
    }

    public function test_main_chat_selects_and_removes_a_google_search_city_exclusion(): void
    {
        config(['services.google_ads.customer_id' => '1234567890', 'services.google_ads.refresh_token' => 'test-refresh-token']);
        $user = User::factory()->create();
        $this->actingAs($user);
        Location::factory()->create(['iso_code' => 'US', 'country_code' => 'US', 'source_key' => 'US']);
        $campaign = Campaign::create([
            'user_id' => $user->getKey(), 'name' => 'Search city exclusion',
            'platform' => 'google', 'campaign_type' => 'search', 'status' => 'draft',
            'ad_account_id' => '1234567890', 'locations' => ['countries' => ['US']],
        ]);
        $location = Location::factory()->create([
            'type' => 'city', 'name' => 'Chicago', 'country_code' => 'US',
            'iso_code' => null, 'source' => 'google', 'source_key' => 'geoTargetConstants/1023191',
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'google',
            'external_id' => 'geoTargetConstants/1023191', 'provider_name' => 'Chicago, Illinois, US',
        ]);
        $workspace = app(Workspace::class);
        $workspace->bindTo('google-exclusion-chat');
        $workspace->focusOn($campaign);
        $candidate = [
            'platform' => 'google', 'external_id' => 'geoTargetConstants/1023191',
            'kind' => 'city', 'name' => 'Chicago', 'label' => 'Chicago, Illinois, US',
            'country_code' => 'US', 'parent_external_id' => 'geoTargetConstants/21147',
        ];
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->andReturn([$candidate]);
        $discovery->shouldReceive('select')->once()->andReturn($mapping);
        $this->app->instance(LocationDiscovery::class, $discovery);
        $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([
            'operation' => 'exclude', 'country_code' => 'US', 'kind' => 'city', 'query' => 'Chicago',
        ])), true);
        $this->assertTrue($search['ok']);

        $selected = json_decode((string) $tool->handle(new ToolRequest([
            'operation' => 'exclude', 'country_code' => 'US', 'kind' => 'city', 'query' => 'Chicago',
            'external_id' => 'geoTargetConstants/1023191', 'expected_revision' => 0,
        ])), true);
        $this->assertTrue($selected['ok']);
        $this->assertSame(1, $selected['revision']);
        $this->assertSame('exclude', app(TargetingSelections::class)->reviewedCampaignPlaces($campaign)[0]['operation']);
        $this->assertSame(['US'], app(TargetingSelections::class)->googleGeoTargets($campaign)['countries']);

        $removed = json_decode((string) $tool->handle(new ToolRequest([
            'operation' => 'exclude', 'country_code' => 'US',
            'remove_external_id' => 'geoTargetConstants/1023191', 'expected_revision' => 1,
        ])), true);
        $this->assertTrue($removed['ok']);
        $this->assertSame([], app(TargetingSelections::class)->reviewedCampaignPlaces($campaign));
    }

    public function test_meta_search_can_reach_and_select_a_later_page(): void
    {
        AllowedAdAccount::factory()->meta('act_123')->create();
        config(['platforms.meta.token' => 'test-token', 'platforms.meta.version' => 'v25.0']);
        Location::factory()->create(['iso_code' => 'US', 'country_code' => 'US', 'source_key' => 'US']);

        Http::preventStrayRequests();
        Http::fake(function ($request) {
            parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query);

            return ($query['after'] ?? null) === 'page-two'
                ? Http::response(['data' => [
                    ['key' => 'later', 'name' => 'Springfield', 'type' => 'city', 'country_code' => 'US', 'region' => 'Oregon'],
                ]])
                : Http::response(['data' => [
                    ['key' => 'first', 'name' => 'Springfield', 'type' => 'city', 'country_code' => 'US', 'region' => 'Illinois'],
                ], 'paging' => ['cursors' => ['after' => 'page-two']]]);
        });

        $discovery = app(LocationDiscovery::class);
        $matches = $discovery->search('meta', 'city', 'US', 'Springfield', 'act_123', page: 2);

        $this->assertSame(['later'], array_column($matches, 'external_id'));
        $this->assertSame('later', $discovery->select('meta', 'city', 'US', 'Springfield', 'later', 'act_123', page: 2)->external_id);
    }
}
