<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\CampaignApprovalBinding;
use App\Campaigns\Publisher;
use App\Campaigns\PublishGate;
use App\Campaigns\Publishing\MetaPublisher;
use App\Campaigns\Publishing\PlatformPublisher;
use App\Campaigns\Targeting\MetaAudienceSelections;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\ApiCall;
use App\Models\Asset;
use App\Models\Campaign;
use App\Models\Location;
use App\Models\PlatformLocation;
use App\Models\User;
use App\Services\Meta\AdSetSpec;
use App\Services\Meta\CampaignSpec;
use App\Services\Meta\Meta;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Tools\Request;
use Mockery;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * The whole path a chat takes to a live campaign, with the platform faked.
 *
 * Covers what the product is for, and the two things that must never regress:
 * the gate refusing an incomplete campaign, and a mid-flight failure leaving
 * nothing behind on the account.
 */
class CampaignPublishTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    protected function setUp(): void
    {
        parent::setUp();

        $this->seedVerifiedCountries();

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['act_111'],
            'platforms.guardrails.max_daily_budget' => 20,
            'platforms.guardrails.max_calls_per_hour' => 60,
            'platforms.meta.mcp.enabled' => false,   // exercise the Graph path
            'platforms.meta.token' => 'test-token',
        ]);

        $this->actingAs(User::factory()->create());
        app(Workspace::class)->bindTo('conv-publish-0001');
    }

    public function test_a_campaign_assembled_in_chat_publishes_and_records_every_call(): void
    {
        $this->fakeMeta();

        $campaign = $this->assembleReadyCampaign();

        $this->assertSame([], app(PublishGate::class)->check($campaign));

        $publisher = app(Publisher::class);
        $decision = $publisher->approve($publisher->propose($campaign, 'test'), 'test');

        $this->assertTrue($decision->wasApplied());
        $this->assertSame('published', $campaign->fresh()->status);
        $this->assertSame('camp-1', $campaign->fresh()->external_campaign_id);
        $this->assertSame('published', $campaign->ads()->first()->status);

        // Every mutation reached the audit log, dry run included.
        $this->assertTrue(ApiCall::where('dry_run', true)->exists());
        $this->assertTrue(ApiCall::where('endpoint', 'act_111/campaigns')->where('mutating', true)->exists());
    }

    public function test_reordered_json_review_keys_do_not_block_an_unchanged_campaign(): void
    {
        $this->fakeMeta();
        $campaign = $this->assembleReadyCampaign();
        $publisher = app(Publisher::class);
        $proposal = $publisher->propose($campaign, 'test');
        $params = $proposal->params;
        $params['country_targeting'] = array_reverse($params['country_targeting'], true);
        $params['meta_targeting'] = array_reverse($params['meta_targeting'], true);
        $proposal->update(['params' => $params]);

        $decision = $publisher->approve($proposal->fresh(), 'test');

        $this->assertTrue($decision->wasApplied());
        $this->assertSame('published', $campaign->fresh()->status);
    }

    public function test_meta_creation_prefers_mcp_when_credentials_are_configured(): void
    {
        config([
            'platforms.meta.mcp.enabled' => true,
            'platforms.meta.mcp.token' => 'test-mcp-token',
            'platforms.meta.mcp.endpoint' => 'https://meta-mcp.example.test/mcp',
        ]);
        Http::fake(['*' => Http::response(['result' => ['content' => [[
            'type' => 'text', 'text' => json_encode(['campaign_id' => 'camp-1']),
        ]]]])]);

        $this->assertTrue(app(Meta::class)->usingMcp());
        $this->assertSame('camp-1', app(Meta::class)->createCampaign(new CampaignSpec('act_111', 'Test', 'OUTCOME_TRAFFIC')));
        Http::assertSent(fn ($request): bool => str_contains($request->url(), 'meta-mcp.example.test')
            && ($request->data()['params']['name'] ?? null) === 'ads_create_campaign');
        Http::assertNotSent(fn ($request): bool => str_contains($request->url(), '/act_111/campaigns'));
    }

    public function test_meta_live_status_updates_use_graph_when_mcp_credentials_are_configured(): void
    {
        config([
            'platforms.meta.mcp.enabled' => true,
            'platforms.meta.mcp.token' => 'test-mcp-token',
            'platforms.meta.mcp.endpoint' => 'https://meta-mcp.example.test/mcp',
        ]);
        Http::fake(['*' => Http::response(['success' => true])]);

        app(Meta::class)->updateEntity('act_111', 'camp-1', 'campaign', ['status' => 'PAUSED']);

        Http::assertSent(fn ($request): bool => str_contains($request->url(), '/camp-1')
            && ($request->data()['status'] ?? null) === 'PAUSED');
        Http::assertNotSent(fn ($request): bool => str_contains($request->url(), 'meta-mcp.example.test'));
    }

    public function test_meta_edits_other_than_status_go_live_through_graph_not_an_mcp_draft(): void
    {
        config([
            'platforms.meta.mcp.enabled' => true,
            'platforms.meta.mcp.token' => 'test-mcp-token',
            'platforms.meta.mcp.endpoint' => 'https://meta-mcp.example.test/mcp',
        ]);
        Http::fake(['*' => Http::response(['success' => true])]);

        app(Meta::class)->updateEntity('act_111', 'adset-1', 'ad_set', ['daily_budget' => 2800]);

        Http::assertSent(fn ($request): bool => str_contains($request->url(), '/adset-1')
            && ($request->data()['daily_budget'] ?? null) == 2800);
        Http::assertNotSent(fn ($request): bool => str_contains($request->url(), 'meta-mcp.example.test'));
    }

    public function test_publishing_two_ad_sets_records_each_created_ad_once(): void
    {
        $this->fakeMeta();
        $campaign = $this->assembleReadyCampaign();
        $firstAd = $campaign->ads()->firstOrFail();
        $second = $campaign->adSets()->create([
            'position' => 2,
            'name' => 'UK test',
            'locations' => ['countries' => ['GB']],
            'placements' => ['facebook'],
        ]);
        $campaign->ads()->create([
            'ad_set_id' => $second->id,
            'headline' => 'UK headline',
            'primary_text' => 'UK copy',
            'cta' => $firstAd->cta,
            'asset_id' => $firstAd->asset_id,
        ]);

        $created = [];
        app(MetaPublisher::class)->create($campaign->fresh(), 'test', $created);

        $this->assertCount(2, $created['ad_sets']);
        $this->assertCount(2, $created['ads']);
        $this->assertEqualsCanonicalizing(
            $campaign->ads()->pluck('id')->all(),
            array_column($created['ads'], 'ad_row'),
        );
    }

    /**
     * A retired placement position fails the whole ad set.
     *
     * facebook_positions carried video_feeds, which Meta has retired and now
     * refuses rather than ignores: "Facebook video feeds placement is
     * deprecated for this API version and cannot be selected" (subcode
     * 2490562). Naming any publisher platform switches off automatic placement
     * and forces these lists to be sent, so one dead position was enough to
     * make every campaign choosing Facebook fail at the ad set. Found by
     * publishing a real draft, not by this suite, which is why it is here now.
     */
    public function test_no_retired_placement_position_is_sent(): void
    {
        $this->fakeMeta();

        $campaign = $this->assembleReadyCampaign();
        $publisher = app(Publisher::class);

        $publisher->approve($publisher->propose($campaign, 'chat'), 'chat');

        Http::assertSent(function ($request): bool {
            if (! str_contains($request->url(), '/adsets')) {
                return false;
            }

            $targeting = json_decode((string) $request->data()['targeting'], true);

            return ($targeting['facebook_positions'] ?? []) === ['feed', 'story', 'facebook_reels', 'marketplace', 'search']
                && ! in_array('video_feeds', $targeting['facebook_positions'] ?? [], true);
        });

        $instagram = (new AdSetSpec(
            adAccountId: 'act_111',
            campaignId: '1',
            name: 'n',
            budgetMinorUnits: 100,
            optimizationGoal: 'LINK_CLICKS',
            targeting: ['countries' => ['US'], 'placements' => ['instagram']],
            pageId: 'page',
        ))->targetingSpec();

        $this->assertSame(['stream', 'story', 'reels'], $instagram['instagram_positions']);
    }

    public function test_selected_meta_website_audiences_reach_the_paused_ad_set_exactly(): void
    {
        $this->fakeMeta([
            '*/act_111/customaudiences*' => Http::response(['data' => [
                ['id' => '700', 'name' => 'Visitors', 'account_id' => '111', 'subtype' => 'WEBSITE',
                    'pixel_id' => '900', 'operation_status' => ['code' => 200], 'delivery_status' => ['code' => 200]],
                ['id' => '701', 'name' => 'Recent buyers', 'account_id' => '111', 'subtype' => 'WEBSITE',
                    'pixel_id' => '900', 'operation_status' => ['code' => 200], 'delivery_status' => ['code' => 200]],
            ]]),
            '*/act_111/adspixels*' => Http::response(['data' => [
                ['id' => 'pixel-1', 'name' => 'Test Pixel'],
                ['id' => '900', 'name' => 'Website pixel'],
            ]]),
        ]);
        $campaign = $this->assembleReadyCampaign();
        $audiences = app(MetaAudienceSelections::class);
        $first = $audiences->save($campaign, '700', 'include', (int) ($campaign->targetingSet()->value('revision') ?? 0));
        $audiences->save($campaign->fresh(), '701', 'exclude', $first->revision);

        $this->assertSame([], app(PublishGate::class)->check($campaign->fresh()));
        $publisher = app(Publisher::class);
        $result = $publisher->approve($publisher->propose($campaign->fresh(), 'test'), 'test');

        $this->assertTrue($result->wasApplied());
        Http::assertSent(function ($request): bool {
            if (! str_contains($request->url(), '/adsets')) {
                return false;
            }

            $targeting = json_decode((string) ($request->data()['targeting'] ?? ''), true);

            return ($targeting['custom_audiences'] ?? null) === [['id' => '700']]
                && ($targeting['excluded_custom_audiences'] ?? null) === [['id' => '701']];
        });
    }

    public function test_selected_meta_city_reaches_the_ad_set_without_widening_to_its_whole_country(): void
    {
        $this->fakeMeta([
            '*/search*' => Http::response(['data' => [
                ['key' => '2420605', 'name' => 'Springfield', 'type' => 'city', 'country_code' => 'US', 'region' => 'Illinois'],
                ['key' => '2420606', 'name' => 'Springfield', 'type' => 'city', 'country_code' => 'US', 'region' => 'Missouri'],
            ]]),
        ]);

        $campaign = $this->assembleReadyCampaign();
        $search = $this->runTool('campaign__choose_location', ['country_code' => 'US', 'kind' => 'city', 'query' => 'Springfield']);

        $this->assertTrue($search['ok']);
        $this->assertSame(['Springfield, Illinois, US', 'Springfield, Missouri, US'], array_column(app(Choices::class)->all()[0]['options'], 'label'));

        $selected = $this->runTool('campaign__choose_location', [
            'country_code' => 'US', 'kind' => 'city', 'query' => 'Springfield',
            'external_id' => '2420606', 'expected_revision' => $search['revision'],
        ]);

        $this->assertTrue($selected['ok']);
        $this->assertSame([], app(PublishGate::class)->check($campaign->fresh()));

        $publisher = app(Publisher::class);
        $this->assertTrue($publisher->approve($publisher->propose($campaign->fresh(), 'test'), 'test')->wasApplied());

        Http::assertSent(function ($request): bool {
            if (! str_contains($request->url(), '/adsets')) {
                return false;
            }

            $geo = json_decode((string) $request->data()['targeting'], true)['geo_locations'] ?? [];

            return ($geo['cities'] ?? null) === [['key' => '2420606']]
                && ! array_key_exists('countries', $geo);
        });
    }

    public function test_chat_publish_review_names_the_exact_city_and_narrowed_provider_payload(): void
    {
        $this->fakeMeta();
        $campaign = $this->assembleReadyCampaign();
        $location = Location::factory()->create([
            'type' => 'city', 'name' => 'Springfield', 'iso_code' => null,
            'country_code' => 'US', 'source' => 'meta', 'source_key' => '2440704',
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $location->getKey(), 'platform' => 'meta',
            'external_id' => '2440704', 'provider_name' => 'Springfield, Illinois, US',
        ]);
        app(TargetingSelections::class)->addCampaignLocation($campaign, $mapping);

        $review = $this->runTool('campaign__request_publish', []);

        $this->assertTrue($review['ready']);
        $this->assertSame('2440704', $review['summary']['selected_places'][0]['external_id']);
        $this->assertSame('Springfield, Illinois, US', $review['summary']['selected_places'][0]['label']);
        $this->assertSame(['cities' => [['key' => '2440704']]], $review['summary']['provider_geography']);
        $this->assertSame('Test Page', $review['summary']['page_name']);

        $request = new Request([], (string) Str::uuid());
        $approval = app(CampaignApprovalBinding::class)->request($request, $campaign->fresh(), 'publish_campaign');

        $this->assertStringContainsString('Springfield, Illinois, US (Meta ID 2440704)', $approval->reason);
        $this->assertStringContainsString('Selected countries: US', $approval->reason);
    }

    public function test_a_location_change_after_publish_review_requires_a_new_approval(): void
    {
        $this->fakeMeta([
            '*/search*' => Http::response(['data' => [
                ['key' => '4081', 'name' => 'California', 'type' => 'region', 'country_code' => 'US'],
            ]]),
        ]);

        $campaign = $this->assembleReadyCampaign();
        $publisher = app(Publisher::class);
        $proposal = $publisher->propose($campaign, 'test');

        $this->assertSame(['countries' => ['US']], $proposal->params['meta_targeting']['geo_locations']);

        $this->runTool('campaign__choose_location', [
            'country_code' => 'US', 'kind' => 'state', 'query' => 'California', 'external_id' => '4081',
        ]);

        $mutationsBeforeApproval = ApiCall::query()->where('mutating', true)->count();
        $decision = $publisher->approve($proposal, 'test');

        $this->assertFalse($decision->wasApplied());
        $this->assertStringContainsString('changed since review', $decision->reason);
        $this->assertSame($mutationsBeforeApproval, ApiCall::query()->where('mutating', true)->count());
    }

    public function test_a_new_shared_place_after_review_blocks_another_campaign_before_provider_mutation(): void
    {
        $this->fakeMeta();
        $campaign = $this->assembleReadyCampaign();
        $publisher = app(Publisher::class);
        $proposal = $publisher->propose($campaign, 'test');
        $this->assertSame('proposed', $proposal->state);

        $second = Campaign::create([
            'user_id' => $campaign->user_id,
            'brief_id' => $campaign->brief_id,
            'name' => 'Other Meta draft',
            'platform' => 'meta',
            'status' => 'draft',
            'locations' => ['countries' => ['US']],
        ]);
        $place = Location::factory()->create([
            'type' => 'city', 'name' => 'Springfield', 'iso_code' => null,
            'country_code' => 'US', 'source' => 'meta', 'source_key' => '2420605',
        ]);
        $mapping = PlatformLocation::factory()->create([
            'location_id' => $place->getKey(), 'platform' => 'meta',
            'external_id' => '2420605', 'provider_name' => 'Springfield, Illinois, US',
        ]);
        app(TargetingSelections::class)->addCampaignLocation($second, $mapping);

        $this->assertStringContainsString('Shared city', app(PublishGate::class)->check($campaign->fresh())[0]);
        $decision = $publisher->approve($proposal, 'test');
        $this->assertSame('blocked', $decision->state);
        $this->assertSame('draft', $campaign->fresh()->status);
        Http::assertNotSent(fn ($request): bool => $request->method() === 'POST' && str_contains($request->url(), '/campaigns'));
    }

    public function test_a_changed_city_parent_after_review_blocks_meta_publication(): void
    {
        $this->fakeMeta([
            '*/search*' => Http::response(['data' => [
                ['key' => '2420605', 'name' => 'Springfield', 'type' => 'city', 'country_code' => 'US', 'region' => 'Illinois', 'region_id' => 10],
            ]]),
        ]);

        $campaign = $this->assembleReadyCampaign();
        $this->runTool('campaign__choose_location', [
            'country_code' => 'US', 'kind' => 'city', 'query' => 'Springfield', 'external_id' => '2420605',
        ]);
        $publisher = app(Publisher::class);
        $proposal = $publisher->propose($campaign->fresh(), 'test');
        $this->assertSame('proposed', $proposal->state);
        $this->assertSame('10', $proposal->params['meta_targeting']['places'][0]['parent_external_id']);

        PlatformLocation::query()->where('platform', 'meta')->where('external_id', '2420605')->sole()
            ->update(['parent_external_id' => '20']);

        $decision = $publisher->approve($proposal, 'test');

        $this->assertFalse($decision->wasApplied());
        $this->assertStringContainsString('changed since review', $decision->reason);
        Http::assertNotSent(fn ($request): bool => $request->method() === 'POST' && str_contains($request->url(), '/adsets'));
    }

    public function test_a_selected_meta_region_can_be_removed_without_a_provider_write(): void
    {
        $this->fakeMeta([
            '*/search*' => Http::response(['data' => [
                ['key' => '4081', 'name' => 'California', 'type' => 'region', 'country_code' => 'US'],
            ]]),
        ]);

        $campaign = $this->assembleReadyCampaign();
        $this->runTool('campaign__choose_location', [
            'country_code' => 'US', 'kind' => 'region', 'query' => 'California', 'external_id' => '4081',
        ]);

        $listed = $this->runTool('campaign__choose_location', ['country_code' => 'US']);
        $this->assertSame('4081', $listed['selected'][0]['external_id']);

        $removed = $this->runTool('campaign__choose_location', [
            'country_code' => 'US', 'remove_external_id' => '4081', 'expected_revision' => $listed['revision'],
        ]);

        $this->assertTrue($removed['ok']);
        $this->assertSame(['countries' => ['US']], app(TargetingSelections::class)->metaGeoLocations($campaign->fresh()));
    }

    /**
     * The tracking has to be on the URL that actually reaches Meta.
     *
     * Storing it and not sending it would look identical everywhere except the
     * analytics, weeks later, on traffic that has already been paid for.
     */
    public function test_the_destination_url_sent_to_meta_carries_the_tracking(): void
    {
        $this->fakeMeta();

        $campaign = $this->assembleReadyCampaign();
        $publisher = app(Publisher::class);

        $publisher->approve($publisher->propose($campaign, 'chat'), 'chat');

        Http::assertSent(function ($request): bool {
            if (! str_contains($request->url(), '/adcreatives')) {
                return false;
            }

            $spec = json_decode((string) ($request->data()['object_story_spec'] ?? '{}'), true);
            $link = $spec['link_data']['link'] ?? '';

            return $link === 'https://example.com/offer?utm_source=facebook&utm_medium=paid_social'
                // The call to action points at the same place, or a click on the
                // button lands untracked while a click on the image does not.
                && ($spec['link_data']['call_to_action']['value']['link'] ?? null) === $link;
        });
    }

    /**
     * Two routes can publish: the chat tool and the panel button. Publishing
     * from one leaves the other's page stale and still enabled, and a second
     * run created a whole second campaign on the account while external_ids
     * kept only the last, orphaning the first.
     */
    public function test_a_campaign_cannot_be_published_twice(): void
    {
        $this->fakeMeta();

        $campaign = $this->assembleReadyCampaign();
        $publisher = app(Publisher::class);

        $first = $publisher->approve($publisher->propose($campaign, 'chat'), 'chat');
        $this->assertTrue($first->wasApplied());

        $callsAfterFirst = ApiCall::where('mutating', true)->count();

        $second = $publisher->approve($publisher->propose($campaign->fresh(), 'web'), 'web');

        $this->assertFalse($second->wasApplied());
        $this->assertStringContainsString('already published', $second->reason);

        // The decisive assertion: nothing further was created on the platform.
        $this->assertSame($callsAfterFirst, ApiCall::where('mutating', true)->count());
        $this->assertSame('camp-1', $campaign->fresh()->external_campaign_id);
    }

    public function test_overlapping_publications_cannot_both_create_a_remote_campaign(): void
    {
        $this->fakeMeta();

        $campaign = $this->assembleReadyCampaign();
        $publisher = app(Publisher::class);
        $platform = Mockery::mock(PlatformPublisher::class);
        $platform->shouldReceive('create')->once()->andReturnUsing(function () use ($campaign, $publisher): array {
            $overlapping = $publisher->approve($publisher->propose($campaign->fresh(), 'overlapping'), 'overlapping');

            $this->assertFalse($overlapping->wasApplied());
            $this->assertStringContainsString('already in progress', $overlapping->reason);

            return ['campaign_id' => 'camp-1'];
        });
        $this->app->instance(config('platforms.publishers.meta'), $platform);

        $first = $publisher->approve($publisher->propose($campaign, 'first'), 'first');

        $this->assertTrue($first->wasApplied());
        $this->assertSame('camp-1', $campaign->fresh()->external_campaign_id);
    }

    public function test_the_gate_reports_an_already_published_campaign(): void
    {
        $this->fakeMeta();

        $campaign = $this->assembleReadyCampaign();
        $publisher = app(Publisher::class);
        $publisher->approve($publisher->propose($campaign, 'chat'), 'chat');

        $blocking = app(PublishGate::class)->check($campaign->fresh());

        $this->assertNotEmpty($blocking);
        $this->assertStringContainsString('already published', $blocking[0]);
    }

    public function test_the_gate_refuses_an_incomplete_campaign(): void
    {
        $created = $this->runTool('campaign__start_campaign', ['name' => 'Bare', 'platform' => 'meta']);
        $campaign = Campaign::find($created['campaign_id']);

        $blocking = app(PublishGate::class)->check($campaign);

        $this->assertContains('objective not set', $blocking);
        $this->assertContains('landing page URL not set', $blocking);
        $this->assertContains('ad account not verified', $blocking);
        $this->assertContains('no ad copy written yet', $blocking);
    }

    public function test_a_failure_part_way_through_removes_what_was_already_created(): void
    {
        // Campaign and ad set succeed, the creative fails. Nothing may survive.
        $this->fakeMeta([
            '*/act_111/adcreatives' => Http::response(
                ['error' => ['message' => 'Invalid image hash', 'code' => 100]], 400,
            ),
        ]);

        $campaign = $this->assembleReadyCampaign();
        $publisher = app(Publisher::class);
        $decision = $publisher->propose($campaign, 'test');

        try {
            $publisher->approve($decision, 'test');
            $this->fail('Publishing should have failed.');
        } catch (\Throwable) {
            // expected
        }

        $this->assertSame('failed', $campaign->fresh()->status);

        // Deepest first, and both objects that existed were deleted.
        $deleted = ApiCall::where('method', 'DELETE')->pluck('endpoint')->all();
        $this->assertSame(['adset-1', 'camp-1'], $deleted);
    }

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

        $this->runTool('campaign__start_campaign', ['name' => 'Rogue', 'platform' => 'meta']);
        $result = $this->runTool('campaign__verify_ad_account', ['ad_account_id' => '999']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not on the allowed list', $result['error']);
        Http::assertNothingSent();
    }

    /**
     * The one tool that spends money must never run on the model's say-so.
     * The package pauses the run when a tool asks for approval, so this is the
     * lock that makes publishing from the chat safe.
     */
    /**
     * Asserted through the registry, not on the tool directly.
     *
     * The agent only ever sees the namespaced wrapper, and the run loop decides
     * whether to pause by testing that wrapper for Approvable. Checking the
     * inner tool passed while the real path executed publish with no pause at
     * all, which is how this shipped unnoticed until a browser run caught it.
     */
    public function test_every_tool_that_spends_money_asks_for_approval_through_the_registry(): void
    {
        $gated = ['campaign__publish_campaign', 'campaign__push_changes'];
        $seen = [];

        foreach (app(ToolRegistry::class)->resolve() as $tool) {
            if (! in_array($tool->name(), $gated, true)) {
                continue;
            }

            $seen[] = $tool->name();

            $this->assertInstanceOf(
                Approvable::class,
                $tool,
                "[{$tool->name()}] is not Approvable as the agent sees it, so the run will never pause.",
            );

            $this->assertNotNull(
                $tool->shouldRequestApproval(new Request([])),
                "[{$tool->name()}] must require approval before it runs.",
            );
        }

        $this->assertSame($gated, $seen, 'A tool that spends money is missing from the registry.');
    }

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

        $this->runTool('campaign__start_campaign', ['name' => 'Bare', 'platform' => 'meta']);
        $result = $this->runTool('campaign__publish_campaign', []);

        $this->assertFalse($result['ok']);
        $this->assertFalse($result['published']);
        $this->assertContains('objective not set', $result['still_needed']);
        Http::assertNothingSent();
    }

    public function test_a_pending_approval_keeps_the_campaign_that_was_reviewed(): void
    {
        $first = $this->runTool('campaign__start_campaign', ['name' => 'First', 'platform' => 'meta']);
        $binding = app(CampaignApprovalBinding::class);
        $request = new Request([], (string) Str::uuid());
        $binding->request($request, Campaign::findOrFail($first['campaign_id']), 'publish_campaign');

        $second = Campaign::create(['user_id' => auth()->id(), 'name' => 'Second', 'platform' => 'meta']);
        app(Workspace::class)->focusOn($second);

        $this->assertSame($first['campaign_id'], $binding->consume($request, 'publish_campaign')?->id);
        $this->assertNotSame($second->id, $first['campaign_id']);
        $this->assertNull($binding->consume($request, 'publish_campaign'));
    }

    public function test_a_campaign_change_invalidates_its_pending_approval(): void
    {
        $created = $this->runTool('campaign__start_campaign', ['name' => 'Before', 'platform' => 'meta']);
        $campaign = Campaign::findOrFail($created['campaign_id']);
        $binding = app(CampaignApprovalBinding::class);
        $request = new Request([], (string) Str::uuid());
        $binding->request($request, $campaign, 'publish_campaign');

        $campaign->update(['name' => 'After']);

        $this->assertNull($binding->consume($request, 'publish_campaign'));
        Http::assertNothingSent();
    }

    #[DataProvider('changedAdSetFields')]
    public function test_ad_set_changes_invalidate_pending_campaign_approval(array $changes): void
    {
        $created = $this->runTool('campaign__start_campaign', ['name' => 'Reviewed', 'platform' => 'meta']);
        $campaign = Campaign::findOrFail($created['campaign_id']);
        $binding = app(CampaignApprovalBinding::class);
        $request = new Request([], (string) Str::uuid());
        $binding->request($request, $campaign, 'publish_campaign');
        $timestamp = $campaign->updated_at;

        $this->travel(5)->minutes();
        $campaign->update($changes);

        $this->assertTrue($timestamp->equalTo($campaign->fresh()->updated_at));
        $this->assertNull($binding->consume($request, 'publish_campaign'));
        Http::assertNothingSent();
    }

    public static function changedAdSetFields(): array
    {
        return [
            'audience' => [['audience' => ['age_min' => 18]]],
            'placements' => [['placements' => ['instagram']]],
            'optimization' => [['optimization_goal' => 'LINK_CLICKS']],
            'conversion' => [['conversion_event' => 'PURCHASE']],
        ];
    }

    #[DataProvider('adSetMutations')]
    public function test_additional_ad_set_changes_invalidate_pending_campaign_approval(string $mutation): void
    {
        $created = $this->runTool('campaign__start_campaign', ['name' => 'Reviewed', 'platform' => 'meta']);
        $campaign = Campaign::findOrFail($created['campaign_id']);
        $adSet = $campaign->adSets()->create(['position' => 2, 'name' => 'Second', 'audience' => ['age_min' => 25]]);
        $binding = app(CampaignApprovalBinding::class);
        $request = new Request([], (string) Str::uuid());
        $binding->request($request, $campaign, 'publish_campaign');

        match ($mutation) {
            'update' => $adSet->update(['audience' => ['age_min' => 18]]),
            'remove' => $adSet->delete(),
            'add' => $campaign->adSets()->create(['position' => 3, 'name' => 'Third']),
        };

        $this->assertNull($binding->consume($request, 'publish_campaign'));
        Http::assertNothingSent();
    }

    public static function adSetMutations(): array
    {
        return [['update'], ['remove'], ['add']];
    }

    // ----------------------------------------------------------------- helpers

    private function assembleReadyCampaign(): Campaign
    {
        Storage::fake('local');
        Storage::disk('local')->put('assets/creative.png', 'bytes');

        $created = $this->runTool('campaign__start_campaign', ['name' => 'Winter Sale', 'platform' => 'meta']);
        $campaign = Campaign::find($created['campaign_id']);

        $this->runTool('campaign__set_campaign_basics', [
            'objective' => 'OUTCOME_SALES',
            'landing_url' => 'https://example.com/offer',
        ]);
        // The gate requires this to be answered, not defaulted.
        $this->runTool('campaign__declare_ad_category', ['categories' => ['NONE']]);
        $this->runTool('campaign__set_campaign_budget', ['amount' => 20]);
        $this->runTool('campaign__set_targeting', [
            'countries' => ['US'],
            'devices' => ['mobile'],
            'placements' => ['facebook', 'instagram'],
        ]);
        $this->runTool('campaign__set_bidding', ['strategy' => 'COST_CAP', 'target_cost' => 0.5]);
        $this->runTool('campaign__set_tracking', ['utm' => 'utm_source=facebook&utm_medium=paid_social']);
        $this->runTool('campaign__verify_ad_account', ['ad_account_id' => '111']);
        $this->runTool('campaign__choose_page', ['page_id' => 'page-1']);
        $this->runTool('campaign__choose_pixel', ['pixel_id' => 'pixel-1']);
        // Instagram is one of the placements above, so the account has to be
        // answered. The fake returns none, which records "runs under the Page".
        $this->runTool('campaign__choose_instagram_account', []);

        // An upload is an asset; it becomes advertising when paired with copy.
        $asset = Asset::create([
            'kind' => 'image',
            'source' => 'upload',
            'path' => 'assets/creative.png',
            'original_name' => 'creative.png',
            'mime' => 'image/png',
            'bytes' => 5,
        ]);
        app(Workspace::class)->produced($asset);
        app(Workspace::class)->focusOn($campaign);

        $this->runTool('campaign__review_assets', []);
        $this->runTool('campaign__write_ad_copy', ['ads' => [[
            'headline' => 'Winter Sale',
            'primary_text' => 'Half price until Sunday.',
            'cta' => 'SHOP_NOW',
        ]]]);

        return $campaign->fresh();
    }

    /**
     * A generated creative must upload from the disk it was written to.
     *
     * Uploads live on the default disk and generated creatives on the public
     * one, and the upload read the local disk for everything. Nothing caught it
     * because every test asset was an upload; a generated one failed only at
     * the call to Meta, long after the point that was actually wrong.
     */
    public function test_an_asset_on_the_public_disk_uploads_from_that_disk(): void
    {
        Storage::fake('public');
        Storage::disk('public')->put('creatives/images/made.png', 'generated-bytes');

        $this->fakeMeta();

        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'name' => 'Generated creative',
            'platform' => 'meta',
            'status' => 'draft',
            'ad_account_id' => 'act_111',
        ]);

        $asset = Asset::create([
            'kind' => 'image',
            'source' => 'generated',
            'disk' => 'public',
            'path' => 'creatives/images/made.png',
            'original_name' => 'creative-1.png',
            'mime' => 'image/png',
            'bytes' => 15,
        ]);

        app(Workspace::class)->produced($asset);
        app(Workspace::class)->focusOn($campaign);

        $this->runTool('campaign__review_assets', []);

        $this->assertTrue(
            $asset->fresh()->platformRefs()->where('ad_account_id', 'act_111')->exists(),
            'The generated asset should have uploaded and recorded a platform ref.',
        );
    }

    /**
     * @param  array<string,mixed>  $overrides  win on key collision, so a test can
     *                                          make one endpoint fail and leave the rest
     */
    private function fakeMeta(array $overrides = []): void
    {
        // Union, not spread: a duplicate key in an array literal is silently
        // won by the later entry, which would drop the override entirely.
        Http::fake($overrides + [
            '*/act_111/campaigns' => Http::response(['id' => 'camp-1']),
            '*/act_111/adsets' => Http::response(['id' => 'adset-1']),
            '*/act_111/adcreatives' => Http::response(['id' => 'creative-1']),
            '*/act_111/ads' => Http::response(['id' => 'ad-1']),
            '*/act_111/adimages' => Http::response(['images' => ['x' => ['hash' => 'hash-1']]]),
            '*/me/accounts*' => Http::response(['data' => [['id' => 'page-1', 'name' => 'Test Page']]]),
            '*/adspixels*' => Http::response(['data' => [['id' => 'pixel-1', 'name' => 'Test Pixel']]]),
            '*/act_111*' => Http::response([
                'id' => 'act_111', 'name' => 'Test Account',
                'user_tasks' => ['DRAFT', 'ANALYZE', 'ADVERTISE', 'MANAGE'], 'account_status' => 1, 'currency' => 'USD',
            ]),
            '*' => Http::response(['success' => true]),
        ]);
    }

    /** @return array<string,mixed> */
    private function runTool(string $name, array $arguments): array
    {
        foreach (app(ToolRegistry::class)->resolve() as $tool) {
            if ($tool->name() === $name) {
                $request = new Request($arguments, (string) Str::uuid());

                if ($name === 'campaign__publish_campaign') {
                    $this->assertNotNull($tool->shouldRequestApproval($request));
                }

                return json_decode((string) $tool->handle($request), true);
            }
        }

        $this->fail("No tool registered as [{$name}].");
    }
}
