<?php

namespace Tests\Feature;

use App\Agent\Tools\Campaign\OpenCampaign;
use App\Agent\Workspace;
use App\Campaigns\CampaignImporter;
use App\Campaigns\PendingChanges;
use App\Campaigns\PublishGate;
use App\Campaigns\Publishing\GooglePublisher;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\AllowedAdAccount;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Models\User;
use App\Services\GoogleAdsService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Tools\Request as ToolRequest;
use RuntimeException;
use Tests\TestCase;

class GoogleCampaignImportTest extends TestCase
{
    use RefreshDatabase;

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

        config([
            'platforms.guardrails.allowed_ad_accounts' => ['google:1234567890'],
            'services.google_ads.refresh_token' => 'refresh-token',
            'services.google_ads.customer_id' => '123-456-7890',
        ]);
    }

    private function fakeGoogle(bool $invalidLocation = false, bool $withProximity = false, bool $withLocationGroup = false, int $budgetReferenceCount = 1, bool $invalidSearchCriterion = false): void
    {
        Http::fake(function (Request $request) use ($invalidLocation, $withProximity, $withLocationGroup, $budgetReferenceCount, $invalidSearchCriterion) {
            if (str_contains($request->url(), 'oauth2.googleapis.com')) {
                return Http::response(['access_token' => 'token', 'expires_in' => 3600]);
            }

            $query = (string) ($request->data()['query'] ?? '');
            if (str_contains($query, 'FROM ad_group_criterion')) {
                return Http::response([['results' => [
                    ['adGroupCriterion' => [
                        'resourceName' => 'customers/1234567890/adGroupCriteria/444~1',
                        'adGroup' => 'customers/1234567890/adGroups/444',
                        'type' => 'KEYWORD', 'status' => 'ENABLED',
                        'keyword' => ['text' => 'seo agency', 'matchType' => $invalidSearchCriterion ? null : 'PHRASE'],
                    ]],
                    ['adGroupCriterion' => [
                        'resourceName' => 'customers/1234567890/adGroupCriteria/555~2',
                        'adGroup' => 'customers/1234567890/adGroups/555',
                        'type' => 'KEYWORD', 'status' => 'PAUSED', 'negative' => true,
                        'keyword' => ['text' => 'free seo', 'matchType' => 'EXACT'],
                    ]],
                    ['adGroupCriterion' => [
                        'resourceName' => 'customers/1234567890/adGroupCriteria/444~3',
                        'adGroup' => 'customers/1234567890/adGroups/444',
                        'type' => 'USER_LIST', 'status' => 'ENABLED', 'negative' => false,
                        'userList' => ['userList' => 'customers/1234567890/userLists/777'],
                    ], 'adGroup' => ['targetingSetting' => ['targetRestrictions' => [
                        ['targetingDimension' => 'AUDIENCE', 'bidOnly' => true],
                    ]]]],
                ]]]);
            }

            if (str_contains($query, "campaign_criterion.type IN ('LOCATION_GROUP')")) {
                return Http::response([['results' => $withLocationGroup
                    ? [['campaignCriterion' => ['type' => 'LOCATION_GROUP']]]
                    : []]]);
            }

            if (str_contains($query, "campaign_criterion.type = 'PROXIMITY'")) {
                return Http::response([['results' => $withProximity ? [[
                    'campaignCriterion' => [
                        'proximity' => [
                            'geoPoint' => ['latitudeInMicroDegrees' => 40712776, 'longitudeInMicroDegrees' => -74005974],
                            'radius' => 10, 'radiusUnits' => 'MILES',
                        ],
                        'negative' => false, 'status' => 'ENABLED',
                    ],
                ]] : []]]);
            }

            if (str_contains($query, "'PROXIMITY'")) {
                return Http::response([['results' => []]]);
            }

            if (str_contains($query, 'FROM geo_target_constant')) {
                return Http::response([['results' => [
                    ['geoTargetConstant' => [
                        'resourceName' => 'geoTargetConstants/2840', 'countryCode' => 'US',
                        'targetType' => 'Country', 'canonicalName' => 'United States',
                    ]],
                    ['geoTargetConstant' => [
                        'resourceName' => 'geoTargetConstants/1023191', 'countryCode' => 'US',
                        'targetType' => 'City', 'canonicalName' => 'San Francisco, California, United States',
                    ]],
                    ['geoTargetConstant' => [
                        'resourceName' => 'geoTargetConstants/21137', 'countryCode' => 'US',
                        'targetType' => 'State', 'canonicalName' => 'California, United States',
                    ]],
                ]]]);
            }

            if (str_contains($query, 'FROM campaign_criterion')) {
                return Http::response([['results' => [
                    ['campaignCriterion' => [
                        'resourceName' => 'customers/1234567890/campaignCriteria/222~1',
                        'location' => ['geoTargetConstant' => 'geoTargetConstants/2840'],
                        'negative' => false,
                        'status' => 'ENABLED',
                    ], 'geoTargetConstant' => ['countryCode' => 'US', 'targetType' => 'Country', 'canonicalName' => 'United States']],
                    ['campaignCriterion' => [
                        'resourceName' => 'customers/1234567890/campaignCriteria/222~2',
                        'location' => ['geoTargetConstant' => $invalidLocation ? null : 'geoTargetConstants/1023191'],
                        'negative' => false,
                        'status' => 'ENABLED',
                    ], 'geoTargetConstant' => ['countryCode' => 'US', 'targetType' => 'City', 'canonicalName' => 'San Francisco, California, United States']],
                    ['campaignCriterion' => [
                        'resourceName' => 'customers/1234567890/campaignCriteria/222~3',
                        'location' => ['geoTargetConstant' => 'geoTargetConstants/21137'],
                        'negative' => true,
                        'status' => 'ENABLED',
                    ], 'geoTargetConstant' => ['countryCode' => 'US', 'targetType' => 'State', 'canonicalName' => 'California, United States']],
                ]]]);
            }

            return Http::response([['results' => [[
                'campaign' => ['id' => '222', 'name' => 'Imported Search', 'status' => 'PAUSED', 'advertisingChannelType' => 'SEARCH'],
                'campaignBudget' => ['resourceName' => 'customers/1234567890/campaignBudgets/333', 'referenceCount' => config('testing.google_budget_reference_count', $budgetReferenceCount), 'amountMicros' => '25000000'],
            ]]]]);
        });
    }

    public function test_google_import_keeps_exact_included_and_excluded_geo_criteria_in_its_baseline(): void
    {
        $this->fakeGoogle();
        $owner = User::factory()->create();

        $campaign = app(CampaignImporter::class)->adoptGoogle('222', $owner);

        $this->assertSame('google', $campaign->platform);
        $this->assertSame('search', $campaign->campaign_type);
        $this->assertSame('333', $campaign->external_ids['budget_id']);
        $this->assertSame(['US'], $campaign->locations['countries']);
        $this->assertCount(3, $campaign->locations['google_location_criteria']);
        $this->assertSame('geoTargetConstants/1023191', $campaign->locations['google_location_criteria'][1]['geo_target']);
        $this->assertTrue($campaign->locations['google_location_criteria'][2]['negative']);
        $this->assertSame($campaign->locations, $campaign->published_state['locations']);
        $this->assertSame([], app(PendingChanges::class)->requiringRebuild($campaign));

        $again = app(CampaignImporter::class)->adoptGoogle('222', $owner);
        $this->assertSame($campaign->id, $again->id);
        $this->assertSame(1, Campaign::query()->count());
    }

    public function test_google_campaign_dates_use_the_v25_date_time_field(): void
    {
        Http::fake(function (Request $request) {
            if (str_contains($request->url(), 'oauth2.googleapis.com')) {
                return Http::response(['access_token' => 'token', 'expires_in' => 3600]);
            }

            return Http::response([['results' => [[
                'campaign' => ['id' => '222', 'name' => 'Search', 'status' => 'PAUSED', 'startDateTime' => '2026-10-06 00:00:00', 'endDateTime' => '2026-12-31 23:59:59'],
                'customer' => ['timeZone' => 'America/New_York'],
                'campaignBudget' => ['resourceName' => 'customers/1234567890/campaignBudgets/333', 'referenceCount' => 1, 'amountMicros' => '25000000'],
            ]]]]);
        });

        $connection = GoogleAdsConnection::shared();
        $this->assertSame('2026-10-06', app(GoogleAdsService::class)->readCampaignStartDate($connection, '222'));
        $profile = app(GoogleAdsService::class)->readCampaignProfile($connection, '222');
        $this->assertSame('2026-10-06', $profile['start_date']);
        $this->assertSame('2026-10-06 00:00:00', $profile['start_date_time']);
        $this->assertSame('2026-12-31 23:59:59', $profile['end_date_time']);
        $this->assertSame('America/New_York', $profile['time_zone']);
        Http::assertSent(fn (Request $request): bool => str_contains((string) ($request->data()['query'] ?? ''), 'campaign.start_date_time')
            && str_contains((string) ($request->data()['query'] ?? ''), 'customer.time_zone'));
        Http::assertNotSent(fn (Request $request): bool => str_contains((string) ($request->data()['query'] ?? ''), 'campaign.start_date\n'));
    }

    public function test_google_profile_reads_the_bid_strategy_and_its_targets(): void
    {
        Http::fake(function (Request $request) {
            if (str_contains($request->url(), 'oauth2.googleapis.com')) {
                return Http::response(['access_token' => 'token', 'expires_in' => 3600]);
            }

            return Http::response([['results' => [[
                'campaign' => [
                    'id' => '222', 'name' => 'Search', 'status' => 'PAUSED', 'biddingStrategyType' => 'MAXIMIZE_CONVERSIONS',
                    'maximizeConversions' => ['targetCpaMicros' => '12345678'],
                    'biddingStrategy' => 'customers/1234567890/biddingStrategies/9',
                ],
                'campaignBudget' => ['resourceName' => 'customers/1234567890/campaignBudgets/333', 'referenceCount' => 1, 'amountMicros' => '25000000'],
            ]]]]);
        });

        $profile = app(GoogleAdsService::class)->readCampaignProfile(GoogleAdsConnection::shared(), '222');

        $this->assertSame('MAXIMIZE_CONVERSIONS', $profile['bidding_strategy_type']);
        $this->assertSame('customers/1234567890/biddingStrategies/9', $profile['bidding_portfolio']);
        $this->assertSame(12.35, $profile['target_cpa']);
        $this->assertNull($profile['target_roas']);
        Http::assertSent(fn (Request $request): bool => str_contains((string) ($request->data()['query'] ?? ''), 'campaign.maximize_conversion_value.target_roas'));
    }

    public function test_google_profile_keeps_other_fields_when_date_readback_is_rejected(): void
    {
        Http::fake(function (Request $request) {
            if (str_contains($request->url(), 'oauth2.googleapis.com')) {
                return Http::response(['access_token' => 'token', 'expires_in' => 3600]);
            }

            if (str_contains((string) ($request->data()['query'] ?? ''), 'campaign.start_date_time')) {
                return Http::response(['error' => ['message' => 'Date field unavailable']], 400);
            }

            return Http::response([['results' => [[
                'campaign' => ['id' => '222', 'name' => 'Search', 'status' => 'PAUSED'],
                'campaignBudget' => ['resourceName' => 'customers/1234567890/campaignBudgets/333', 'referenceCount' => 1, 'amountMicros' => '25000000'],
            ]]]]);
        });

        $connection = GoogleAdsConnection::shared();
        $this->assertNull(app(GoogleAdsService::class)->readCampaignStartDate($connection, '222'));

        $profile = app(GoogleAdsService::class)->readCampaignProfile($connection, '222');
        $this->assertSame('Search', $profile['name']);
        $this->assertSame('PAUSED', $profile['status']);
        $this->assertSame(25.0, $profile['daily_budget']);
        $this->assertSame('', $profile['start_date']);
        $this->assertSame('', $profile['time_zone']);
        $this->assertStringContainsString('Date field unavailable', $profile['profile_fields_error']);
    }

    public function test_google_import_preserves_ad_group_keyword_and_audience_criteria_with_their_scope(): void
    {
        $this->fakeGoogle();

        $campaign = app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());
        $criteria = $campaign->external_ids['google_ad_group_criteria'];

        $this->assertCount(3, $criteria);
        $this->assertFalse($criteria[0]['negative']);
        $this->assertSame('customers/1234567890/adGroups/555', $criteria[2]['ad_group']);
        $this->assertSame(['text' => 'free seo', 'match_type' => 'EXACT'], array_intersect_key($criteria[2], array_flip(['text', 'match_type'])));
        $this->assertTrue($criteria[2]['negative']);
        $this->assertSame('customers/1234567890/userLists/777', $criteria[1]['user_list']);
        $this->assertTrue($criteria[1]['audience_bid_only']);
        $this->assertSame($criteria, $campaign->published_state['google_imported_ad_group_criteria']);
        $this->assertSame([], app(PendingChanges::class)->requiringRebuild($campaign));

        $html = view('partials.campaign-panel', [
            'campaign' => $campaign, 'progress' => [], 'nextStep' => null,
            'blocking' => [], 'sources' => [], 'pending' => [], 'needsRebuild' => [],
            'campaigns' => collect([$campaign]), 'assets' => collect(),
        ])->render();
        $this->assertStringContainsString('Imported Search keywords', $html);
        $this->assertStringContainsString('seo agency [PHRASE], ad group 444', $html);
        $this->assertStringContainsString('customers/1234567890/userLists/777, ad group 444 (observation', $html);
    }

    public function test_google_import_rejects_incomplete_keyword_criteria_before_creating_a_campaign(): void
    {
        $this->fakeGoogle(invalidSearchCriterion: true);

        try {
            app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());
            $this->fail('Incomplete provider targeting should block import.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('keyword without text or match type', $exception->getMessage());
        }

        $this->assertSame(0, Campaign::query()->count());
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_imported_search_criteria_cannot_be_dropped_by_republishing_the_campaign(): void
    {
        $this->fakeGoogle();
        $campaign = app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());
        $campaign->update(['external_campaign_id' => null, 'status' => 'draft', 'locations' => ['countries' => ['US']]]);
        $created = [];

        try {
            app(GooglePublisher::class)->create($campaign->fresh(), 'tester', $created);
            $this->fail('An imported multi-group baseline must not be flattened into a new ad group.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('original ad-group scope', $exception->getMessage());
        }

        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_google_location_readback_can_request_criterion_status_without_changing_import_shape(): void
    {
        $this->fakeGoogle();
        $connection = GoogleAdsConnection::shared();
        $this->assertNotNull($connection);

        $criteria = app(GoogleAdsService::class)->readCampaignLocationCriteria($connection, '222', includeStatus: true);

        $this->assertSame(['ENABLED', 'ENABLED', 'ENABLED'], array_column($criteria, 'status'));
        Http::assertSent(fn (Request $request): bool => str_contains((string) ($request->data()['query'] ?? ''), 'campaign_criterion.status')
            && str_contains((string) ($request->data()['query'] ?? ''), 'campaign_criterion.location.geo_target_constant')
            && ! str_contains((string) ($request->data()['query'] ?? ''), 'geo_target_constant.country_code'));
    }

    public function test_geo_summary_keeps_location_names_when_campaign_also_uses_radius(): void
    {
        $this->fakeGoogle(withProximity: true);
        $connection = GoogleAdsConnection::shared();
        $this->assertNotNull($connection);

        $this->assertSame([
            'United States', 'San Francisco, California, United States', 'California, United States',
        ], app(GoogleAdsService::class)->readCampaignGeoTargets($connection, '222'));
    }

    public function test_an_unreadable_google_location_aborts_import_without_creating_a_campaign(): void
    {
        $this->fakeGoogle(invalidLocation: true);

        try {
            app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());
            $this->fail('Import should have refused the incomplete location criterion.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('location criterion', $exception->getMessage());
        }

        $this->assertSame(0, Campaign::query()->count());
    }

    public function test_imported_google_places_and_exclusions_are_visible_in_review(): void
    {
        $this->fakeGoogle();
        $campaign = app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());

        $html = view('partials.campaign-panel', [
            'campaign' => $campaign,
            'progress' => [],
            'nextStep' => null,
            'blocking' => [],
            'sources' => [],
            'pending' => [],
            'needsRebuild' => [],
            'campaigns' => collect([$campaign]),
            'assets' => collect(),
        ])->render();

        $this->assertStringContainsString('San Francisco, California, United States', $html);
        $this->assertStringContainsString('Imported Google excluded state: California, United States', $html);
    }

    public function test_google_import_preserves_existing_radius_targeting_without_editing_it(): void
    {
        $this->fakeGoogle(withProximity: true);
        $campaign = app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());

        $this->assertSame([[
            'latitude' => 40.712776, 'longitude' => -74.005974, 'radius' => 10,
            'radius_unit' => 'mi', 'negative' => false, 'status' => 'ENABLED',
        ]], $campaign->locations['google_proximity_criteria']);
        $this->assertSame($campaign->locations, $campaign->published_state['locations']);
        $this->assertSame([], app(PendingChanges::class)->requiringRebuild($campaign));

        $html = view('partials.campaign-panel', [
            'campaign' => $campaign, 'progress' => [], 'nextStep' => null,
            'blocking' => [], 'sources' => [], 'pending' => [], 'needsRebuild' => [],
            'campaigns' => collect([$campaign]), 'assets' => collect(),
        ])->render();
        $this->assertStringContainsString('Imported Google radius: 10 mi around 40.712776, -74.005974', $html);
    }

    public function test_google_import_refuses_unrepresented_location_group_targeting(): void
    {
        $this->fakeGoogle(withLocationGroup: true);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('proximity or location-group');
        try {
            app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());
        } finally {
            $this->assertSame(0, Campaign::query()->count());
        }
    }

    public function test_imported_shared_google_budget_cannot_be_edited_as_a_single_campaign_budget(): void
    {
        $this->fakeGoogle(budgetReferenceCount: 2);
        $campaign = app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());

        $this->assertSame(2, $campaign->external_ids['budget_reference_count']);
        $this->expectExceptionMessage('budget may be shared by multiple campaigns');

        app(GooglePublisher::class)->update($campaign, ['budget' => ['from' => '25', 'to' => '30']], 'tester');
    }

    public function test_unrelated_google_name_edit_does_not_replace_imported_location_criteria(): void
    {
        $this->fakeGoogle();
        $campaign = app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());
        $importedCriteria = $campaign->locations['google_location_criteria'];

        app(GooglePublisher::class)->update($campaign, ['name' => ['from' => 'Imported Search', 'to' => 'Renamed Search']], 'tester');

        Http::assertSent(fn (Request $request): bool => str_contains($request->url(), 'campaigns:mutate'));
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), 'campaignCriteria:mutate'));
        $this->assertSame($importedCriteria, $campaign->fresh()->locations['google_location_criteria']);
    }

    public function test_google_date_edit_uses_v25_date_time_fields(): void
    {
        $this->fakeGoogle();
        $campaign = app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());
        $campaign->starts_at = '2026-10-07';
        $campaign->ends_at = '2026-10-31';

        app(GooglePublisher::class)->update($campaign, [
            'starts_at' => ['from' => null, 'to' => '2026-10-07'],
            'ends_at' => ['from' => null, 'to' => '2026-10-31'],
        ], 'tester');

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

            $update = $request->data()['operations'][0]['update'] ?? [];

            return ($update['startDateTime'] ?? null) === '2026-10-07 00:00:00'
                && ($update['endDateTime'] ?? null) === '2026-10-31 23:59:59';
        });
    }

    public function test_imported_google_budget_is_rechecked_before_any_live_edit(): void
    {
        $this->fakeGoogle();
        $campaign = app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());
        config(['testing.google_budget_reference_count' => 2]);
        $this->assertSame(2, config('testing.google_budget_reference_count'));
        $this->assertSame(2, app(GoogleAdsService::class)->readCampaignProfile(GoogleAdsConnection::shared(), '222', fresh: true)['budget_reference_count']);
        $callsBefore = Http::recorded()->count();

        try {
            app(GooglePublisher::class)->update($campaign, [
                'name' => ['from' => 'Imported Search', 'to' => 'Renamed Search'],
                'budget' => ['from' => '25', 'to' => '30'],
            ], 'tester');
            $this->fail('The now-shared budget should have blocked the edit.');
        } catch (RuntimeException $exception) {
            $this->assertStringContainsString('ownership changed since import', $exception->getMessage());
        }

        $this->assertGreaterThan($callsBefore, Http::recorded()->count());
        Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), ':mutate'));
    }

    public function test_imported_city_only_google_campaign_is_not_mistaken_for_worldwide_targeting(): void
    {
        $campaign = Campaign::query()->create([
            'user_id' => User::factory()->create()->id,
            'name' => 'Imported City',
            'platform' => 'google',
            'status' => 'published',
            'ad_account_id' => '1234567890',
            'external_campaign_id' => '222',
            'locations' => ['countries' => [], 'google_location_criteria' => [[
                'criterion' => 'customers/1234567890/campaignCriteria/222~2',
                'geo_target' => 'geoTargetConstants/1023191',
                'country_code' => 'US',
                'target_type' => 'City',
                'name' => 'San Francisco, California, United States',
                'negative' => false,
            ]]],
        ]);

        $this->assertNotContains('target country not set', app(PublishGate::class)->soundness($campaign));
    }

    public function test_imported_radius_only_google_campaign_is_not_mistaken_for_worldwide_targeting(): void
    {
        $campaign = Campaign::query()->create([
            'user_id' => User::factory()->create()->id,
            'name' => 'Imported Radius', 'platform' => 'google', 'status' => 'published',
            'ad_account_id' => '1234567890', 'external_campaign_id' => '222',
            'locations' => ['countries' => [], 'google_proximity_criteria' => [[
                'latitude' => 40.712776, 'longitude' => -74.005974,
                'radius' => 10, 'radius_unit' => 'mi', 'negative' => false, 'status' => 'ENABLED',
            ]]],
        ]);

        $this->assertNotContains('target country not set', app(PublishGate::class)->soundness($campaign));
    }

    public function test_imported_google_criteria_cannot_be_republished_as_a_broader_draft(): void
    {
        $this->fakeGoogle();
        $campaign = app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());
        $campaign->update(['external_campaign_id' => null, 'status' => 'draft']);

        $this->expectExceptionMessage('Imported Google location and radius criteria must be reselected');

        app(TargetingSelections::class)->googleGeoTargets($campaign->fresh());
    }

    public function test_google_import_checks_the_account_allowlist_before_reading(): void
    {
        config(['platforms.guardrails.allowed_ad_accounts' => []]);
        AllowedAdAccount::query()->delete();
        Http::fake();

        $this->expectExceptionMessage('No ad accounts are allowed');

        try {
            app(CampaignImporter::class)->adoptGoogle('222', User::factory()->create());
        } finally {
            Http::assertNothingSent();
        }
    }

    public function test_open_campaign_tool_can_adopt_google_by_explicit_platform_and_id(): void
    {
        $this->fakeGoogle();
        $owner = User::factory()->create();
        $this->actingAs($owner);
        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-google-import');
        $workspace->ownedBy($owner);

        $message = (string) app(OpenCampaign::class)->handle(new ToolRequest([
            'platform' => 'google',
            'campaign_id' => '222',
        ]));

        $this->assertStringContainsString('Opened "Imported Search"', $message);
        $this->assertSame('google', Campaign::query()->firstOrFail()->platform);
    }
}
