<?php

namespace Tests\Feature;

use App\Agent\Answers;
use App\Agent\Choices;
use App\Agent\MarketingAgent;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\LaunchFlow;
use App\Campaigns\LinkedInManagement;
use App\Campaigns\Platforms\LinkedInRules;
use App\Campaigns\PublishGate;
use App\Campaigns\Publishing\LinkedInPublisher;
use App\Http\Controllers\ChatController;
use App\Models\Asset;
use App\Models\AssetPlatformRef;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\CampaignChange;
use App\Models\User;
use App\Services\LinkedIn\LinkedIn;
use App\Services\LinkedIn\LinkedInException;
use App\Services\LinkedIn\LinkedInTargetingFacets;
use App\Services\Platforms\LinkedInAdapter;
use App\Support\Actor;
use App\Support\Markdown;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Laravel\Ai\Tools\Request;
use PHPUnit\Framework\Attributes\TestWith;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

class ChatLinkedInFlowTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    protected User $user;

    protected Campaign $campaign;

    protected Workspace $workspace;

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

        $this->seedVerifiedCountries();

        MarketingAgent::fake(['Pick one.']);

        Config::set('platforms.guardrails.allowed_ad_accounts', [
            '556447014',
            'urn:li:sponsoredAccount:556447014',
        ]);
        Config::set('platforms.linkedin.access_token', 'test-token');
        Config::set('platforms.guardrails.max_daily_budget', 1000.0);

        $this->user = User::factory()->create();
        $this->actingAs($this->user);

        $this->workspace = app(Workspace::class);
        $this->workspace->bindTo('conv-linkedin-0001');
        $this->workspace->ownedBy($this->user);

        $this->campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'LinkedIn B2B Campaign',
            'platform' => 'linkedin',
            'status' => 'draft',
            'objective' => 'WEBSITE_VISITS',
            'currency' => 'USD',
        ]);

        $this->workspace->focusOn($this->campaign);
    }

    private function runTool(string $name, array $arguments = []): string
    {
        $tool = collect(app(ToolRegistry::class)->resolve())->first(fn ($t) => $t->name() === $name);

        $this->assertNotNull($tool, "Tool {$name} is not registered.");

        return (string) $tool->handle(new Request($arguments));
    }

    public function test_list_ad_accounts_for_linkedin(): void
    {
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts?q=search' => Http::response([
                'elements' => [
                    ['id' => 556447014, 'name' => 'AdMedia Products', 'currency' => 'USD', 'status' => 'ACTIVE'],
                ],
            ], 200),
        ]);

        $json = json_decode($this->runTool('campaign__list_ad_accounts'), true);

        $this->assertTrue($json['ok']);
        $this->assertCount(1, $json['ad_accounts']);
        $this->assertEquals('556447014', $json['ad_accounts'][0]['id']);
        $all = app(Choices::class)->all();
        $this->assertNotEmpty($all);
        $this->assertEquals('ad_account_id', $all[0]['field']);
        $this->assertEquals('556447014', $all[0]['options'][0]['value']);
    }

    public function test_linkedin_campaign_listing_preserves_pagination_and_never_reads_meta(): void
    {
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns*' => Http::response([
                'elements' => [['id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'status' => 'DRAFT']],
                'metadata' => ['nextPageToken' => 'next'],
            ]),
        ]);

        $result = json_decode($this->runTool('campaign__list_campaigns', [
            'platform' => 'linkedin', 'ad_account_id' => '556447014',
        ]), true);

        $this->assertTrue($result['ok']);
        $this->assertSame(77, $result['elements'][0]['id']);
        $this->assertSame('next', $result['next_page_token']);
        Http::assertSentCount(1);
    }

    public function test_an_external_linkedin_campaign_can_be_opened_without_platform_writes(): void
    {
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
            'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'name' => 'External campaign',
            'status' => 'PAUSED', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88',
            'objectiveType' => 'WEBSITE_VISIT', 'dailyBudget' => ['amount' => '25.00', 'currencyCode' => 'USD'],
        ])]);

        $result = $this->runTool('campaign__open_campaign', ['platform' => 'linkedin', 'campaign_id' => '77', 'ad_account_id' => '556447014']);

        $this->assertStringContainsString('External campaign', $result);
        $this->assertDatabaseHas('campaigns', ['platform' => 'linkedin', 'external_campaign_id' => '77', 'budget' => '25.00']);
        $this->assertDatabaseHas('api_calls', [
            'platform' => 'linkedin',
            'actor' => app(Actor::class)->describe('campaign import'),
        ]);
        Http::assertNotSent(fn ($request): bool => $request->method() !== 'GET');
    }

    public function test_reopening_a_linkedin_campaign_refreshes_remote_fields_and_preserves_pending_local_edits(): void
    {
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::sequence()
            ->push(['id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'name' => 'First name',
                'objectiveType' => 'WEBSITE_VISIT', 'dailyBudget' => ['amount' => '25.00', 'currencyCode' => 'USD']])
            ->push(['id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'name' => 'Renamed externally',
                'objectiveType' => 'WEBSITE_VISIT', 'dailyBudget' => ['amount' => '90', 'currencyCode' => 'USD']])
            ->push(['id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'name' => 'Renamed externally',
                'objectiveType' => 'WEBSITE_VISIT', 'dailyBudget' => ['amount' => '120', 'currencyCode' => 'USD']]),
        ]);

        $arguments = ['platform' => 'linkedin', 'campaign_id' => '77', 'ad_account_id' => '556447014'];
        $this->runTool('campaign__open_campaign', $arguments);
        $this->runTool('campaign__open_campaign', $arguments);

        $campaign = Campaign::where('external_campaign_id', '77')->firstOrFail();
        $this->assertSame('Renamed externally', $campaign->name);
        $this->assertSame('90.00', $campaign->budget);
        $this->assertSame('90.00', $campaign->published_state['budget']);

        $campaign->update(['budget' => 80]);
        $this->runTool('campaign__open_campaign', $arguments);

        $campaign->refresh();
        $this->assertSame('80.00', $campaign->budget);
        $this->assertSame('120.00', $campaign->published_state['budget']);
        Http::assertNotSent(fn ($request): bool => $request->method() !== 'GET');
    }

    public function test_importing_a_target_cost_campaign_preserves_its_bid_strategy(): void
    {
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
            'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'name' => 'Target cost',
            'objectiveType' => 'WEBSITE_VISIT', 'dailyBudget' => ['amount' => '25.00', 'currencyCode' => 'USD'],
            'optimizationTargetType' => 'TARGET_COST_PER_CLICK', 'unitCost' => ['amount' => '4.00', 'currencyCode' => 'USD'],
        ])]);

        $this->runTool('campaign__open_campaign', ['platform' => 'linkedin', 'campaign_id' => '77', 'ad_account_id' => '556447014']);

        $campaign = Campaign::where('external_campaign_id', '77')->firstOrFail();
        $this->assertSame('TARGET_COST', $campaign->bid_strategy);
        $this->assertSame('TARGET_COST', $campaign->published_state['bid_strategy']);
    }

    public function test_linkedin_page_selection_requires_approved_posting_permission(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014']);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/organizationsLookup*' => Http::response(['results' => ['123' => ['id' => 123, 'localizedName' => 'Verified Company Page']]]),
            'https://api.linkedin.com/rest/organizationAcls*' => Http::response(['elements' => [
                ['organization' => 'urn:li:organization:123', 'role' => 'DIRECT_SPONSORED_CONTENT_POSTER', 'state' => 'APPROVED'],
                ['organization' => 'urn:li:organization:456', 'role' => 'ADMINISTRATOR', 'state' => 'REQUESTED'],
            ]])]);

        $offered = json_decode($this->runTool('campaign__choose_page'), true);
        $card = collect(app(Choices::class)->all())->firstWhere('field', 'page_id');
        $result = json_decode($this->runTool('campaign__choose_page', ['page_id' => '123']), true);
        $refused = json_decode($this->runTool('campaign__choose_page', ['page_id' => '456']), true);

        $this->assertTrue($offered['ok']);
        $this->assertSame('Verified Company Page', $card['options'][0]['label']);
        $this->assertSame('Sponsored content poster', $card['options'][0]['hint']);
        $this->assertTrue($result['ok']);
        $this->assertFalse($refused['ok']);
        $this->assertSame('123', $this->campaign->fresh()->page_id);
        $this->assertSame('Verified Company Page', $this->campaign->fresh()->meta['linkedin_page']['name']);
        $this->assertDatabaseHas('api_calls', ['campaign_id' => $this->campaign->getKey(), 'platform' => 'linkedin', 'endpoint' => 'rest/organizationAcls']);
        Http::assertNotSent(fn ($request): bool => $request->method() !== 'GET');
    }

    public function test_missing_linkedin_page_posting_role_stops_instead_of_asking_which_page(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014',
            'landing_url' => 'https://example.com',
        ]);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/organizationAcls*' => Http::response(['elements' => [[
            'organization' => 'urn:li:organization:123',
            'role' => 'ADMINISTRATOR',
            'state' => 'REQUESTED',
        ]]])]);

        $controller = app(ChatController::class);
        (new \ReflectionMethod($controller, 'offerNextStep'))->invoke($controller);
        $reply = (new \ReflectionMethod($controller, 'questionFor'))->invoke(
            $controller,
            'No approved Page role is available. Which LinkedIn Page should publish these ads?',
            [],
            false,
        );

        $this->assertStringContainsString('An admin must grant', $reply);
        $this->assertStringContainsString('campaign has not been sent to LinkedIn', $reply);
        $this->assertStringNotContainsString('Which LinkedIn Page', $reply);
        $this->assertSame([], app(Choices::class)->drain());
    }

    /** Every publish builds its own campaign group, so the flow never asks for one. */
    public function test_no_campaign_group_is_asked_for_or_offered(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014']);
        Http::preventStrayRequests();

        $this->assertNull(collect(app(LaunchFlow::class)->progress($this->campaign->fresh()))->firstWhere('key', 'linkedin_campaign_group'));

        $result = json_decode($this->runTool('campaign__choose_linked_in_resource', ['campaign_group_id' => '88']), true);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('creates its own new campaign group', $result['error']);
        $this->assertArrayNotHasKey('campaign_group_id', (array) $this->campaign->fresh()->external_ids);
        $this->assertSame([], app(Choices::class)->drain());
    }

    /** A group picked before the step was removed is not built into. */
    public function test_publishing_forgets_a_previously_chosen_group(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_ids' => ['campaign_group_id' => '88'],
            'meta' => ['linkedin_setup' => ['campaign_group' => ['id' => '88', 'name' => 'Existing group']]]]);
        $adapter = \Mockery::mock(LinkedInAdapter::class);
        $adapter->shouldReceive('createCampaign')->once()->andReturnUsing(function (Campaign $campaign): string {
            $this->assertArrayNotHasKey('campaign_group_id', (array) $campaign->external_ids);
            $campaign->update(['external_ids' => ['campaign_group_id' => '99']]);

            return 'urn:li:sponsoredCampaign:1';
        });
        $adapter->shouldReceive('park')->andReturn(true);
        $created = [];

        (new LinkedInPublisher($adapter))->create($this->campaign->fresh(), 'tester', $created);

        $this->assertSame('99', $created['campaign_group_id']);
        $this->assertArrayNotHasKey('campaign_group', $this->campaign->fresh()->meta['linkedin_setup']);
    }

    public function test_linkedin_professional_targeting_saves_only_current_provider_results(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014']);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [[
            'urn' => 'urn:li:seniority:4', 'facetUrn' => 'urn:li:adTargetingFacet:seniorities', 'name' => 'Senior',
        ]]])]);

        $saved = json_decode($this->runTool('campaign__choose_linked_in_resource', ['audience_mode' => 'seniorities', 'selection' => ['seniorities|urn:li:seniority:4']]), true);
        $refused = json_decode($this->runTool('campaign__choose_linked_in_resource', ['selection' => ['seniorities|urn:li:seniority:999']]), true);

        $this->assertTrue($saved['ok'], json_encode($saved));
        $this->assertFalse($refused['ok']);
        $this->assertSame(['urn:li:seniority:4'], $this->campaign->fresh()->audience['linkedin_facets']['seniorities']);
        Http::assertNotSent(fn ($request): bool => $request->method() !== 'GET');
    }

    public function test_linkedin_audience_recovery_offers_ai_search_and_inline_manual_input(): void
    {
        $controller = app(ChatController::class);
        $method = new \ReflectionMethod($controller, 'offerRecovery');
        $method->invoke($controller, [
            'key' => 'linkedin_audience', 'label' => 'professional audience',
            'tool' => 'choose_linked_in_resource', 'offers' => true,
        ]);

        $choice = app(Choices::class)->drain()[0];

        $this->assertSame('AI Generated', $choice['options'][0]['label']);
        $this->assertSame('Suggested', $choice['options'][0]['badge']);
        $this->assertStringContainsString('show verified LinkedIn matches', $choice['options'][0]['sends']);
        $this->assertTrue($choice['allow_other']);
        $this->assertFalse($choice['other_in_composer']);
        $this->assertSame('Enter it myself', $choice['other_label']);
        $this->assertSame('e.g. Software Engineer', $choice['other_placeholder']);
        $this->assertCount(1, $choice['options']);
    }

    public function test_creative_recovery_offers_retry_and_generator_instructions_instead_of_selection_question(): void
    {
        $controller = app(ChatController::class);
        $method = new \ReflectionMethod($controller, 'offerRecovery');
        $method->invoke($controller, [
            'key' => 'creatives', 'label' => 'creatives',
            'tool' => 'import_creatives', 'offers' => true,
        ]);

        $choices = app(Choices::class)->drain();
        $reply = (new \ReflectionMethod($controller, 'questionFor'))->invoke(
            $controller,
            'Which creatives should be used?',
            [],
            false,
        );
        $this->assertStringContainsString('[creative generator]('.route('creatives.create').')', $reply);
        $this->assertStringContainsString('compatible with this campaign', $reply);
        $this->assertStringContainsString('1200x628 (1.91:1)', $reply);
        $this->assertStringContainsString('1200x1200 (1:1)', $reply);
        $this->assertStringContainsString('960x1200 (4:5)', $reply);
        $this->assertStringContainsString('video aspect ratios are 16:9, 9:16, 1:1, and 4:5', $reply);
        $this->assertStringContainsString('Wait until generation finishes', $reply);
        $this->assertStringContainsString('return to this chat and click **Try again**', $reply);
        $this->assertStringNotContainsString('Which creatives should be used?', $reply);
        $this->assertStringContainsString('href="'.route('creatives.create').'"', (string) Markdown::toHtml($reply));

        $this->assertCount(1, $choices);
        $this->assertSame('retry_creatives', $choices[0]['field']);
        $this->assertCount(1, $choices[0]['options']);
        $this->assertSame('Try again', $choices[0]['options'][0]['label']);
        $this->assertStringContainsString('import_creatives', $choices[0]['options'][0]['sends']);
        $this->assertFalse($choices[0]['allow_other']);
    }

    public function test_creative_recovery_preserves_the_specific_compatibility_reason(): void
    {
        $controller = app(ChatController::class);
        $reason = 'Finished creatives were found, but none are compatible with this LinkedIn campaign: '
            .'10 (image 9:16). Supported dimensions are listed here.';
        (new \ReflectionMethod($controller, 'offerRecovery'))->invoke($controller, [
            'key' => 'creatives', 'label' => 'creatives',
            'tool' => 'import_creatives', 'offers' => true,
        ], $reason);

        $reply = (new \ReflectionMethod($controller, 'questionFor'))->invoke(
            $controller,
            'Which creatives should be used?',
            [],
            false,
        );

        $this->assertSame($reason, $reply);
        $this->assertSame('retry_creatives', app(Choices::class)->drain()[0]['field']);
    }

    #[TestWith([true, []])]
    #[TestWith([false, [['id' => 'approval', 'tool' => 'publish_campaign', 'reason' => null]]])]
    public function test_creative_recovery_preserves_failure_and_approval_replies(bool $failed, array $awaiting): void
    {
        $controller = app(ChatController::class);
        (new \ReflectionMethod($controller, 'offerRecovery'))->invoke($controller, [
            'key' => 'creatives', 'label' => 'creatives',
            'tool' => 'import_creatives', 'offers' => true,
        ]);
        app(Choices::class)->drain();

        $reply = (new \ReflectionMethod($controller, 'questionFor'))->invoke(
            $controller, 'Important failure or approval details.', $awaiting, $failed,
        );

        $this->assertSame('Important failure or approval details.', $reply);
    }

    public function test_unresolved_automatic_linkedin_step_replaces_later_options_with_recovery_actions(): void
    {
        $step = [
            'key' => 'linkedin_insight_tag',
            'label' => 'Insight Tag',
            'tool' => 'choose_linked_in_resource',
            'offers' => false,
            'arguments' => ['section' => 'insight_tag'],
            'ask' => 'Verify the account Insight Tag is reporting from the landing domain.',
        ];
        $budget = [
            'key' => 'budget',
            'label' => 'budget',
            'tool' => 'set_campaign_budget',
            'offers' => true,
            'ask' => 'How should the budget work, and how much?',
        ];
        $flow = \Mockery::mock(LaunchFlow::class);
        $flow->shouldReceive('next')->twice()->with(\Mockery::type(Campaign::class))->andReturn($step);
        $flow->shouldReceive('steps')->twice()->with(\Mockery::type(Campaign::class))->andReturn([$step, $budget]);
        app()->instance(LaunchFlow::class, $flow);

        app(Choices::class)->offer('budget_amount', 'Choose a budget.', [
            ['value' => '50', 'label' => 'USD 50'],
        ]);
        $controller = app(ChatController::class);
        (new \ReflectionMethod($controller, 'offerNextStep'))->invoke($controller, 'continue');

        $choices = app(Choices::class)->drain();
        $reply = (new \ReflectionMethod($controller, 'questionFor'))->invoke(
            $controller,
            'Insight Tag verification failed.',
            [],
            false,
        );

        $this->assertCount(1, $choices);
        $this->assertSame('retry_linkedin_insight_tag', $choices[0]['field']);
        $this->assertSame('The Insight Tag step is still unresolved. What would you like to do?', $choices[0]['question']);
        $this->assertSame(['Try again', 'Show troubleshooting steps'], array_column($choices[0]['options'], 'label'));
        $this->assertStringContainsString('campaign__choose_linked_in_resource', $choices[0]['options'][0]['sends']);
        $this->assertStringContainsString('section="insight_tag"', $choices[0]['options'][0]['sends']);
        $this->assertStringContainsString('do not offer later steps', $choices[0]['options'][0]['sends']);
        $this->assertSame('Insight Tag verification failed.', $reply);
        $this->assertSame([], array_filter($choices, fn (array $choice): bool => $choice['field'] === 'budget_amount'));
    }

    public function test_insight_tag_retry_click_runs_the_verification_tool_without_model_interpretation(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014',
            'landing_url' => 'https://attestpath.ai/',
        ]);
        $step = [
            'key' => 'linkedin_insight_tag',
            'label' => 'Insight Tag',
            'tool' => 'choose_linked_in_resource',
            'offers' => false,
            'arguments' => ['section' => 'insight_tag'],
        ];
        $controller = app(ChatController::class);
        (new \ReflectionMethod($controller, 'offerRecovery'))->invoke($controller, $step);
        $this->workspace->rememberChoices(app(Choices::class)->drain());
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/insightTags*' => Http::response(['elements' => [[
                'id' => 55,
                'sponsoredAccounts' => ['urn:li:sponsoredAccount:556447014'],
            ]]]),
            'https://api.linkedin.com/rest/insightTagDomains*' => Http::response(['elements' => [[
                'domainName' => 'attestpath.ai',
                'insightTag' => 'urn:tscp:insightTag:55',
                'blocked' => false,
                'lastCallbackAt' => 123456789,
            ]]]),
        ]);

        $applied = (new \ReflectionMethod($controller, 'applyAnswers'))->invoke($controller, [[
            'field' => 'retry_linkedin_insight_tag',
            'value' => 'retry',
        ]]);

        $this->assertTrue($applied[0]['applied']);
        $this->assertSame('55', $this->campaign->fresh()->meta['linkedin_setup']['insight_tag']['id']);
        (new \ReflectionProperty($controller, 'steppedIn'))->setValue($controller, [
            'ask' => 'How should the budget work, and how much?',
        ]);
        $reply = (new \ReflectionMethod($controller, 'questionFor'))->invoke(
            $controller,
            'I cannot retry the unchanged request. LinkedIn still rejects it.',
            [],
            false,
        );
        $this->assertSame(
            "The LinkedIn Insight Tag is now verified for attestpath.ai. Tracking verification is complete.\n\n"
                .'How should the budget work, and how much?',
            $reply,
        );
        $this->assertStringNotContainsString('rejects', $reply);
        Http::assertSentCount(2);
    }

    public function test_linkedin_audience_review_reopens_modes_without_changing_saved_targeting(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014',
            'audience' => ['linkedin_facets' => ['titles' => ['urn:li:title:1']]],
            'meta' => ['linkedin_audience_mode' => 'titles', 'linkedin_audience_query' => ['titles' => 'SEO']],
        ]);
        $before = $this->campaign->fresh();
        Http::preventStrayRequests();

        $result = json_decode($this->runTool('campaign__choose_linked_in_resource', [
            'section' => 'audience', 'review_audience' => true,
        ]), true);
        $choice = app(Choices::class)->drain()[0];

        $this->assertTrue($result['ok']);
        $this->assertSame('linkedin_audience_mode', $choice['field']);
        $this->assertSame(['done', 'broad', 'retargeting', ...LinkedInTargetingFacets::keys(), 'exclude', 'remove'], array_column($choice['options'], 'value'));
        $this->assertSame($before->audience, $this->campaign->fresh()->audience);
        $this->assertSame($before->meta, $this->campaign->fresh()->meta);
        Http::assertNothingSent();

        app(Choices::class)->offer('linkedin_audience_segment', 'Choose an audience', [
            ['value' => 'change_audience_mode', 'label' => 'Review targeting', 'sends' => 'Show other audience options.'],
        ]);
        $this->workspace->rememberChoices(app(Choices::class)->drain());
        $controller = app(ChatController::class);
        $applied = (new \ReflectionMethod($controller, 'applyAnswers'))->invoke($controller, [
            ['field' => 'linkedin_audience_segment', 'value' => 'change_audience_mode'],
        ]);
        app(Choices::class)->pin();
        (new \ReflectionMethod($controller, 'offerNextStep'))->invoke($controller, 'Show other audience options.');
        $reviewChoices = app(Choices::class)->drain();

        $this->assertTrue($applied[0]['applied'] ?? false);
        $this->assertCount(1, $reviewChoices);
        $this->assertSame('linkedin_audience_mode', $reviewChoices[0]['field']);
        $this->assertSame($before->audience, $this->campaign->fresh()->audience);
        Http::assertNothingSent();
    }

    public function test_review_audience_phrase_does_not_replace_pending_choices(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014']);
        Http::preventStrayRequests();
        app(Choices::class)->offer('linkedin_professional_selection', 'Previous titles', [
            ['value' => 'titles|urn:li:title:1', 'label' => 'Previous title'],
        ]);
        $before = app(Choices::class)->all();
        $controller = app(ChatController::class);

        (new \ReflectionMethod($controller, 'offerNextStep'))->invoke($controller,
            'What does review_audience true mean?');

        $this->assertSame($before, app(Choices::class)->all());
        Http::assertNothingSent();
    }

    #[TestWith([[]])]
    #[TestWith([[['value' => 'include|urn:li:adSegment:1', 'label' => 'Segment']]])]
    #[TestWith([[['value' => 'change_audience_mode', 'label' => 'Review', 'disabled' => true]]])]
    public function test_audience_review_requires_an_enabled_current_option(array $options): void
    {
        $this->campaign->update(['ad_account_id' => '556447014']);
        $this->workspace->rememberChoices($options === [] ? [] : [[
            'field' => 'linkedin_audience_segment', 'options' => $options,
        ]]);
        Http::preventStrayRequests();
        $controller = app(ChatController::class);

        $applied = (new \ReflectionMethod($controller, 'applyAnswers'))->invoke($controller, [
            ['field' => 'linkedin_audience_segment', 'value' => 'change_audience_mode'],
        ]);

        $this->assertNotContains(true, array_column($applied, 'applied'));
        $this->assertFalse(app(Answers::class)->apply('linkedin_audience_segment', 'change_audience_mode'));
        $this->assertSame([], app(Choices::class)->all());
        Http::assertNothingSent();
    }

    public function test_verified_linkedin_audience_results_include_inline_manual_search(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014']);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [[
            'urn' => 'urn:li:title:1', 'facetUrn' => 'urn:li:adTargetingFacet:titles', 'name' => 'Software Engineer',
        ]]])]);

        $result = json_decode($this->runTool('campaign__choose_linked_in_resource', [
            'section' => 'audience', 'audience_mode' => 'titles', 'query' => 'Engineer',
        ]), true);
        $choice = app(Choices::class)->drain()[0];

        $this->assertTrue($result['ok']);
        $this->assertTrue($choice['allow_other']);
        $this->assertFalse($choice['other_in_composer']);
        $this->assertSame('Enter it myself', $choice['other_label']);
    }

    public function test_company_and_industry_modes_offer_search_without_advancing_to_budget(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014',
            'audience' => ['linkedin_facets' => ['titles' => ['urn:li:title:1']]],
            'meta' => ['linkedin_audience_mode' => 'titles', 'linkedin_audience_reviewed' => true],
        ]);
        Http::preventStrayRequests();

        foreach (['employers', 'industries'] as $mode) {
            $result = json_decode($this->runTool('campaign__choose_linked_in_resource', [
                'section' => 'audience', 'audience_mode' => $mode,
            ]), true);
            $controller = app(ChatController::class);
            (new \ReflectionMethod($controller, 'offerNextStep'))->invoke($controller);
            $choices = app(Choices::class)->drain();

            $this->assertTrue($result['ok']);
            $this->assertCount(1, $choices);
            $this->assertSame('retry_linkedin_audience', $choices[0]['field']);
            $this->assertSame('AI Generated', $choices[0]['options'][0]['label']);
            $this->assertTrue($choices[0]['allow_other']);
            $this->assertFalse($this->campaign->fresh()->meta['linkedin_audience_reviewed']);
            $this->assertSame(['titles' => ['urn:li:title:1']], $this->campaign->fresh()->audience['linkedin_facets']);
        }
        Http::assertNothingSent();
    }

    public function test_manual_linkedin_search_uses_the_entered_term_instead_of_the_saved_query(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014',
            'meta' => ['linkedin_audience_mode' => 'titles', 'linkedin_audience_query' => ['titles' => 'SEO']],
        ]);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [[
            'urn' => 'urn:li:title:123', 'facetUrn' => 'urn:li:adTargetingFacet:titles', 'name' => 'Developer',
        ]]])]);

        app(Choices::class)->offer('linkedin_professional_selection', 'Choose verified titles.', [
            ['value' => 'titles|urn:li:title:1', 'label' => 'Previous SEO title'],
        ], multiple: true, allowOther: true);
        $this->workspace->rememberChoices(app(Choices::class)->drain());
        $controller = app(ChatController::class);
        $applied = (new \ReflectionMethod($controller, 'applyAnswers'))->invoke($controller, [[
            'field' => 'linkedin_professional_search', 'value' => 'Developer',
        ]]);
        $choices = app(Choices::class)->drain();

        $this->assertTrue($applied[0]['applied']);
        Http::assertSent(fn ($request): bool => $request['query'] === 'Developer');
        Http::assertNotSent(fn ($request): bool => $request['query'] === 'SEO');
        $this->assertSame('Developer', $choices[0]['options'][0]['label']);
        $this->assertSame('Developer', $this->campaign->fresh()->meta['linkedin_audience_query']['titles']);
        $this->assertEmpty($this->campaign->fresh()->audience['linkedin_facets'] ?? []);
    }

    public function test_failed_manual_linkedin_search_does_not_reopen_old_results(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014',
            'audience' => ['linkedin_facets' => ['titles' => ['urn:li:title:1']]],
            'meta' => ['linkedin_audience_mode' => 'titles', 'linkedin_audience_reviewed' => true,
                'linkedin_audience_query' => ['titles' => 'SEO']],
        ]);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adTargetingEntities*' => Http::response([
            'message' => 'Access denied',
        ], 403)]);

        $applied = app(Answers::class)->applyAll([[
            'field' => 'linkedin_professional_search', 'value' => 'Developer',
        ]]);
        app(Choices::class)->pin();
        (new \ReflectionMethod(app(ChatController::class), 'offerNextStep'))->invoke(app(ChatController::class));
        $choices = app(Choices::class)->drain();

        $this->assertFalse($applied[0]['applied']);
        $this->assertCount(1, $choices);
        $this->assertSame('retry_linkedin_audience', $choices[0]['field']);
        $this->assertSame('Developer', $this->campaign->fresh()->meta['linkedin_audience_query']['titles']);
        $this->assertFalse($this->campaign->fresh()->meta['linkedin_audience_reviewed']);
        $this->assertSame(['titles' => ['urn:li:title:1']], $this->campaign->fresh()->audience['linkedin_facets']);
        Http::assertSent(fn ($request): bool => $request['query'] === 'Developer');
        Http::assertNotSent(fn ($request): bool => $request['query'] === 'SEO');
    }

    public function test_manual_linkedin_search_is_blocked_without_an_inline_search_offer(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014']);
        app(Choices::class)->offer('linkedin_professional_selection', 'Choose verified titles.', [
            ['value' => 'titles|urn:li:title:1', 'label' => 'Verified title'],
        ], multiple: true);
        $this->workspace->rememberChoices(app(Choices::class)->drain());
        Http::preventStrayRequests();

        $controller = app(ChatController::class);
        $applied = (new \ReflectionMethod($controller, 'applyAnswers'))->invoke($controller, [[
            'field' => 'linkedin_professional_search', 'value' => 'Developer',
        ]]);

        $this->assertFalse($applied[0]['applied']);
        Http::assertNothingSent();
    }

    #[TestWith(['titles', 'urn:li:title:9', 'seniorities', 'urn:li:seniority:8'])]
    #[TestWith(['employers', 'urn:li:organization:123', 'industries', 'urn:li:industry:80'])]
    public function test_incompatible_linkedin_filter_selection_preserves_the_existing_audience(string $existingMode, string $existingUrn, string $mode, string $urn): void
    {
        $audience = ['linkedin_facets' => [$existingMode => [$existingUrn]]];
        $this->campaign->update(['ad_account_id' => '556447014', 'audience' => $audience]);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [[
            'urn' => $urn, 'facetUrn' => 'urn:li:adTargetingFacet:'.$mode, 'name' => 'Verified option',
        ]]])]);

        $result = json_decode($this->runTool('campaign__choose_linked_in_resource', [
            'section' => 'audience', 'audience_mode' => $mode,
            'query' => $mode === 'industries' ? 'Software' : null,
            'selection' => [$mode.'|'.$urn],
        ]), true);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('cannot combine', $result['error']);
        $this->assertSame($audience, $this->campaign->fresh()->audience);
        $choices = app(Choices::class)->drain();
        $this->assertSame('linkedin_audience_conflict', $choices[0]['field']);
        $this->assertSame(['replace', 'keep'], array_column($choices[0]['options'], 'value'));
    }

    public function test_adding_company_size_keeps_existing_filters_and_reports_the_estimate(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014', 'locations' => ['countries' => ['US']],
            'audience' => ['linkedin_facets' => ['titles' => ['urn:li:title:9']]],
            'meta' => ['linkedin_audience_labels' => ['urn:li:title:9' => 'Software Engineer']],
        ]);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [
                ['urn' => 'urn:li:staffCountRange:(11,50)', 'facetUrn' => 'urn:li:adTargetingFacet:staffCountRanges', 'name' => '11-50 employees'],
                ['urn' => 'urn:li:staffCountRange:(51,200)', 'facetUrn' => 'urn:li:adTargetingFacet:staffCountRanges', 'name' => '51-200 employees'],
            ]]),
            'https://api.linkedin.com/rest/audienceCounts*' => Http::response(['elements' => [['total' => 44000]]]),
        ]);

        foreach (['urn:li:staffCountRange:(11,50)', 'urn:li:staffCountRange:(51,200)'] as $urn) {
            $result = json_decode($this->runTool('campaign__choose_linked_in_resource', [
                'audience_mode' => 'staffCountRanges', 'selection' => ['staffCountRanges|'.$urn],
            ]), true);
            $this->assertTrue($result['ok'], json_encode($result));
        }
        $campaign = $this->campaign->fresh();
        $menu = app(Choices::class)->drain()[0];

        $this->assertSame([
            'titles' => ['urn:li:title:9'],
            'staffCountRanges' => ['urn:li:staffCountRange:(11,50)', 'urn:li:staffCountRange:(51,200)'],
        ], $campaign->audience['linkedin_facets']);
        $this->assertTrue($campaign->meta['linkedin_audience_reviewed']);
        $this->assertSame(44000, $campaign->meta['linkedin_audience_size']['total']);
        $this->assertSame('linkedin_audience_mode', $menu['field']);
        $this->assertStringContainsString('Job titles: Software Engineer; Company size: 11-50 employees, 51-200 employees', $menu['question']);
        $this->assertStringContainsString('about 44,000 members', $menu['question']);
        Http::assertSent(fn ($request): bool => str_contains($request->url(), 'audienceCounts')
            && str_contains($request->url(), 'urn%3Ali%3AadTargetingFacet%3Atitles:List(urn%3Ali%3Atitle%3A9)'));
        Http::assertNotSent(fn ($request): bool => $request->method() !== 'GET');
    }

    public function test_age_and_gender_choices_carry_the_policy_warning(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014']);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [
            ['urn' => 'urn:li:gender:FEMALE', 'facetUrn' => 'urn:li:adTargetingFacet:genders', 'name' => 'Female'],
        ]])]);

        $result = json_decode($this->runTool('campaign__choose_linked_in_resource', [
            'section' => 'audience', 'audience_mode' => 'genders',
        ]), true);
        $choice = app(Choices::class)->drain()[0];

        $this->assertTrue($result['ok']);
        $this->assertStringContainsString('employment, housing or credit', $result['warning']);
        $this->assertSame('linkedin_professional_selection', $choice['field']);
        $this->assertStringContainsString('employment, housing or credit', $choice['question']);
        $this->assertSame(['genders|urn:li:gender:FEMALE'], array_column($choice['options'], 'value'));
    }

    public function test_an_incompatible_selection_can_replace_the_conflicting_filter_and_keep_the_rest(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'audience' => ['linkedin_facets' => [
            'titles' => ['urn:li:title:9'], 'staffCountRanges' => ['urn:li:staffCountRange:(11,50)'],
        ]]]);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [
            ['urn' => 'urn:li:seniority:5', 'facetUrn' => 'urn:li:adTargetingFacet:seniorities', 'name' => 'Manager'],
        ]])]);

        $refused = json_decode($this->runTool('campaign__choose_linked_in_resource', [
            'audience_mode' => 'seniorities', 'selection' => ['seniorities|urn:li:seniority:5'],
        ]), true);
        app(Choices::class)->drain();
        $replaced = json_decode($this->runTool('campaign__choose_linked_in_resource', ['conflict' => 'replace']), true);

        $this->assertFalse($refused['ok']);
        $this->assertTrue($replaced['ok'], json_encode($replaced));
        $this->assertSame([
            'staffCountRanges' => ['urn:li:staffCountRange:(11,50)'], 'seniorities' => ['urn:li:seniority:5'],
        ], $this->campaign->fresh()->audience['linkedin_facets']);
        $this->assertSame('Manager', $this->campaign->fresh()->meta['linkedin_audience_labels']['urn:li:seniority:5']);
        $this->assertArrayNotHasKey('linkedin_audience_pending', $this->campaign->fresh()->meta);
    }

    public function test_keeping_the_current_audience_discards_the_conflicting_selection(): void
    {
        $audience = ['linkedin_facets' => ['employers' => ['urn:li:organization:1035']]];
        $this->campaign->update(['ad_account_id' => '556447014', 'audience' => $audience, 'meta' => ['linkedin_audience_pending' => [
            'facet' => 'industries', 'urns' => ['urn:li:industry:4'], 'labels' => ['urn:li:industry:4' => 'Software Development'], 'query' => 'Software',
        ]]]);
        Http::preventStrayRequests();

        $applied = app(Answers::class)->applyAll([['field' => 'linkedin_audience_conflict', 'value' => 'keep']]);

        $this->assertTrue($applied[0]['applied']);
        $this->assertSame($audience, $this->campaign->fresh()->audience);
        $this->assertArrayNotHasKey('linkedin_audience_pending', $this->campaign->fresh()->meta);
        $this->assertSame('linkedin_audience_mode', app(Choices::class)->drain()[0]['field']);
        Http::assertNothingSent();
    }

    public function test_saved_filters_can_be_removed_one_at_a_time(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'audience' => ['linkedin_facets' => [
            'titles' => ['urn:li:title:1', 'urn:li:title:2'], 'genders' => ['urn:li:gender:MALE'],
        ]], 'meta' => ['linkedin_audience_labels' => ['urn:li:title:1' => 'Engineer', 'urn:li:title:2' => 'Developer', 'urn:li:gender:MALE' => 'Male']]]);
        Http::preventStrayRequests();

        $this->runTool('campaign__choose_linked_in_resource', ['audience_mode' => 'remove']);
        $choice = app(Choices::class)->drain()[0];
        $removed = app(Answers::class)->applyAll([['field' => 'linkedin_audience_remove', 'value' => ['titles|urn:li:title:1', 'genders|urn:li:gender:MALE']]])[0];
        $refused = json_decode($this->runTool('campaign__choose_linked_in_resource', ['remove' => ['titles|urn:li:title:99']]), true);

        $this->assertSame('linkedin_audience_remove', $choice['field']);
        $this->assertSame(['titles|urn:li:title:1', 'titles|urn:li:title:2', 'genders|urn:li:gender:MALE'], array_column($choice['options'], 'value'));
        $this->assertSame('Job titles: Engineer', $choice['options'][0]['label']);
        $this->assertTrue($removed['applied']);
        $this->assertFalse($refused['ok']);
        $this->assertSame(['titles' => ['urn:li:title:2']], $this->campaign->fresh()->audience['linkedin_facets']);
        $this->assertSame(['urn:li:title:2' => 'Developer'], $this->campaign->fresh()->meta['linkedin_audience_labels']);
    }

    public function test_people_can_be_excluded_by_clicking_through_the_audience_menu(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014', 'locations' => ['countries' => ['US']],
            'audience' => ['linkedin_facets' => ['titles' => ['urn:li:title:9']]],
            'meta' => ['linkedin_audience_labels' => ['urn:li:title:9' => 'Software Engineer']],
        ]);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [
                ['urn' => 'urn:li:industry:4', 'facetUrn' => 'urn:li:adTargetingFacet:industries', 'name' => 'Software Development'],
            ]]),
            'https://api.linkedin.com/rest/audienceCounts*' => Http::response(['elements' => [['total' => 52000]]]),
        ]);

        app(Answers::class)->applyAll([['field' => 'linkedin_audience_mode', 'value' => 'exclude']]);
        $facets = app(Choices::class)->drain()[0];
        app(Answers::class)->applyAll([['field' => 'linkedin_audience_exclude', 'value' => 'industries']]);
        $search = app(Choices::class)->drain()[0];
        $this->runTool('campaign__choose_linked_in_resource', ['query' => 'Software']);
        $results = app(Choices::class)->drain()[0];
        $applied = app(Answers::class)->applyAll([['field' => 'linkedin_professional_exclusion', 'value' => ['industries|urn:li:industry:4']]])[0];
        $menu = app(Choices::class)->drain()[0];
        $campaign = $this->campaign->fresh();

        $this->assertSame('linkedin_audience_exclude', $facets['field']);
        $this->assertSame(LinkedInTargetingFacets::excludableKeys(), array_column($facets['options'], 'value'));
        $this->assertSame('retry_linkedin_audience', $search['field']);
        $this->assertStringContainsString('exclude_facet industries', $search['options'][0]['sends']);
        $this->assertSame('linkedin_professional_exclusion', $results['field']);
        $this->assertStringContainsString('to exclude', $results['question']);
        $this->assertTrue($applied['applied']);
        $this->assertSame(['titles' => ['urn:li:title:9']], $campaign->audience['linkedin_facets']);
        $this->assertSame(['industries' => ['urn:li:industry:4']], $campaign->audience['linkedin_exclusions']);
        $this->assertSame(52000, $campaign->meta['linkedin_audience_size']['total']);
        $this->assertStringContainsString('Job titles: Software Engineer; Excluding Industries: Software Development', $menu['question']);
        $this->assertSame('1 excluded, add more', collect($menu['options'])->firstWhere('value', 'exclude')['hint']);
        Http::assertSent(fn ($request): bool => str_contains($request->url(), 'audienceCounts')
            && str_contains($request->url(), 'exclude:(or:(urn%3Ali%3AadTargetingFacet%3Aindustries:List(urn%3Ali%3Aindustry%3A4)))'));
    }

    public function test_a_value_cannot_be_both_included_and_excluded(): void
    {
        $audience = [
            'linkedin_facets' => ['titles' => ['urn:li:title:9'], 'staffCountRanges' => ['urn:li:staffCountRange:(11,50)']],
            'linkedin_exclusions' => ['industries' => ['urn:li:industry:4']],
        ];
        $this->campaign->update(['ad_account_id' => '556447014', 'audience' => $audience]);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [
            ['urn' => 'urn:li:title:9', 'facetUrn' => 'urn:li:adTargetingFacet:titles', 'name' => 'Software Engineer'],
            ['urn' => 'urn:li:staffCountRange:(1,1)', 'facetUrn' => 'urn:li:adTargetingFacet:staffCountRanges', 'name' => 'Myself Only'],
            ['urn' => 'urn:li:industry:4', 'facetUrn' => 'urn:li:adTargetingFacet:industries', 'name' => 'Software Development'],
        ]])]);

        $sameTitle = json_decode($this->runTool('campaign__choose_linked_in_resource', [
            'exclude_facet' => 'titles', 'query' => 'Software', 'exclude_selection' => ['titles|urn:li:title:9'],
        ]), true);
        $sizeBothWays = json_decode($this->runTool('campaign__choose_linked_in_resource', [
            'exclude_facet' => 'staffCountRanges', 'exclude_selection' => ['staffCountRanges|urn:li:staffCountRange:(1,1)'],
        ]), true);
        app(Choices::class)->drain();
        $includeExcluded = json_decode($this->runTool('campaign__choose_linked_in_resource', [
            'audience_mode' => 'industries', 'query' => 'Software', 'selection' => ['industries|urn:li:industry:4'],
        ]), true);
        $choices = app(Choices::class)->drain();
        $age = json_decode($this->runTool('campaign__choose_linked_in_resource', ['exclude_facet' => 'ageRanges']), true);

        $this->assertStringContainsString('both included and excluded', $sameTitle['error']);
        $this->assertStringContainsString('Company size to be included or excluded, not both', $sizeBothWays['error']);
        $this->assertStringContainsString('both included and excluded', $includeExcluded['error']);
        $this->assertSame('linkedin_audience_mode', $choices[0]['field']);
        $this->assertFalse($age['ok']);
        $this->assertSame($audience, $this->campaign->fresh()->audience);
    }

    public function test_an_exclusion_can_be_removed_without_touching_included_filters(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'audience' => [
            'linkedin_facets' => ['titles' => ['urn:li:title:9']],
            'linkedin_exclusions' => ['industries' => ['urn:li:industry:4']],
        ], 'meta' => ['linkedin_audience_labels' => ['urn:li:title:9' => 'Software Engineer', 'urn:li:industry:4' => 'Software Development']]]);
        Http::preventStrayRequests();

        $this->runTool('campaign__choose_linked_in_resource', ['audience_mode' => 'remove']);
        $choice = app(Choices::class)->drain()[0];
        $removed = app(Answers::class)->applyAll([['field' => 'linkedin_audience_remove', 'value' => ['exclude:industries|urn:li:industry:4']]])[0];
        $campaign = $this->campaign->fresh();

        $this->assertSame(['titles|urn:li:title:9', 'exclude:industries|urn:li:industry:4'], array_column($choice['options'], 'value'));
        $this->assertSame('Excluded Industries: Software Development', $choice['options'][1]['label']);
        $this->assertTrue($removed['applied']);
        $this->assertSame(['linkedin_facets' => ['titles' => ['urn:li:title:9']]], $campaign->audience);
        $this->assertSame(['urn:li:title:9' => 'Software Engineer'], $campaign->meta['linkedin_audience_labels']);
    }

    public function test_companies_and_company_size_cannot_be_included_together(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'audience' => ['linkedin_facets' => ['employers' => ['urn:li:organization:1035']]]]);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adTargetingEntities*' => Http::response(['elements' => [
            ['urn' => 'urn:li:staffCountRange:(11,50)', 'facetUrn' => 'urn:li:adTargetingFacet:staffCountRanges', 'name' => '11-50 employees'],
        ]])]);

        $result = json_decode($this->runTool('campaign__choose_linked_in_resource', [
            'audience_mode' => 'staffCountRanges', 'selection' => ['staffCountRanges|urn:li:staffCountRange:(11,50)'],
        ]), true);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('cannot combine Companies with Company size', $result['error']);
        $this->assertSame('linkedin_audience_conflict', app(Choices::class)->drain()[0]['field']);
    }

    public function test_an_audience_below_linkedins_minimum_needs_confirmation_before_publishing(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014', 'locations' => ['countries' => ['US']],
            'audience' => ['linkedin_facets' => ['titles' => ['urn:li:title:9']]],
        ]);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/audienceCounts*' => Http::response(['elements' => [['total' => 0]]])]);
        $rules = app(LinkedInRules::class);

        $kept = json_decode($this->runTool('campaign__choose_linked_in_resource', ['audience_mode' => 'done']), true);
        $menu = app(Choices::class)->drain()[0];
        $blocked = $rules->additionalProblems($this->campaign->fresh());
        $stepDone = app(LaunchFlow::class)->progress($this->campaign->fresh());

        $this->assertTrue($kept['ok']);
        $this->assertStringContainsString('below 300', $kept['warning']);
        $this->assertSame('confirm_small_audience', $menu['options'][0]['value']);
        $this->assertNotEmpty(array_filter($blocked, fn (string $problem): bool => str_contains($problem, 'below 300')));
        $this->assertFalse(collect($stepDone)->firstWhere('key', 'linkedin_audience')['done']);

        $confirmed = json_decode($this->runTool('campaign__choose_linked_in_resource', ['audience_mode' => 'confirm_small_audience']), true);

        $this->assertTrue($confirmed['ok']);
        $this->assertEmpty(array_filter($rules->additionalProblems($this->campaign->fresh()), fn (string $problem): bool => str_contains($problem, 'below 300')));
        $this->assertTrue(collect(app(LaunchFlow::class)->progress($this->campaign->fresh()))->firstWhere('key', 'linkedin_audience')['done']);
    }

    public function test_a_stale_or_unavailable_estimate_never_blocks_publishing(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014', 'locations' => ['countries' => ['US']],
            'audience' => ['linkedin_facets' => ['titles' => ['urn:li:title:9']]],
            'meta' => ['linkedin_audience_reviewed' => true, 'linkedin_audience_size' => ['total' => 0, 'signature' => 'older-audience', 'checked_at' => now()->toIso8601String()]],
        ]);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/audienceCounts*' => Http::response(['message' => 'Unavailable'], 503)]);

        $kept = json_decode($this->runTool('campaign__choose_linked_in_resource', ['audience_mode' => 'done']), true);

        $this->assertTrue($kept['ok']);
        $this->assertArrayNotHasKey('warning', $kept);
        $this->assertEmpty(array_filter(app(LinkedInRules::class)->additionalProblems($this->campaign->fresh()), fn (string $problem): bool => str_contains($problem, 'below 300')));
    }

    public function test_lead_and_conversion_objectives_require_their_selected_resources(): void
    {
        $rules = app(LinkedInRules::class);
        $this->campaign->update(['objective' => 'LEAD_GENERATION']);
        $this->assertContains('Choose a published LinkedIn Lead Gen Form.', $rules->additionalProblems($this->campaign->fresh()));
        $this->campaign->update(['objective' => 'WEBSITE_CONVERSIONS']);
        $this->assertContains('Choose an enabled LinkedIn conversion rule.', $rules->additionalProblems($this->campaign->fresh()));
    }

    public function test_lead_generation_creative_uses_the_selected_form_and_remains_draft(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77',
            'objective' => 'LEAD_GENERATION', 'meta' => ['linkedin_setup' => ['lead_form' => ['id' => '55']]]]);
        $asset = Asset::create(['kind' => 'image', 'source' => 'upload', 'path' => 'unavailable.png']);
        AssetPlatformRef::create(['asset_id' => $asset->getKey(), 'platform' => 'linkedin',
            'ad_account_id' => '556447014', 'external_id' => 'urn:li:share:123']);
        $ad = $this->campaign->ads()->create(['asset_id' => $asset->getKey(), 'headline' => 'Get a demo',
            'primary_text' => 'Request details.', 'cta' => 'REQUEST_DEMO']);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adAccounts/556447014/creatives' => Http::response([], 201, ['x-restli-id' => 'urn:li:sponsoredCreative:99'])]);

        $creative = app(LinkedInAdapter::class)->createAd($this->campaign, $ad);

        $this->assertSame('urn:li:sponsoredCreative:99', $creative);
        Http::assertSent(fn ($request): bool => $request->data()['leadgenCallToAction'] === ['destination' => 'urn:li:adForm:55', 'label' => 'REQUEST_DEMO']
            && $request->data()['intendedStatus'] === 'DRAFT');
    }

    public function test_linkedin_copy_edit_stages_a_draft_replacement_without_changing_the_original(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        $asset = Asset::create(['kind' => 'image', 'source' => 'upload', 'path' => 'unavailable.png',
            'owner_type' => User::class, 'owner_id' => $this->user->getKey()]);
        AssetPlatformRef::create(['asset_id' => $asset->getKey(), 'platform' => 'linkedin', 'ad_account_id' => '556447014', 'external_id' => 'urn:li:image:123']);
        $original = $this->campaign->ads()->create(['headline' => 'Original', 'primary_text' => 'Body', 'cta' => 'LEARN_MORE',
            'asset_id' => $asset->getKey(), 'external_creative_id' => 'urn:li:sponsoredCreative:99', 'status' => 'published']);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
                'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/creatives/urn*' => Http::response([
                'id' => 'urn:li:sponsoredCreative:99', 'account' => 'urn:li:sponsoredAccount:556447014',
                'campaign' => 'urn:li:sponsoredCampaign:77', 'intendedStatus' => 'ACTIVE',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/creatives' => Http::response([], 201, ['x-restli-id' => 'urn:li:sponsoredCreative:100']),
            'https://api.linkedin.com/rest/posts' => Http::response([], 201, ['x-restli-id' => 'urn:li:share:124']),
        ]);

        $result = app(LinkedInManagement::class)->update($this->campaign, 'creative', '99', ['headline' => 'Replacement'], 'tester');

        $this->assertTrue($result['replacement_staged']);
        $this->assertSame('Original', $original->fresh()->headline);
        $this->assertDatabaseHas('campaign_ads', ['campaign_id' => $this->campaign->getKey(), 'headline' => 'Replacement', 'external_creative_id' => 'urn:li:sponsoredCreative:100']);
        Http::assertNotSent(fn ($request): bool => isset($request->data()['patch']));
        Http::assertSent(fn ($request): bool => str_ends_with($request->url(), '/posts')
            && $request->data()['content']['media']['title'] === 'Replacement'
            && $request->data()['lifecycleState'] === 'PUBLISHED');
    }

    public function test_linkedin_management_refuses_a_creative_from_another_campaign(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
                'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/creatives/*' => Http::response([
                'id' => 'urn:li:sponsoredCreative:99', 'account' => 'urn:li:sponsoredAccount:556447014',
                'campaign' => 'urn:li:sponsoredCampaign:123', 'intendedStatus' => 'ACTIVE',
            ]),
        ]);

        try {
            app(LinkedInManagement::class)->update($this->campaign, 'creative', '99', ['intendedStatus' => 'PAUSED'], 'tester');
            $this->fail('A foreign creative must not be changed.');
        } catch (\RuntimeException $exception) {
            $this->assertStringContainsString('not part of', $exception->getMessage());
        }

        Http::assertNotSent(fn ($request): bool => $request->method() !== 'GET');
    }

    public function test_linkedin_creative_status_is_read_back_before_local_sync(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        $creative = ['id' => 'urn:li:sponsoredCreative:99', 'account' => 'urn:li:sponsoredAccount:556447014',
            'campaign' => 'urn:li:sponsoredCampaign:77'];
        $ad = $this->campaign->ads()->create(['headline' => 'Test headline', 'primary_text' => 'Test body', 'cta' => 'LEARN_MORE',
            'external_creative_id' => 'urn:li:sponsoredCreative:99', 'status' => 'published']);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
                'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/creatives/*' => Http::sequence()
                ->push([...$creative, 'intendedStatus' => 'ACTIVE'])->push([], 204)
                ->push([...$creative, 'intendedStatus' => 'PAUSED']),
        ]);

        $result = app(LinkedInManagement::class)->update($this->campaign, 'creative', '99', ['intendedStatus' => 'PAUSED'], 'tester');

        $this->assertTrue($result['changed']);
        $this->assertSame('paused', $ad->fresh()->status);
        Http::assertSentCount(5);
    }

    public function test_a_different_linkedin_read_back_does_not_advance_local_state(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        $creative = ['id' => 'urn:li:sponsoredCreative:99', 'account' => 'urn:li:sponsoredAccount:556447014',
            'campaign' => 'urn:li:sponsoredCampaign:77'];
        $ad = $this->campaign->ads()->create(['headline' => 'Test headline', 'primary_text' => 'Test body', 'cta' => 'LEARN_MORE',
            'external_creative_id' => 'urn:li:sponsoredCreative:99', 'status' => 'published']);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
                'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/creatives/*' => Http::sequence()
                ->push([...$creative, 'intendedStatus' => 'ACTIVE'])->push([], 204)
                ->push([...$creative, 'intendedStatus' => 'ACTIVE']),
        ]);

        try {
            app(LinkedInManagement::class)->update($this->campaign, 'creative', '99', ['intendedStatus' => 'PAUSED'], 'tester');
            $this->fail('A read-back that differs from the requested status must not be treated as success.');
        } catch (\RuntimeException $exception) {
            $this->assertStringContainsString('read-back value differed', $exception->getMessage());
            $this->assertStringContainsString('may have been normalized', $exception->getMessage());
        }

        $this->assertSame('published', $ad->fresh()->status);
    }

    public function test_registered_linkedin_status_tool_maps_ad_to_creative_intended_status(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        $creative = ['id' => 'urn:li:sponsoredCreative:99', 'account' => 'urn:li:sponsoredAccount:556447014',
            'campaign' => 'urn:li:sponsoredCampaign:77'];
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
                'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/creatives/*' => Http::sequence()
                ->push([...$creative, 'intendedStatus' => 'ACTIVE'])
                ->push([...$creative, 'intendedStatus' => 'ACTIVE'])->push([], 204)
                ->push([...$creative, 'intendedStatus' => 'PAUSED']),
        ]);

        $result = json_decode($this->runTool('campaign__set_entity_status', ['entity_type' => 'ad', 'ids' => ['99'], 'status' => 'PAUSED']), true);

        $this->assertTrue($result['ok'], json_encode($result));
        Http::assertSent(fn ($request): bool => $request->method() === 'POST'
            && $request->data()['patch']['$set'] === ['intendedStatus' => 'PAUSED']
            && $request->hasHeader('X-RestLi-Method', 'PARTIAL_UPDATE'));
    }

    public function test_pending_linkedin_deletion_retains_ids_until_removal_is_confirmed(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        $creative = ['id' => 'urn:li:sponsoredCreative:99', 'account' => 'urn:li:sponsoredAccount:556447014',
            'campaign' => 'urn:li:sponsoredCampaign:77', 'createdAt' => (int) now()->subDay()->getTimestampMs()];
        $ad = $this->campaign->ads()->create(['headline' => 'Test', 'primary_text' => 'Body', 'cta' => 'LEARN_MORE',
            'external_creative_id' => 'urn:li:sponsoredCreative:99', 'status' => 'published']);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAnalytics*' => Http::response(['elements' => [[
                'pivotValues' => ['urn:li:sponsoredCreative:99'], 'costInLocalCurrency' => '0', 'impressions' => 0,
            ]]]),
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
                'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/creatives/*' => Http::sequence()
                ->push([...$creative, 'intendedStatus' => 'ACTIVE'])->push([], 204)
                ->push([...$creative, 'intendedStatus' => 'PENDING_DELETION']),
        ]);

        $result = app(LinkedInManagement::class)->delete($this->campaign, 'creative', '99', 'tester');

        $this->assertTrue($result['pending_deletion']);
        $this->assertFalse($result['deleted']);
        $this->assertSame('urn:li:sponsoredCreative:99', $ad->fresh()->external_creative_id);
        Http::assertNotSent(fn ($request): bool => $request->method() === 'DELETE');
    }

    public function test_starting_a_campaign_cannot_start_its_shared_stopped_group(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published',
            'external_ids' => ['campaign_group_id' => '88'], 'meta' => ['linkedin_setup' => ['campaign_group' => ['id' => '88']]]]);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaignGroups/88' => Http::response([
                'id' => 88, 'account' => 'urn:li:sponsoredAccount:556447014', 'status' => 'PAUSED',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns*' => Http::response(['elements' => [
                ['id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014'],
                ['id' => 78, 'account' => 'urn:li:sponsoredAccount:556447014'],
            ]]),
        ]);

        try {
            app(LinkedInAdapter::class)->activate($this->campaign, ['urn:li:sponsoredCreative:99']);
            $this->fail('A campaign approval must not activate its siblings.');
        } catch (LinkedInException $exception) {
            $this->assertStringContainsString('other campaigns', $exception->getMessage());
        }
        Http::assertNotSent(fn ($request): bool => $request->method() !== 'GET');
    }

    public function test_pausing_a_shared_linkedin_group_does_not_stop_sibling_campaigns(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
                'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014',
                'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaignGroups/88' => Http::response([
                'id' => 88, 'account' => 'urn:li:sponsoredAccount:556447014', 'status' => 'ACTIVE',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns*' => Http::response(['elements' => [
                ['id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014'],
                ['id' => 78, 'account' => 'urn:li:sponsoredAccount:556447014'],
            ]]),
        ]);

        try {
            app(LinkedInManagement::class)->update($this->campaign, 'campaign_group', '88', ['status' => 'PAUSED'], 'tester');
            $this->fail('Pausing a shared group must not stop its sibling campaigns.');
        } catch (\RuntimeException $exception) {
            $this->assertStringContainsString('other campaigns', $exception->getMessage());
        }

        Http::assertNotSent(fn ($request): bool => $request->method() !== 'GET');
    }

    public function test_pausing_a_linkedin_group_with_only_the_focused_campaign_succeeds(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        $groupStatus = 'ACTIVE';
        Http::preventStrayRequests();
        Http::fake(function ($request) use (&$groupStatus) {
            if (str_ends_with($request->url(), '/adCampaigns/77')) {
                return Http::response(['id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014',
                    'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88']);
            }
            if (str_ends_with($request->url(), '/adCampaignGroups/88')) {
                if ($request->method() === 'POST') {
                    $groupStatus = $request->data()['patch']['$set']['status'];

                    return Http::response([], 204);
                }

                return Http::response(['id' => 88, 'account' => 'urn:li:sponsoredAccount:556447014', 'status' => $groupStatus]);
            }

            return Http::response(['elements' => [['id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014']]]);
        });

        $result = app(LinkedInManagement::class)->update($this->campaign, 'campaign_group', '88', ['status' => 'PAUSED'], 'tester');

        $this->assertTrue($result['changed']);
        $this->assertSame('PAUSED', $result['entity']['status']);
        Http::assertSent(fn ($request): bool => $request->method() === 'POST'
            && str_ends_with($request->url(), '/adCampaignGroups/88')
            && $request->data()['patch']['$set'] === ['status' => 'PAUSED']);
    }

    public function test_draft_linkedin_creative_deletion_clears_only_confirmed_local_references(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        $ad = $this->campaign->ads()->create(['headline' => 'Test', 'primary_text' => 'Body', 'cta' => 'LEARN_MORE',
            'external_creative_id' => 'urn:li:sponsoredCreative:99', 'external_ad_id' => 'urn:li:sponsoredCreative:99', 'status' => 'published']);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAnalytics*' => Http::response(['elements' => [[
                'pivotValues' => ['urn:li:sponsoredCreative:99'], 'costInLocalCurrency' => '0', 'impressions' => 0,
            ]]]),
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
                'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/creatives/*' => Http::sequence()->push([
                'id' => 'urn:li:sponsoredCreative:99', 'account' => 'urn:li:sponsoredAccount:556447014',
                'campaign' => 'urn:li:sponsoredCampaign:77', 'intendedStatus' => 'DRAFT', 'createdAt' => (int) now()->subDay()->getTimestampMs(),
            ])->push([], 204),
        ]);

        $result = app(LinkedInManagement::class)->delete($this->campaign, 'creative', '99', 'tester');

        $this->assertTrue($result['deleted']);
        $this->assertNull($ad->fresh()->external_creative_id);
        $this->assertSame('draft', $ad->fresh()->status);
        Http::assertSent(fn ($request): bool => $request->method() === 'DELETE' && $request->hasHeader('X-RestLi-Method', 'DELETE'));
    }

    public function test_linkedin_writes_use_the_scoped_client_even_if_on_returns_a_clone(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        $original = \Mockery::mock(LinkedIn::class);
        $scoped = \Mockery::mock(LinkedIn::class);
        $original->shouldReceive('on')->with($this->campaign->id, 'tester')->andReturn($scoped);
        $original->shouldNotReceive('updateEntity');
        $scoped->shouldReceive('campaign')->with('556447014', '77')->andReturn(['id' => 77]);
        $creative = ['id' => 'urn:li:sponsoredCreative:99', 'campaign' => 'urn:li:sponsoredCampaign:77'];
        $scoped->shouldReceive('creative')->with('556447014', '99')->andReturn([...$creative, 'name' => 'Original'], [...$creative, 'name' => 'Renamed']);
        $scoped->shouldReceive('updateEntity')->once()->with('556447014', 'creative', '99', ['name' => 'Renamed']);

        $result = (new LinkedInManagement($original))->update($this->campaign, 'creative', '99', ['name' => 'Renamed '], 'tester');

        $this->assertTrue($result['changed']);
        $this->assertSame('Renamed', $result['entity']['name']);
    }

    public function test_linkedin_edits_respect_cooldown_and_do_not_bypass_change_history(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        config(['platforms.guardrails.change_cooldown_seconds' => 600]);
        CampaignChange::create(['campaign_id' => $this->campaign->id, 'actor' => 'tester',
            'changes' => ['budget' => ['from' => 20, 'to' => 25]], 'state' => 'applied', 'applied_at' => now()]);
        $management = $this->mock(LinkedInManagement::class);
        $management->shouldReceive('entity')->andReturn(['id' => 'urn:li:sponsoredCreative:99']);
        $management->shouldNotReceive('update');
        Http::preventStrayRequests();

        $result = json_decode($this->runTool('campaign__edit_entity', ['entity_type' => 'creative', 'id' => '99', 'name' => 'Renamed']), true);

        $this->assertFalse($result['ok']);
        $this->assertSame(1, CampaignChange::where('campaign_id', $this->campaign->id)->count());
        Http::assertNothingSent();
    }

    public function test_linkedin_edit_records_applied_change_history(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        config(['platforms.guardrails.change_cooldown_seconds' => 0]);
        $management = $this->mock(LinkedInManagement::class);
        $management->shouldReceive('entity')->andReturn(['id' => 'urn:li:sponsoredCreative:99']);
        $management->shouldReceive('update')->once()->andReturn(['changed' => true, 'id' => '99']);

        $result = json_decode($this->runTool('campaign__edit_entity', ['entity_type' => 'creative', 'id' => '99', 'name' => 'Renamed']), true);

        $this->assertTrue($result['ok']);
        $change = CampaignChange::where('campaign_id', $this->campaign->id)->sole();
        $this->assertSame('applied', $change->state);
        $this->assertSame(['creative:99' => ['name' => 'Renamed']], $change->changes);
        $this->assertNotNull($change->applied_at);
    }

    public function test_linkedin_failed_edit_is_recorded_without_claiming_success(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        config(['platforms.guardrails.change_cooldown_seconds' => 0]);
        $management = $this->mock(LinkedInManagement::class);
        $management->shouldReceive('entity')->andReturn(['id' => '99']);
        $management->shouldReceive('update')->andThrow(new \RuntimeException('LinkedIn did not confirm the edit.'));

        $result = json_decode($this->runTool('campaign__edit_entity', ['entity_type' => 'creative', 'id' => '99', 'name' => 'Renamed']), true);

        $this->assertFalse($result['ok']);
        $change = CampaignChange::where('campaign_id', $this->campaign->id)->sole();
        $this->assertSame('failed', $change->state);
        $this->assertNull($change->applied_at);
        $this->assertStringContainsString('did not confirm', $change->error);
    }

    public function test_linkedin_structure_names_a_missing_group_relationship(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        Http::preventStrayRequests();
        Http::fake(['https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
            'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'status' => 'DRAFT',
        ])]);

        $result = json_decode($this->runTool('campaign__list_campaign_structure'), true);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('without a campaignGroup relationship', $result['error']);
        Http::assertSentCount(1);
    }

    public function test_linkedin_structure_bounds_display_even_when_the_provider_ignores_page_size(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
                'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'status' => 'DRAFT', 'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaignGroups/88' => Http::response([
                'id' => 88, 'account' => 'urn:li:sponsoredAccount:556447014', 'status' => 'DRAFT',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/creatives*' => Http::response(['elements' => array_fill(0, 51, [
                'id' => 'urn:li:sponsoredCreative:99', 'account' => 'urn:li:sponsoredAccount:556447014', 'campaign' => 'urn:li:sponsoredCampaign:77',
            ])]),
        ]);

        $result = json_decode($this->runTool('campaign__list_campaign_structure'), true);

        $this->assertTrue($result['ok']);
        $this->assertTrue($result['truncated']);
        $this->assertCount(50, $result['creatives']);
    }

    public function test_linkedin_structure_reads_group_and_creative_relationships(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014', 'external_campaign_id' => '77', 'status' => 'published']);
        Http::preventStrayRequests();
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaigns/77' => Http::response([
                'id' => 77, 'account' => 'urn:li:sponsoredAccount:556447014', 'status' => 'DRAFT',
                'campaignGroup' => 'urn:li:sponsoredCampaignGroup:88',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/adCampaignGroups/88' => Http::response([
                'id' => 88, 'account' => 'urn:li:sponsoredAccount:556447014', 'status' => 'DRAFT',
            ]),
            'https://api.linkedin.com/rest/adAccounts/556447014/creatives*' => Http::response([
                'elements' => [['id' => 'urn:li:sponsoredCreative:99', 'campaign' => 'urn:li:sponsoredCampaign:77',
                    'account' => 'urn:li:sponsoredAccount:556447014', 'intendedStatus' => 'DRAFT']],
            ]),
        ]);

        $result = json_decode($this->runTool('campaign__list_campaign_structure'), true);

        $this->assertTrue($result['ok'], json_encode($result));
        $this->assertSame(88, $result['campaign_group']['id']);
        $this->assertSame('urn:li:sponsoredCreative:99', $result['creatives'][0]['id']);
        $this->assertSame('DRAFT', $this->campaign->fresh()->meta['linkedin_state']['campaign_status']);
        Http::assertSentCount(3);
    }

    public function test_verify_ad_account_for_linkedin(): void
    {
        Http::fake([
            'https://api.linkedin.com/rest/adAccounts/556447014' => Http::response([
                'id' => 556447014,
                'name' => 'AdMedia Products',
                'currency' => 'USD',
                'status' => 'ACTIVE',
            ], 200),
        ]);

        $result = $this->runTool('campaign__verify_ad_account', [
            'ad_account_id' => '556447014',
        ]);
        $json = json_decode($result, true);

        $this->assertTrue($json['ok']);
        $this->assertEquals('556447014', $json['ad_account_id']);

        $this->campaign->refresh();
        $this->assertEquals('556447014', $this->campaign->ad_account_id);
        $this->assertEquals('USD', $this->campaign->currency);
    }

    public function test_targeting_offers_and_accepts_linkedin_placements(): void
    {
        // 1. Placements lead; the coordinator asks for countries afterwards.
        $result = $this->runTool('campaign__set_targeting', []);
        $json = json_decode($result, true);
        $this->assertTrue($json['ok']);
        $this->assertSame(['placements'], array_column(app(Choices::class)->all(), 'field'));

        // 2. Setting country and linkedin placements
        $result = $this->runTool('campaign__set_targeting', [
            'countries' => ['US'],
            'placements' => ['linkedin_feed'],
        ]);
        $json = json_decode($result, true);

        $this->assertTrue($json['ok']);
        $this->assertEquals(['US'], $json['countries']);
        $this->assertEquals(['linkedin_feed'], $json['placements']);

        $this->campaign->refresh();
        $this->assertEquals(['countries' => ['US']], $this->campaign->locations);
        $this->assertEquals(['linkedin_feed'], $this->campaign->placements);
    }

    public function test_bidding_offers_and_accepts_linkedin_strategies(): void
    {
        // 1. Offering strategies for LinkedIn
        $result = $this->runTool('campaign__set_bidding', []);
        $json = json_decode($result, true);
        $this->assertTrue($json['ok']);

        $all = app(Choices::class)->all();
        $this->assertNotEmpty($all);
        $this->assertEquals('bid_strategy', $all[0]['field']);
        $values = array_column($all[0]['options'], 'value');
        $this->assertContains('AUTOMATED_BID', $values);
        $this->assertContains('TARGET_COST', $values);
        $this->assertContains('MAXIMUM_BID', $values);

        // 2. Setting AUTOMATED_BID
        $result = $this->runTool('campaign__set_bidding', [
            'strategy' => 'AUTOMATED_BID',
        ]);
        $json = json_decode($result, true);

        $this->assertTrue($json['ok']);
        $this->assertEquals('AUTOMATED_BID', $json['strategy']);

        $this->campaign->refresh();
        $this->assertEquals('AUTOMATED_BID', $this->campaign->bid_strategy);
    }

    public function test_launch_flow_requires_linkedin_page_but_not_meta_special_ad_categories(): void
    {
        $flow = app(LaunchFlow::class);
        $progress = collect($flow->progress($this->campaign))->keyBy('key');

        $this->assertTrue($progress->has('page'), 'LinkedIn requires its own publishing Page.');
        $this->assertFalse($progress->has('special_ad_categories'), 'LinkedIn campaigns must not require Special Ad Categories');
    }

    /**
     * A Facebook Page is Meta's requirement, not LinkedIn's.
     *
     * The ad is given a creative that has reached the platform, which it needs
     * anyway. This used to pass with no creative at all, because the gate
     * exempted LinkedIn from the creative check, and the assertion that the
     * Page is not required was quietly also asserting that an ad with nothing
     * to show is ready to publish. LinkedInRules::requiresCreativeAsset() says
     * otherwise, and the publisher had nothing to sponsor.
     */
    public function test_publish_gate_requires_a_linkedin_page(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014',
            'landing_url' => 'https://example.com/product',
            'budget' => 50.00,
            'budget_mode' => 'daily',
            'bid_strategy' => 'AUTOMATED_BID',
            'locations' => ['countries' => ['US']],
            'placements' => ['linkedin_feed'],
        ]);

        $asset = Asset::create([
            'owner_type' => User::class,
            'owner_id' => $this->user->id,
            'kind' => 'image',
            'source' => 'upload',
            'disk' => 'local',
            'path' => 'creatives/test.png',
            'original_name' => 'test.png',
        ]);

        AssetPlatformRef::create([
            'asset_id' => $asset->id,
            'platform' => 'linkedin',
            'ad_account_id' => '556447014',
            'external_id' => 'urn:li:image:C4E10AQ',
        ]);

        CampaignAd::create([
            'campaign_id' => $this->campaign->id,
            'asset_id' => $asset->id,
            'headline' => 'Scale your growth today',
            'primary_text' => 'Discover how our platform accelerates revenue.',
            'cta' => 'LEARN_MORE',
        ]);

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

        $this->assertContains('Page not selected', $problems);
        $this->campaign->update(['page_id' => '123']);
        $this->assertEmpty(app(PublishGate::class)->check($this->campaign->fresh()));
    }

    /** And an ad with nothing to show is still refused. */
    public function test_publish_gate_refuses_a_linkedin_ad_with_no_creative(): void
    {
        $this->campaign->update([
            'ad_account_id' => '556447014',
            'landing_url' => 'https://example.com/product',
            'budget' => 50.00,
            'budget_mode' => 'daily',
            'bid_strategy' => 'AUTOMATED_BID',
            'locations' => ['countries' => ['US']],
            'placements' => ['linkedin_feed'],
        ]);

        CampaignAd::create([
            'campaign_id' => $this->campaign->id,
            'headline' => 'Scale your growth today',
            'primary_text' => 'Discover how our platform accelerates revenue.',
            'cta' => 'LEARN_MORE',
        ]);

        $this->assertStringContainsString(
            'creative not uploaded',
            implode('; ', app(PublishGate::class)->check($this->campaign)),
        );
    }

    public function test_review_assets_uploads_image_to_linkedin(): void
    {
        $this->campaign->update(['ad_account_id' => '556447014']);

        Storage::fake('local');
        Storage::disk('local')->put('creatives/test.png', 'fake-image-bytes');

        $asset = Asset::create([
            'owner_type' => User::class,
            'owner_id' => $this->user->id,
            'kind' => 'image',
            'source' => 'upload',
            'disk' => 'local',
            'path' => 'creatives/test.png',
            'original_name' => 'test.png',
            'mime' => 'image/png',
            'bytes' => 100,
            'checksum' => 'checksum123',
        ]);

        $this->workspace->produced($asset, focus: false);

        Http::fake([
            'https://api.linkedin.com/rest/images?action=initializeUpload' => Http::response([
                'value' => [
                    'uploadUrl' => 'https://api.linkedin.com/mock-upload-url',
                    'image' => 'urn:li:image:MOCK123456',
                ],
            ], 200),
            'https://api.linkedin.com/mock-upload-url' => Http::response('', 201),
        ]);

        $result = $this->runTool('campaign__review_assets');
        $json = json_decode($result, true);

        $this->assertTrue($json['ok']);
        $this->assertCount(1, $json['just_uploaded']);
        $this->assertEquals('urn:li:image:MOCK123456', $json['just_uploaded'][0]['reference']);

        $ref = $asset->refFor('linkedin', '556447014');
        $this->assertNotNull($ref);
        $this->assertEquals('urn:li:image:MOCK123456', $ref->reference());
    }
}
