<?php

namespace Tests\Feature;

use App\Agent\ToolRegistry;
use App\Agent\Tools\Campaign\ApplyPublishedLocationChange;
use App\Agent\Workspace;
use App\Campaigns\Targeting\PublishedLocationChangePlanner;
use App\Campaigns\Targeting\PublishedLocationEditor;
use App\Models\Campaign;
use App\Models\Decision;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Tools\Request;
use Mockery;
use Tests\TestCase;

class PublishedLocationApplyToolTest extends TestCase
{
    use RefreshDatabase;

    public function test_disabled_guards_block_direct_call_without_consuming_approval(): void
    {
        config(['platforms.guardrails.published_location_edits_enabled' => false,
            'platforms.guardrails.google_published_location_edits_enabled' => false]);

        $tool = app(ApplyPublishedLocationChange::class);
        $this->assertInstanceOf(Approvable::class, $tool);
        $result = json_decode((string) $tool->handle(new Request([], 'disabled-edit')), true);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('disabled', $result['error']);
    }

    public function test_google_location_apply_tool_is_registered(): void
    {
        $this->assertContains(ApplyPublishedLocationChange::class, array_map(
            fn ($tool): string => get_class($tool->inner()), app(ToolRegistry::class)->resolve(['campaign']),
        ));
    }

    public function test_approved_chat_tool_uses_bound_campaign_even_after_focus_changes(): void
    {
        config(['platforms.guardrails.published_location_edits_enabled' => true]);
        $owner = User::factory()->create();
        $this->actingAs($owner);
        $campaign = Campaign::create([
            'user_id' => $owner->getKey(), 'name' => 'Published city edit',
            'platform' => 'meta', 'status' => 'published', 'external_campaign_id' => '12345',
            'ad_account_id' => 'act_111', 'locations' => ['countries' => ['US']],
        ]);
        $workspace = app(Workspace::class);
        $workspace->bindTo('published-location-approval-chat');
        $workspace->ownedBy($owner);
        $workspace->focusOn($campaign);

        $plan = [
            'campaign_id' => $campaign->getKey(), 'platform' => 'meta', 'account_id' => 'act_111',
            'revision' => 0, 'operation' => 'add',
            'place' => ['mapping_id' => 17, 'label' => 'Springfield, Illinois, US', 'external_id' => '2440704'],
            'before' => ['countries' => ['US'], 'cities' => [], 'regions' => []],
            'after' => ['countries' => [], 'cities' => ['2440704'], 'regions' => []],
            'fingerprint' => 'reviewed-location-plan',
        ];
        $planner = Mockery::mock(PublishedLocationChangePlanner::class);
        $planner->shouldReceive('preview')->twice()->andReturn($plan);
        $this->app->instance(PublishedLocationChangePlanner::class, $planner);
        $editor = Mockery::mock(PublishedLocationEditor::class);
        $editor->shouldReceive('apply')->once()->with(
            Mockery::on(fn (Campaign $bound): bool => $bound->is($campaign)),
            $plan,
            Mockery::type(Decision::class),
        )->andReturn(['campaign_id' => $campaign->getKey(), 'targeting_revision' => 1]);
        $this->app->instance(PublishedLocationEditor::class, $editor);
        $tool = app(ApplyPublishedLocationChange::class);
        $request = new Request(['operation' => 'add', 'mapping_id' => 17, 'expected_revision' => 0], 'approved-location-call');

        $approval = $tool->shouldRequestApproval($request);
        $this->assertStringContainsString('Springfield, Illinois, US', $approval->reason);
        $this->assertSame('proposed', Decision::query()->where('approval_call_id', 'approved-location-call')->value('state'));

        $other = Campaign::create(['user_id' => $owner->getKey(), 'name' => 'Other campaign', 'platform' => 'meta']);
        $workspace->focusOn($other);
        $result = json_decode((string) $tool->handle($request), true);

        $this->assertTrue($result['ok']);
        $this->assertSame($campaign->getKey(), $result['result']['campaign_id']);
        $this->assertSame('consumed', Decision::query()->where('approval_call_id', 'approved-location-call')->value('state'));
    }
}
