<?php

namespace Tests\Feature;

use App\Agent\Workspace;
use App\Campaigns\Targeting\PublishedLocationApprovalBinding;
use App\Campaigns\Targeting\PublishedLocationChangePlanner;
use App\Models\Campaign;
use App\Models\Decision;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Laravel\Ai\Tools\Request;
use Mockery;
use Tests\TestCase;

class PublishedLocationApprovalBindingTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(): Campaign
    {
        $owner = User::factory()->create();
        $this->actingAs($owner);
        $campaign = Campaign::create([
            'user_id' => $owner->getKey(), 'name' => 'Springfield edit',
            'platform' => 'meta', 'status' => 'published', 'ad_account_id' => 'act_111',
            'external_campaign_id' => '12345', 'locations' => ['countries' => ['US']],
        ]);
        $workspace = app(Workspace::class);
        $workspace->bindTo('location-edit-conversation');
        $workspace->ownedBy($owner);
        $workspace->focusOn($campaign);

        return $campaign;
    }

    /** @return array<string, mixed> */
    private function plan(Campaign $campaign, string $fingerprint = 'reviewed-state'): array
    {
        return [
            'campaign_id' => $campaign->getKey(), 'platform' => 'meta',
            'account_id' => $campaign->ad_account_id, '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' => $fingerprint,
        ];
    }

    private function request(string $callId, int $mappingId = 17): Request
    {
        return new Request(['operation' => 'add', 'mapping_id' => $mappingId, 'expected_revision' => 0], $callId);
    }

    public function test_approval_keeps_the_exact_campaign_and_is_consumed_once(): void
    {
        $campaign = $this->campaign();
        $plan = $this->plan($campaign);
        $planner = Mockery::mock(PublishedLocationChangePlanner::class);
        $planner->shouldReceive('preview')->twice()->with(Mockery::type(Campaign::class), 'add', 17, 0)->andReturn($plan);
        $this->app->instance(PublishedLocationChangePlanner::class, $planner);
        $binding = app(PublishedLocationApprovalBinding::class);
        $request = $this->request((string) Str::uuid());

        $approval = $binding->request($request, $campaign);
        $this->assertStringContainsString('Springfield, Illinois, US (Meta ID 2440704)', $approval->reason);
        $this->assertStringContainsString('account act_111', $approval->reason);

        $other = Campaign::create(['user_id' => $campaign->user_id, 'name' => 'Other', 'platform' => 'meta']);
        app(Workspace::class)->focusOn($other);

        $approved = $binding->consume($request);
        $this->assertSame($campaign->getKey(), $approved['campaign']->getKey());
        $this->assertSame($plan, $approved['plan']);
        $this->assertSame('consumed', $approved['decision']->state);
        $this->assertNull($binding->consume($request));
    }

    public function test_changed_arguments_block_before_provider_recheck(): void
    {
        $campaign = $this->campaign();
        $planner = Mockery::mock(PublishedLocationChangePlanner::class);
        $planner->shouldReceive('preview')->once()->andReturn($this->plan($campaign));
        $this->app->instance(PublishedLocationChangePlanner::class, $planner);
        $binding = app(PublishedLocationApprovalBinding::class);
        $callId = (string) Str::uuid();
        $binding->request($this->request($callId), $campaign);

        $this->assertNull($binding->consume($this->request($callId, 18)));
        $this->assertSame('blocked', Decision::query()->where('approval_call_id', $callId)->value('state'));
    }

    public function test_replacement_approval_binds_both_old_and_new_place_ids(): void
    {
        $campaign = $this->campaign();
        $plan = $this->plan($campaign);
        $plan['operation'] = 'replace';
        $plan['replaced_place'] = ['mapping_id' => 16, 'label' => 'Old city, US', 'external_id' => '2440703'];
        $planner = Mockery::mock(PublishedLocationChangePlanner::class);
        $planner->shouldReceive('preview')->once()
            ->with(Mockery::type(Campaign::class), 'replace', 17, 0, 16)->andReturn($plan);
        $this->app->instance(PublishedLocationChangePlanner::class, $planner);
        $binding = app(PublishedLocationApprovalBinding::class);
        $callId = (string) Str::uuid();

        $approval = $binding->request(new Request([
            'operation' => 'replace', 'mapping_id' => 17, 'replace_mapping_id' => 16, 'expected_revision' => 0,
        ], $callId), $campaign);
        $this->assertStringContainsString('Replace Old city, US with Springfield', $approval->reason);

        $this->assertNull($binding->consume(new Request([
            'operation' => 'replace', 'mapping_id' => 17, 'replace_mapping_id' => 18, 'expected_revision' => 0,
        ], $callId)));
        $this->assertSame('blocked', Decision::query()->where('approval_call_id', $callId)->value('state'));
    }

    public function test_changed_provider_plan_blocks_approval(): void
    {
        $campaign = $this->campaign();
        $planner = Mockery::mock(PublishedLocationChangePlanner::class);
        $planner->shouldReceive('preview')->twice()->andReturn($this->plan($campaign, 'before'), $this->plan($campaign, 'after'));
        $this->app->instance(PublishedLocationChangePlanner::class, $planner);
        $binding = app(PublishedLocationApprovalBinding::class);
        $callId = (string) Str::uuid();
        $request = $this->request($callId);
        $binding->request($request, $campaign);

        $this->assertNull($binding->consume($request));
        $this->assertSame('blocked', Decision::query()->where('approval_call_id', $callId)->value('state'));
        $this->assertStringContainsString('changed since review', Decision::query()->where('approval_call_id', $callId)->value('reason'));
    }

    public function test_another_user_cannot_consume_pending_approval(): void
    {
        $campaign = $this->campaign();
        $planner = Mockery::mock(PublishedLocationChangePlanner::class);
        $planner->shouldReceive('preview')->once()->andReturn($this->plan($campaign));
        $this->app->instance(PublishedLocationChangePlanner::class, $planner);
        $binding = app(PublishedLocationApprovalBinding::class);
        $callId = (string) Str::uuid();
        $request = $this->request($callId);
        $binding->request($request, $campaign);
        $this->actingAs(User::factory()->create());

        $this->assertNull($binding->consume($request));
        $this->assertSame('proposed', Decision::query()->where('approval_call_id', $callId)->value('state'));
    }
}
