<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Targeting\LocationDiscovery;
use App\Campaigns\Targeting\PublishedLocationChangePlanner;
use App\Campaigns\Targeting\TargetingSelections;
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 Tests\TestCase;

class PublishedLocationPreviewToolTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(User $owner, ?PlatformLocation $selected = null): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $owner->getKey(),
            'name' => 'Published Meta campaign',
            'platform' => 'meta',
            'status' => 'draft',
            'ad_account_id' => 'act_111',
            'locations' => ['countries' => ['US']],
        ]);

        if ($selected !== null) {
            app(TargetingSelections::class)->addCampaignLocation($campaign, $selected);
        }

        $campaign->update(['status' => 'published', 'external_campaign_id' => '12345']);
        $workspace = app(Workspace::class);
        $workspace->bindTo('published-location-preview-chat');
        $workspace->focusOn($campaign);

        return $campaign->fresh();
    }

    private function city(): PlatformLocation
    {
        $location = Location::factory()->create([
            'type' => 'city', 'name' => 'Springfield', 'country_code' => 'US',
            'iso_code' => null, 'source' => 'meta', 'source_key' => '2440704',
        ]);

        return PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'meta',
            'external_id' => '2440704', 'provider_name' => 'Springfield, Illinois, US',
        ]);
    }

    private function tool(): mixed
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__preview_published_location_change');
        $this->assertNotNull($tool);

        return $tool;
    }

    public function test_a_live_location_change_is_named_as_an_edit_rather_than_this_preview(): void
    {
        $description = (string) $this->tool()->description();

        $this->assertStringContainsString('edit_entity', $description);
        $this->assertStringContainsString('already live', $description);
    }

    public function test_main_chat_search_and_exact_selection_only_preview_an_addition(): void
    {
        Http::fake();
        $owner = User::factory()->create();
        $this->actingAs($owner);
        $campaign = $this->campaign($owner);
        $city = $this->city();
        $candidate = [
            'platform' => 'meta', 'external_id' => '2440704', 'kind' => 'city',
            'name' => 'Springfield', 'label' => 'Springfield, Illinois, US',
            'country_code' => 'US', 'parent_external_id' => '3856',
        ];
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->with('meta', 'city', 'US', 'Springfield', 'act_111', 1)->andReturn([$candidate]);
        $discovery->shouldReceive('select')->once()->with('meta', 'city', 'US', 'Springfield', '2440704', 'act_111', 1)->andReturn($city);
        $this->app->instance(LocationDiscovery::class, $discovery);
        $planner = Mockery::mock(PublishedLocationChangePlanner::class);
        $planner->shouldReceive('preview')->once()->with(Mockery::type(Campaign::class), 'add', $city->getKey(), 0)
            ->andReturn(['before' => ['countries' => ['US']], 'after' => ['cities' => ['2440704']]]);
        $this->app->instance(PublishedLocationChangePlanner::class, $planner);
        $tool = $this->tool();

        $search = json_decode((string) $tool->handle(new ToolRequest([
            'operation' => 'add', 'country_code' => 'US', 'kind' => 'city', 'query' => 'Springfield',
        ])), true);

        $this->assertTrue($search['ok']);
        $this->assertSame('2440704', app(Choices::class)->all()[0]['options'][0]['value']);

        $preview = json_decode((string) $tool->handle(new ToolRequest([
            'operation' => 'add', 'country_code' => 'US', 'kind' => 'city',
            'query' => 'Springfield', 'external_id' => '2440704', 'expected_revision' => 0,
        ])), true);

        $this->assertTrue($preview['ok']);
        $this->assertFalse($preview['applied']);
        $this->assertSame(['cities' => ['2440704']], $preview['after']);
        $this->assertFalse($campaign->targetingSet()->exists());
        Http::assertNothingSent();
    }

    public function test_main_chat_lists_a_selected_place_and_previews_removal_without_deleting_it(): void
    {
        $owner = User::factory()->create();
        $this->actingAs($owner);
        $city = $this->city();
        $campaign = $this->campaign($owner, $city);
        $planner = Mockery::mock(PublishedLocationChangePlanner::class);
        $planner->shouldReceive('preview')->once()->with(Mockery::type(Campaign::class), 'remove', $city->getKey(), 1)
            ->andReturn(['before' => ['cities' => ['2440704']], 'after' => ['countries' => ['US']]]);
        $this->app->instance(PublishedLocationChangePlanner::class, $planner);
        $tool = $this->tool();

        $listing = json_decode((string) $tool->handle(new ToolRequest(['operation' => 'remove'])), true);
        $this->assertTrue($listing['ok']);
        $this->assertSame($city->getKey(), $listing['selected_places'][0]['mapping_id']);

        $preview = json_decode((string) $tool->handle(new ToolRequest([
            'operation' => 'remove', 'mapping_id' => $city->getKey(), 'expected_revision' => 1,
        ])), true);

        $this->assertTrue($preview['ok']);
        $this->assertFalse($preview['applied']);
        $this->assertSame(1, $campaign->targetingSet->locations()->where('kind', 'city')->count());
    }

    public function test_main_chat_previews_exact_replacement_without_changing_selection(): void
    {
        $owner = User::factory()->create();
        $this->actingAs($owner);
        $old = $this->city();
        $campaign = $this->campaign($owner, $old);
        $newLocation = Location::factory()->create([
            'type' => 'city', 'name' => 'Chicago', 'country_code' => 'US',
            'iso_code' => null, 'source' => 'meta', 'source_key' => '2420605',
        ]);
        $new = PlatformLocation::factory()->create([
            'location_id' => $newLocation->getKey(), 'platform' => 'meta',
            'external_id' => '2420605', 'provider_name' => 'Chicago, Illinois, US',
        ]);
        $candidate = [
            'platform' => 'meta', 'external_id' => '2420605', 'kind' => 'city',
            'name' => 'Chicago', 'label' => 'Chicago, Illinois, US',
            'country_code' => 'US', 'parent_external_id' => '3856',
        ];
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldReceive('search')->once()->with('meta', 'city', 'US', 'Chicago', 'act_111', 1)->andReturn([$candidate]);
        $discovery->shouldReceive('select')->once()->with('meta', 'city', 'US', 'Chicago', '2420605', 'act_111', 1)->andReturn($new);
        $this->app->instance(LocationDiscovery::class, $discovery);
        $planner = Mockery::mock(PublishedLocationChangePlanner::class);
        $planner->shouldReceive('preview')->once()
            ->with(Mockery::type(Campaign::class), 'replace', $new->getKey(), 1, $old->getKey())
            ->andReturn(['before' => ['cities' => ['2440704']], 'after' => ['cities' => ['2420605']]]);
        $this->app->instance(PublishedLocationChangePlanner::class, $planner);
        $tool = $this->tool();

        $listing = json_decode((string) $tool->handle(new ToolRequest(['operation' => 'replace'])), true);
        $this->assertSame($old->getKey(), $listing['selected_places'][0]['mapping_id']);

        $search = json_decode((string) $tool->handle(new ToolRequest([
            'operation' => 'replace', 'replace_mapping_id' => $old->getKey(),
            'kind' => 'city', 'query' => 'Chicago',
        ])), true);
        $this->assertTrue($search['ok']);
        $this->assertSame('2420605', $search['matches'][0]['external_id']);
        $this->assertSame($old->getKey(), $search['replace_mapping_id']);

        $preview = json_decode((string) $tool->handle(new ToolRequest([
            'operation' => 'replace', 'replace_mapping_id' => $old->getKey(),
            'kind' => 'city', 'query' => 'Chicago', 'external_id' => '2420605', 'expected_revision' => 1,
        ])), true);
        $this->assertTrue($preview['ok']);
        $this->assertFalse($preview['applied']);
        $this->assertSame(['cities' => ['2420605']], $preview['after']);
        $this->assertSame($old->getKey(), $campaign->fresh()->targetingSet->locations()->where('kind', 'city')->value('platform_location_id'));
    }

    public function test_main_chat_refuses_another_users_published_campaign_before_lookup(): void
    {
        $owner = User::factory()->create();
        $campaign = $this->campaign($owner);
        $this->actingAs(User::factory()->create());
        $discovery = Mockery::mock(LocationDiscovery::class);
        $discovery->shouldNotReceive('search');
        $this->app->instance(LocationDiscovery::class, $discovery);

        $result = json_decode((string) $this->tool()->handle(new ToolRequest([
            'operation' => 'add', 'country_code' => 'US', 'kind' => 'city', 'query' => 'Springfield',
        ])), true);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('signed-in user', $result['error']);
        $this->assertSame('published', $campaign->fresh()->status);
    }
}
