<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\NamespacedTool;
use App\Agent\ToolRegistry;
use App\Agent\Tools\Campaign\EditLinkedInCampaign;
use App\Agent\Workspace;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Factory;
use Illuminate\Http\Client\Request as HttpRequest;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * A live LinkedIn campaign edits its own budget, bid, and end date.
 * A Meta campaign is refused.
 */
class EditLinkedInCampaignTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

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

        config([
            'platforms.linkedin.token' => 'test-token',
            'platforms.linkedin.publish_enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['556447014'],
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_daily_budget' => 500,
        ]);

        $this->user = User::factory()->create();
        $this->actingAs($this->user);
        app(Workspace::class)->bindTo('conv-linkedin-edit');
        app(Workspace::class)->ownedBy($this->user);
    }

    public function test_a_live_linkedin_campaign_offers_the_four_fields(): void
    {
        $this->focus($this->linkedin());
        $this->fakeLinkedIn();

        $result = $this->edit([]);

        $this->assertTrue($result['ok']);
        $choice = app(Choices::class)->all()[0];
        $this->assertSame('linkedin_edit', $choice['field']);
        $this->assertSame(
            ['Ad set name', 'Daily budget', 'Bidding', 'Target cost', 'Schedule', 'Placements', 'Locations', 'Target audience'],
            array_column($choice['options'], 'label'),
        );
        Http::assertNothingSent();
    }

    public function test_an_edit_with_no_named_id_uses_the_panel_ad_set(): void
    {
        $campaign = $this->linkedin([
            'external_campaign_id' => 'urn:li:sponsoredCampaign:870120596',
            'external_ids' => [
                'campaign_id' => '678118596',
                'campaign_group_id' => '1192894936',
            ],
        ]);
        $this->focus($campaign);
        $this->fakeLinkedIn();

        $result = $this->edit(['name' => 'ARB-Spring sale']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame([
            'campaign_id' => '1192894936',
            'ad_set_id' => '678118596',
        ], $result['panel']);
        $this->assertStringContainsString('right-hand panel', $result['panel_note']);
        $this->assertSame('urn:li:sponsoredCampaign:870120596', $campaign->fresh()->external_campaign_id);

        $urls = [];
        foreach (Http::recorded() as [$request]) {
            if (str_contains($request->url(), 'adCampaigns')) {
                $urls[] = $request->url();
            }
        }

        $this->assertNotEmpty($urls);
        foreach ($urls as $url) {
            $this->assertStringContainsString('/adCampaigns/678118596', $url);
            $this->assertStringNotContainsString('870120596', $url);
        }
    }

    public function test_a_new_ad_set_name_is_sent_to_linkedin(): void
    {
        $campaign = $this->linkedin();
        $this->focus($campaign);
        $this->fakeLinkedIn();

        $result = $this->edit(['name' => 'ARB-Spring sale']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('Spring sale', $campaign->fresh()->name);
        $this->assertSame('ARB-Spring sale', $this->sentPatch()['name'] ?? null);
    }

    public function test_a_new_budget_is_sent_only_to_linkedin(): void
    {
        $campaign = $this->linkedin();
        $this->focus($campaign);
        $this->fakeLinkedIn();

        $result = $this->edit(['budget' => 80]);

        $this->assertTrue($result['ok']);
        $this->assertSame(80.0, (float) $campaign->fresh()->budget);
        $this->assertSame('80.00', $this->sentPatch()['dailyBudget']['amount'] ?? null);
    }

    public function test_a_meta_campaign_is_refused(): void
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Meta sale',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'external_campaign_id' => '120',
            'budget' => 25,
            'budget_mode' => 'daily',
            'currency' => 'USD',
        ]);
        $this->focus($campaign);
        Http::fake();

        $result = $this->edit(['budget' => 40]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('only for a LinkedIn campaign', $result['error']);
        $this->assertSame(25.0, (float) $campaign->fresh()->budget);
        Http::assertNothingSent();
    }

    public function test_a_fixed_linkedin_field_is_refused(): void
    {
        $this->focus($this->linkedin());
        $this->fakeLinkedIn();

        $result = $this->edit(['landing_url' => 'https://example.com']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('landing_url', $result['error']);
        Http::assertNothingSent();
    }

    public function test_an_empty_placement_list_offers_both(): void
    {
        $this->focus($this->linkedin());
        $this->fakeLinkedIn();

        $result = $this->edit(['placements' => []]);

        $this->assertTrue($result['ok']);
        $choice = app(Choices::class)->all()[0];
        $this->assertSame('linkedin_placements', $choice['field']);
        $this->assertTrue($choice['multiple']);
        $this->assertSame(['LinkedIn feed', 'Audience Network'], array_column($choice['options'], 'label'));
        Http::assertNothingSent();
    }

    public function test_an_empty_placement_list_does_not_ask_for_approval(): void
    {
        $this->focus($this->linkedin());
        $tool = app(EditLinkedInCampaign::class);
        $gate = new \ReflectionMethod($tool, 'needsApproval');

        $this->assertFalse($gate->invoke($tool, new Request(['placements' => []])));
        $this->assertFalse($gate->invoke($tool, new Request(['location_query' => 'new york'])));
        $this->assertFalse($gate->invoke($tool, new Request([
            'location_query' => 'california',
            'keep_locations' => ['urn:li:geo:105080838'],
        ])));
        $this->assertFalse($gate->invoke($tool, new Request(['audience' => []])));
        $this->assertFalse($gate->invoke($tool, new Request(['audience_facet' => 'titles', 'audience_query' => 'engineer'])));
        $this->assertNotFalse($gate->invoke($tool, new Request(['audience_expansion' => true])));
        $this->assertNotFalse($gate->invoke($tool, new Request(['locations' => ['urn:li:geo:105080838']])));
        $this->assertNotFalse($gate->invoke($tool, new Request(['placements' => ['linkedin_feed', 'linkedin_audience_network']])));
        $this->assertNotFalse($gate->invoke($tool, new Request(['budget' => 80])));
    }

    public function test_both_placements_turn_on_audience_network(): void
    {
        $campaign = $this->linkedin(['placements' => ['linkedin_feed']]);
        $this->focus($campaign);
        $this->fakeLinkedIn();

        $result = $this->edit(['placements' => ['linkedin_audience_network', 'linkedin_feed']]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['linkedin_feed', 'linkedin_audience_network'], $campaign->fresh()->placements);
        $this->assertTrue($this->sentPatch()['offsiteDeliveryEnabled'] ?? false);
    }

    public function test_the_feed_alone_turns_audience_network_off(): void
    {
        $campaign = $this->linkedin(['placements' => ['linkedin_feed', 'linkedin_audience_network']]);
        $this->focus($campaign);
        $this->fakeLinkedIn();

        $result = $this->edit(['placements' => ['linkedin_feed']]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame(['linkedin_feed'], $campaign->fresh()->placements);
        $this->assertFalse($this->sentPatch()['offsiteDeliveryEnabled'] ?? true);
    }

    public function test_a_meta_placement_is_refused_on_linkedin(): void
    {
        $campaign = $this->linkedin(['placements' => ['linkedin_feed']]);
        $this->focus($campaign);
        $this->fakeLinkedIn();

        $result = $this->edit(['placements' => ['facebook']]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('linkedin_feed', $result['error']);
        $this->assertSame(['linkedin_feed'], $campaign->fresh()->placements);
        Http::assertNothingSent();
    }

    public function test_a_place_search_offers_linkedin_matches(): void
    {
        $this->focus($this->linkedin());
        $this->fakeLocations();

        $result = $this->edit(['location_query' => 'new york']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $choice = app(Choices::class)->all()[0];
        $this->assertSame('linkedin_locations', $choice['field']);
        $this->assertTrue($choice['multiple']);
        $this->assertSame(
            ['New York, United States', 'New York City Metropolitan Area'],
            array_column($choice['options'], 'label'),
        );
        $this->assertSame(
            ['urn:li:geo:105080838', 'urn:li:geo:90000070'],
            array_column($choice['options'], 'value'),
        );
        $this->assertFalse($this->postedCampaign());
    }

    public function test_another_location_search_keeps_places_already_chosen(): void
    {
        $this->focus($this->linkedin());
        $this->fakeLocations();

        $result = $this->edit([
            'location_query' => 'california',
            'keep_locations' => ['urn:li:geo:105080838'],
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $choice = app(Choices::class)->all()[0];
        $this->assertSame('linkedin_locations', $choice['field']);
        $this->assertTrue($choice['options'][0]['selected']);
        $this->assertSame('urn:li:geo:105080838', $choice['options'][0]['value']);
        $this->assertSame(
            ['New York, United States', 'California, United States'],
            array_column($choice['options'], 'label'),
        );
        $this->assertFalse($this->postedCampaign());
    }

    public function test_an_unknown_kept_place_is_not_searched(): void
    {
        $this->focus($this->linkedin());
        $this->fakeLocations();

        $result = $this->edit([
            'location_query' => 'california',
            'keep_locations' => ['urn:li:geo:1'],
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('urn:li:geo:1', $result['error']);
        $this->assertSame([], app(Choices::class)->all());
        $this->assertFalse($this->postedCampaign());
    }

    public function test_chosen_places_replace_only_the_location_facet(): void
    {
        $campaign = $this->linkedin();
        $this->focus($campaign);
        $this->fakeLocations();

        $result = $this->edit(['locations' => ['urn:li:geo:105080838', 'urn:li:geo:90000070']]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $criteria = $this->sentPatch()['targetingCriteria'] ?? [];
        $and = $criteria['include']['and'] ?? [];
        $this->assertSame(
            ['urn:li:geo:105080838', 'urn:li:geo:90000070'],
            $and[0]['or']['urn:li:adTargetingFacet:locations'] ?? null,
        );
        $this->assertSame(
            ['urn:li:locale:en_US'],
            $and[1]['or']['urn:li:adTargetingFacet:interfaceLocales'] ?? null,
        );
        $this->assertSame(
            ['urn:li:seniority:3'],
            $and[2]['or']['urn:li:adTargetingFacet:seniorities'] ?? null,
        );
        $this->assertSame([
            ['urn' => 'urn:li:geo:105080838', 'name' => 'New York, United States'],
            ['urn' => 'urn:li:geo:90000070', 'name' => 'New York City Metropolitan Area'],
        ], $campaign->fresh()->locations['linkedin_places']);
    }

    public function test_a_location_id_linkedin_does_not_know_is_not_sent(): void
    {
        $campaign = $this->linkedin();
        $this->focus($campaign);
        $this->fakeLocations();

        $result = $this->edit(['locations' => ['urn:li:geo:1']]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('urn:li:geo:1', $result['error']);
        $this->assertFalse($this->postedCampaign());
        $this->assertNull($campaign->fresh()->locations['linkedin_places'] ?? null);
    }

    public function test_the_audience_menu_offers_attributes_and_expansion(): void
    {
        $this->focus($this->linkedin());
        $this->fakeLinkedIn();

        $result = $this->edit(['audience' => []]);

        $this->assertTrue($result['ok']);
        $labels = array_column(app(Choices::class)->all()[0]['options'], 'label');
        $this->assertContains('Job titles', $labels);
        $this->assertContains('Skills', $labels);
        $this->assertContains('Degrees', $labels);
        $this->assertContains('Fields of study', $labels);
        $this->assertContains('Member schools', $labels);
        $this->assertContains('Member interests', $labels);
        $this->assertContains('Member groups', $labels);
        $this->assertContains('Member traits', $labels);
        $this->assertContains('Job functions', $labels);
        $this->assertContains('Years of experience', $labels);
        $this->assertContains('Company growth rate', $labels);
        $this->assertContains('Company category', $labels);
        $this->assertContains('Company followers', $labels);
        $this->assertNotContains('Device', $labels);
        $this->assertContains('Matched audiences', $labels);
        $this->assertContains('Turn on Audience Expansion', $labels);
        Http::assertNothingSent();
    }

    public function test_a_job_title_search_offers_linkedin_matches(): void
    {
        $this->focus($this->linkedin());
        $this->fakeAudience();

        $result = $this->edit(['audience_facet' => 'titles', 'audience_query' => 'engineer']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $choice = app(Choices::class)->all()[0];
        $this->assertSame('linkedin_audience', $choice['field']);
        $this->assertTrue($choice['multiple']);
        $this->assertSame(['Software Engineer'], array_column($choice['options'], 'label'));
        $this->assertFalse($this->postedCampaign());
    }

    public function test_a_job_title_is_added_without_removing_locations(): void
    {
        $campaign = $this->linkedin();
        $this->focus($campaign);
        $this->fakeAudience();

        $result = $this->edit(['audience_facet' => 'titles', 'audience_include' => ['urn:li:title:9']]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $and = $this->sentPatch()['targetingCriteria']['include']['and'] ?? [];
        $facets = [];
        foreach ($and as $clause) {
            $facets += $clause['or'] ?? [];
        }
        $this->assertSame(['urn:li:geo:103644278'], $facets['urn:li:adTargetingFacet:locations'] ?? null);
        $this->assertSame(['urn:li:locale:en_US'], $facets['urn:li:adTargetingFacet:interfaceLocales'] ?? null);
        $this->assertSame(['urn:li:title:9'], $facets['urn:li:adTargetingFacet:titles'] ?? null);
        $this->assertSame(['urn:li:title:9'], $campaign->fresh()->audience['linkedin_facets']['titles']);
    }

    public function test_audience_expansion_is_sent_on_its_own(): void
    {
        $campaign = $this->linkedin();
        $this->focus($campaign);
        $this->fakeLinkedIn();

        $result = $this->edit(['audience_expansion' => true]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertTrue($this->sentPatch()['audienceExpansionEnabled'] ?? false);
        $this->assertArrayNotHasKey('targetingCriteria', $this->sentPatch());
        $this->assertTrue($campaign->fresh()->meta['linkedin_audience_expansion']);
    }

    public function test_a_matched_audience_uses_its_segment_facet(): void
    {
        $campaign = $this->linkedin();
        $this->focus($campaign);
        $this->fakeAudience();

        $result = $this->edit(['matched_audiences' => ['urn:li:adSegment:42'], 'matched_operation' => 'include']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $and = $this->sentPatch()['targetingCriteria']['include']['and'] ?? [];
        $facets = [];
        foreach ($and as $clause) {
            $facets += $clause['or'] ?? [];
        }
        $this->assertSame(['urn:li:adSegment:42'], $facets['urn:li:adTargetingFacet:dynamicSegments'] ?? null);
        $this->assertSame(['urn:li:geo:103644278'], $facets['urn:li:adTargetingFacet:locations'] ?? null);
        $this->assertSame('Site visitors', $campaign->fresh()->audience['linkedin_matched'][0]['name']);
    }

    public function test_years_of_experience_accepts_at_most_two_values(): void
    {
        $this->focus($this->linkedin());
        Http::preventStrayRequests();

        $result = $this->edit([
            'audience_facet' => 'yearsOfExperienceRanges',
            'audience_include' => ['urn:li:yearsOfExperience:1', 'urn:li:yearsOfExperience:5', 'urn:li:yearsOfExperience:12'],
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('one or two', $result['error']);
        Http::assertNothingSent();
    }

    public function test_member_groups_cannot_be_excluded(): void
    {
        $this->focus($this->linkedin());
        Http::preventStrayRequests();

        $result = $this->edit([
            'audience_facet' => 'groups',
            'audience_exclude' => true,
            'audience_include' => ['urn:li:group:1'],
        ]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Member groups', $result['error']);
        Http::assertNothingSent();
    }

    public function test_a_job_title_is_refused_when_seniority_is_already_targeted(): void
    {
        $campaign = $this->linkedin();
        $this->focus($campaign);
        $this->fakeAudience(seniority: true);

        $result = $this->edit(['audience_facet' => 'titles', 'audience_include' => ['urn:li:title:9']]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Job titles', $result['error']);
        $this->assertStringContainsString('Seniorities', $result['error']);
        $this->assertFalse($this->postedCampaign());
    }

    public function test_an_end_date_keeps_the_recorded_start(): void
    {
        $campaign = $this->linkedin(['starts_at' => '2026-11-01 00:00:00']);
        $this->focus($campaign);
        $this->fakeLinkedIn();

        $result = $this->edit(['ends_at' => '2026-12-01']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $schedule = $this->sentPatch()['runSchedule'] ?? [];
        $this->assertSame(
            $campaign->starts_at->getTimestamp() * 1000,
            $schedule['start'] ?? null,
        );
        $this->assertArrayHasKey('end', $schedule);
    }

    private function linkedin(array $extra = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Stock Prices',
            'platform' => 'linkedin',
            'status' => 'published',
            'objective' => 'WEBSITE_VISITS',
            'ad_account_id' => '556447014',
            'external_campaign_id' => 'urn:li:sponsoredCampaign:77',
            'budget' => 50,
            'budget_mode' => 'daily',
            'currency' => 'USD',
            'bid_strategy' => 'TARGET_COST',
            'bid_amount' => 1,
            ...$extra,
        ]);
        app(Workspace::class)->produced($campaign);

        return $campaign;
    }

    private function focus(Campaign $campaign): void
    {
        app(Workspace::class)->focusOn($campaign);
    }

    private function fakeLinkedIn(): void
    {
        Http::swap(new Factory);
        Http::preventStrayRequests();
        $profile = [
            'id' => 77,
            'account' => 'urn:li:sponsoredAccount:556447014',
            'name' => 'ARB-Stock Prices',
            'status' => 'PAUSED',
            'dailyBudget' => ['amount' => '50.00', 'currencyCode' => 'USD'],
            'unitCost' => ['amount' => '1.00', 'currencyCode' => 'USD'],
            'optimizationTargetType' => 'TARGET_COST_PER_CLICK',
        ];
        Http::fake(function (HttpRequest $request) use (&$profile) {
            if ($request->method() === 'GET') {
                return Http::response($profile);
            }

            $profile = array_replace_recursive($profile, $request->data()['patch']['$set'] ?? []);

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

    /** @return array<string, mixed> */
    private function sentPatch(): array
    {
        foreach (Http::recorded() as [$request]) {
            if ($request->method() === 'POST' && str_contains($request->url(), 'adCampaigns')) {
                return $request->data()['patch']['$set'] ?? [];
            }
        }

        return [];
    }

    private function fakeAudience(bool $seniority = false): void
    {
        Http::swap(new Factory);
        Http::preventStrayRequests();
        $profile = [
            'id' => 77,
            'account' => 'urn:li:sponsoredAccount:556447014',
            'name' => 'ARB-Stock Prices',
            'status' => 'PAUSED',
            'dailyBudget' => ['amount' => '50.00', 'currencyCode' => 'USD'],
            'unitCost' => ['amount' => '1.00', 'currencyCode' => 'USD'],
            'optimizationTargetType' => 'TARGET_COST_PER_CLICK',
            'targetingCriteria' => [
                'include' => ['and' => [
                    ['or' => ['urn:li:adTargetingFacet:locations' => ['urn:li:geo:103644278']]],
                    ['or' => ['urn:li:adTargetingFacet:'.($seniority ? 'seniorities' : 'interfaceLocales') => [$seniority ? 'urn:li:seniority:3' : 'urn:li:locale:en_US']]],
                ]],
            ],
        ];
        Http::fake(function (HttpRequest $request) use (&$profile) {
            $url = $request->url();

            if (str_contains($url, 'adTargetingEntities') && str_contains($url, 'typeahead')) {
                return Http::response(['elements' => [
                    ['urn' => 'urn:li:title:9', 'name' => 'Software Engineer', 'facetUrn' => 'urn:li:adTargetingFacet:titles'],
                ]]);
            }

            if (str_contains($url, 'q=urns')) {
                return Http::response(['elements' => [
                    ['urn' => 'urn:li:title:9', 'name' => 'Software Engineer', 'facetUrn' => 'urn:li:adTargetingFacet:titles'],
                ]]);
            }

            if (str_contains($url, 'adSegments')) {
                return Http::response(['elements' => [
                    ['id' => 42, 'name' => 'Site visitors', 'type' => 'RETARGETING', 'status' => 'READY', 'account' => 'urn:li:sponsoredAccount:556447014'],
                ]]);
            }

            if ($request->method() === 'GET') {
                return Http::response($profile);
            }

            $set = $request->data()['patch']['$set'] ?? [];

            if (isset($set['targetingCriteria'])) {
                $profile['targetingCriteria'] = $set['targetingCriteria'];
                unset($set['targetingCriteria']);
            }

            $profile = array_replace_recursive($profile, $set);

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

    private function postedCampaign(): bool
    {
        foreach (Http::recorded() as [$request]) {
            if ($request->method() === 'POST' && str_contains($request->url(), 'adCampaigns')) {
                return true;
            }
        }

        return false;
    }

    private function fakeLocations(): void
    {
        Http::swap(new Factory);
        Http::preventStrayRequests();
        $profile = [
            'id' => 77,
            'account' => 'urn:li:sponsoredAccount:556447014',
            'name' => 'ARB-Stock Prices',
            'status' => 'PAUSED',
            'dailyBudget' => ['amount' => '50.00', 'currencyCode' => 'USD'],
            'unitCost' => ['amount' => '1.00', 'currencyCode' => 'USD'],
            'optimizationTargetType' => 'TARGET_COST_PER_CLICK',
            'targetingCriteria' => [
                'include' => ['and' => [
                    ['or' => ['urn:li:adTargetingFacet:locations' => ['urn:li:geo:103644278']]],
                    ['or' => ['urn:li:adTargetingFacet:interfaceLocales' => ['urn:li:locale:en_US']]],
                    ['or' => ['urn:li:adTargetingFacet:seniorities' => ['urn:li:seniority:3']]],
                ]],
            ],
        ];
        Http::fake(function (HttpRequest $request) use (&$profile) {
            $url = $request->url();

            if (str_contains($url, 'adTargetingEntities') && str_contains($url, 'typeahead')) {
                if (str_contains(rawurldecode($url), 'california')) {
                    return Http::response(['elements' => [
                        ['urn' => 'urn:li:geo:102095887', 'name' => 'California, United States', 'facetUrn' => 'urn:li:adTargetingFacet:locations'],
                    ]]);
                }

                return Http::response(['elements' => [
                    ['urn' => 'urn:li:geo:105080838', 'name' => 'New York, United States', 'facetUrn' => 'urn:li:adTargetingFacet:locations'],
                    ['urn' => 'urn:li:geo:90000070', 'name' => 'New York City Metropolitan Area', 'facetUrn' => 'urn:li:adTargetingFacet:locations'],
                    ['urn' => 'urn:li:country:us', 'name' => 'United States', 'facetUrn' => 'urn:li:adTargetingFacet:locations'],
                ]]);
            }

            if (str_contains($url, 'q=urns')) {
                return Http::response(['elements' => [
                    ['urn' => 'urn:li:geo:105080838', 'name' => 'New York, United States', 'facetUrn' => 'urn:li:adTargetingFacet:locations'],
                    ['urn' => 'urn:li:geo:90000070', 'name' => 'New York City Metropolitan Area', 'facetUrn' => 'urn:li:adTargetingFacet:locations'],
                ]]);
            }

            if ($request->method() === 'GET') {
                return Http::response($profile);
            }

            $set = $request->data()['patch']['$set'] ?? [];

            if (isset($set['targetingCriteria'])) {
                $profile['targetingCriteria'] = $set['targetingCriteria'];
                unset($set['targetingCriteria']);
            }

            $profile = array_replace_recursive($profile, $set);

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

    private function tool(): NamespacedTool
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__edit_linkedin_campaign');

        $this->assertNotNull($tool);

        return $tool;
    }

    /** @param  array<string, mixed>  $arguments */
    private function edit(array $arguments): array
    {
        return json_decode((string) $this->tool()->handle(new Request($arguments)), true);
    }
}
