<?php

namespace Tests\Feature;

use App\Campaigns\Publishing\MetaDraftPause;
use App\Campaigns\Publishing\MetaPublisher;
use App\Models\ApiCall;
use App\Models\Asset;
use App\Models\AssetPlatformRef;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\User;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Sleep;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * Creating through the MCP is not publishing, and this is what closes the gap.
 *
 * ads_create_campaign has no status parameter. What it makes is an unpublished
 * Ads Manager draft with the status staged ACTIVE, which neither serves nor runs
 * and which goes live the moment somebody presses Review and publish. Every
 * campaign this product reported as published on production between 30 Sep and
 * 1 Oct was one of those: campaign 120249665465240510 read back from
 * ads_get_ad_entities as source=mcp_campaign_creation, status=EDITING, staged
 * status ACTIVE.
 *
 * Two calls close it, both verified against the live endpoint on 1 Oct before
 * any of this was written. ads_update_entity restages a draft object PAUSED and
 * answers is_draft true. ads_activate_entity with publish_as_active false
 * publishes the staged objects exactly as staged, which is what turns a draft
 * into a live campaign.
 *
 * What these pin is the pair of mistakes that would put spend at risk: leaving
 * the draft staged ACTIVE, and publishing with publish_as_active true.
 */
class McpPublishesPausedTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    /** @var list<array{tool: string, arguments: array<string, mixed>}> */
    private array $calls = [];

    private bool $metaAnswersActive = false;

    private bool $failAdSetInternally = false;

    private bool $refuseDeletes = false;

    /** publishing: 1815558 while the publish is in flight. other: a real pause refusal. */
    private ?string $pauseUpdateError = null;

    /** Graph cannot see the draft yet, which is StockPrices right after activate. */
    private bool $draftsNotVisible = false;

    /** Id Graph returns for ad set 900002 once the publish has finished. */
    private ?string $adSetReadBackId = null;

    /** @var list<array<string, mixed>>|null */
    private ?array $activateObjectErrors = null;

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

        $this->seedVerifiedCountries();

        config([
            'platforms.meta.mcp.enabled' => true,
            'platforms.meta.mcp.token' => 'test-token',
            'platforms.meta.token' => 'test-token',
            'platforms.guardrails.paused' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['act_1238155271384134'],
        ]);

        $this->calls = [];

        // Every create answers with an id so the publisher can walk the tree,
        // and every call is recorded so the order can be asserted.
        Http::fake(function ($request) {
            $body = $request->data();
            $tool = $body['params']['name'] ?? '';

            // Graph speaks a different shape, and this test also runs with the
            // MCP off to prove nothing publishes on that path.
            if ($tool === '') {
                $this->calls[] = ['tool' => $request->method().' '.$request->url(), 'arguments' => $body];

                if ($request->method() === 'DELETE') {
                    return $this->refuseDeletes
                        ? Http::response(['error' => ['message' => '(#10) Application does not have permission', 'code' => 10]], 403)
                        : Http::response(['success' => true]);
                }

                if (config('platforms.meta.mcp.enabled') && str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/adsets')) {
                    return Http::response([
                        'error' => [
                            'message' => '900001 is not a valid campaign id',
                            'type' => 'OAuthException',
                            'code' => 100,
                            'error_subcode' => 1815148,
                        ],
                    ], 400);
                }

                if ($this->draftsNotVisible && $request->method() === 'GET' && str_contains($request->url(), 'effective_status')) {
                    return Http::response([
                        'error' => [
                            'message' => 'Unsupported get request. Object with ID does not exist',
                            'type' => 'GraphMethodException',
                            'code' => 100,
                        ],
                    ], 400);
                }

                $path = (string) parse_url($request->url(), PHP_URL_PATH);
                $id = '900001';

                if (preg_match('#/(\d+)$#', $path, $match) === 1) {
                    $id = $match[1];
                }

                if ($id === '900002' && $this->adSetReadBackId !== null) {
                    $id = $this->adSetReadBackId;
                }

                return Http::response(['id' => $id, 'status' => 'ACTIVE', 'effective_status' => 'ACTIVE']);
            }

            $this->calls[] = ['tool' => $tool, 'arguments' => $body['params']['arguments'] ?? []];

            if ($tool === 'ads_update_entity' && $this->pauseUpdateError !== null) {
                $publishing = $this->pauseUpdateError === 'publishing';

                return Http::response([
                    'result' => [
                        'isError' => true,
                        'content' => [[
                            'type' => 'text',
                            'text' => json_encode($publishing ? [
                                'success' => false,
                                'error_category' => 'VALIDATION',
                                'error_message' => 'Cannot edit a draft fragment while it is publishing: A fragment is being edited while it is being published',
                                'error_code' => '100',
                                'error_subcode' => '1815558',
                                'is_retryable' => false,
                            ] : [
                                'error_category' => 'VALIDATION',
                                'error_message' => 'The budget is below the minimum.',
                                'error_code' => '100',
                                'error_subcode' => '1885014',
                            ]),
                        ]],
                    ],
                ]);
            }

            if ($tool === 'ads_create_ad_set' && $this->failAdSetInternally) {
                return Http::response([
                    'result' => [
                        'isError' => true,
                        'content' => [[
                            'type' => 'text',
                            'text' => json_encode([
                                'error_category' => 'INTERNAL',
                                'error_message' => 'An internal error occurred. Please try again later.',
                                'error_code' => null,
                                'error_subcode' => null,
                                'is_retryable' => true,
                                'campaign_id' => '120252186296080626',
                                'details' => ['access_token' => 'secret-response-token'],
                            ]),
                        ]],
                    ],
                ], 200, [
                    'X-Request-Id' => 'mcp-request-123',
                    'X-FB-Trace-ID' => 'meta-trace-456',
                ]);
            }

            $payload = match ($tool) {
                'ads_create_campaign' => ['campaign_id' => '900001'],
                'ads_create_ad_set' => ['ad_set_id' => '900002'],
                'ads_create_creative' => ['creative_id' => '900003'],
                'ads_create_ad' => ['ad_id' => '900004'],
                'ads_activate_entity' => $this->activatePayload(),
                default => ['success' => true],
            };

            return Http::response([
                'result' => ['content' => [['type' => 'text', 'text' => json_encode($payload)]]],
            ]);
        });
    }

    private function publish(): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => User::factory()->create()->id,
            'name' => 'Paused on arrival',
            'platform' => 'meta',
            'status' => 'draft',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_1238155271384134',
            'page_id' => '1207169149145078',
            'landing_url' => 'https://example.com',
            'budget' => 20,
            'budget_mode' => 'daily',
            'currency' => 'USD',
            'locations' => ['countries' => ['US']],
            'audience' => ['countries' => ['US'], 'placements' => ['facebook'], 'devices' => ['mobile', 'desktop']],
        ]);

        $created = [];

        app(MetaPublisher::class)->create($campaign->fresh(), 'tester', $created);

        return $campaign->fresh();
    }

    /** @return list<array<string, mixed>> */
    private function argumentsFor(string $tool): array
    {
        return array_values(array_map(
            fn (array $call): array => $call['arguments'],
            array_filter($this->calls, fn (array $call): bool => $call['tool'] === $tool),
        ));
    }

    /**
     * The draft is never left staged.
     *
     * Without this the campaign is only ever an Ads Manager draft, which is the
     * state production was in: nothing served, nothing ran, and the product said
     * it had published.
     */
    public function test_the_staged_draft_is_published(): void
    {
        $this->publish();

        $this->assertNotEmpty(
            $this->argumentsFor('ads_activate_entity'),
            'Nothing published the draft, so the campaign exists only in Ads Manager.',
        );
    }

    public function test_an_mcp_campaign_is_not_used_for_graph_ad_set_validation(): void
    {
        $this->publish();

        Http::assertNotSent(fn ($request): bool => str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/adsets'));
        $this->assertSame('900001', $this->argumentsFor('ads_create_ad_set')[0]['campaign_id']);
        $this->assertNotEmpty($this->argumentsFor('ads_activate_entity'));
    }

    /** And published as staged rather than as live. */
    public function test_it_is_never_published_as_active(): void
    {
        $this->publish();

        $campaignPublish = $this->argumentsFor('ads_activate_entity')[0];

        $this->assertFalse(
            $campaignPublish['publish_as_active'] ?? true,
            'The campaign was published active, so it begins spending immediately.',
        );
    }

    /**
     * Only the campaign is paused, and only after the publish returns.
     *
     * A status update before ads_activate_entity starts a publish of its own.
     * Campaign 253 then failed because the ad set was already publishing, and
     * the rollback's second update was refused with 1815558.
     *
     * The ad set is left active beneath the paused campaign: the campaign gates
     * its whole tree. Everything is paused when publish_pause_level is 'all'.
     */
    public function test_only_the_campaign_is_restaged_paused(): void
    {
        $this->publish();

        $this->assertEqualsCanonicalizing(['campaign'], $this->restagedPaused());
    }

    public function test_every_object_is_restaged_paused_when_the_level_is_all(): void
    {
        config(['platforms.guardrails.publish_pause_level' => 'all']);

        $this->publish();

        $this->assertEqualsCanonicalizing(['campaign', 'ad_set'], $this->restagedPaused());
    }

    /** The ad set is published in the one campaign call and left active under it. */
    public function test_the_ad_set_is_published_with_the_campaign_and_left_active(): void
    {
        $this->publish();

        $activations = $this->argumentsFor('ads_activate_entity');

        $this->assertCount(1, $activations);
        $this->assertContains('900002', $activations[0]['object_ids']);
        $this->assertFalse($activations[0]['publish_as_active']);
        $this->assertNotContains('ad_set', $this->restagedPaused());
    }

    /** @return list<string> entity types restaged to PAUSED */
    private function restagedPaused(): array
    {
        $paused = [];

        foreach ($this->argumentsFor('ads_update_entity') as $arguments) {
            if ((json_decode((string) ($arguments['fields'] ?? '{}'), true)['status'] ?? null) === 'PAUSED') {
                $paused[] = $arguments['entity_type'];
            }
        }

        return $paused;
    }

    /** Meta reports the campaign ACTIVE after the publish even when told not to, so it is paused again. */
    public function test_a_campaign_meta_reports_active_is_paused_again_after_publishing(): void
    {
        $this->metaAnswersActive = true;

        $this->publish();

        $tools = array_column($this->calls, 'tool');
        $publishedAt = array_search('ads_activate_entity', $tools, true);

        // After the publish, not necessarily last: the ad set is set active
        // afterwards, so "last call" stopped being the right question.
        $repaused = null;

        foreach ($this->calls as $index => $call) {
            if ($index <= $publishedAt || $call['tool'] !== 'ads_update_entity') {
                continue;
            }

            if ($call['arguments']['entity_type'] === 'campaign'
                && (json_decode((string) $call['arguments']['fields'], true)['status'] ?? null) === 'PAUSED') {
                $repaused = $index;
            }
        }

        $this->assertNotNull($repaused, 'the campaign Meta reported ACTIVE was never paused again');
        $this->assertGreaterThan($publishedAt, $repaused);
    }

    /**
     * StockPrices returns from ads_activate_entity while the publish is still running.
     *
     * The pause then gets 1815558. That is the publish from the activate, not a
     * second failure, and rolling it back is what left the ad set on the account.
     */
    public function test_a_pause_refused_while_meta_is_still_publishing_keeps_the_campaign(): void
    {
        $this->pauseUpdateError = 'publishing';
        Log::spy();

        $this->publish();

        $this->assertCount(1, $this->argumentsFor('ads_activate_entity'));
        $this->assertFalse($this->argumentsFor('ads_activate_entity')[0]['publish_as_active']);
        $this->assertSame(['campaign'], $this->restagedPaused());
        foreach ($this->calls as $call) {
            $this->assertStringStartsNotWith('DELETE ', $call['tool']);
        }

        Log::shouldHaveReceived('warning')
            ->withArgs(fn (string $message, array $context): bool => $message === 'Meta is still publishing the draft, so the pause waits for that publish'
                && ($context['entity_type'] ?? null) === 'campaign'
                && str_contains((string) ($context['error'] ?? ''), '1815558'))
            ->once();
    }

    /** StockPrices cannot see the ad set or ad yet, so the campaign is not paused into that window. */
    public function test_the_campaign_is_not_paused_until_the_ad_set_and_ads_exist(): void
    {
        $this->draftsNotVisible = true;
        Log::spy();

        app(Meta::class)->settleAsPaused('act_1238155271384134', [
            ['id' => '900001', 'type' => 'campaign'],
            ['id' => '900002', 'type' => 'ad_set'],
            ['id' => '900004', 'type' => 'ad'],
        ], pauseChildren: false, whenCreated: true);

        $this->assertCount(1, $this->argumentsFor('ads_activate_entity'));
        $this->assertSame([], $this->argumentsFor('ads_update_entity'));

        Log::shouldHaveReceived('info')
            ->withArgs(fn (string $message, array $context): bool => $message === 'Meta campaign objects are not created yet, so the campaign is not paused'
                && collect($context['missing'])->pluck('type')->all() === ['campaign', 'ad_set', 'ad'])
            ->once();
    }

    /** Once Graph can see every object, only the campaign is paused. */
    public function test_the_campaign_is_paused_after_the_ad_set_and_ads_are_created(): void
    {
        Sleep::fake();
        Log::spy();

        $objects = [
            ['id' => '900001', 'type' => 'campaign'],
            ['id' => '900002', 'type' => 'ad_set'],
            ['id' => '900004', 'type' => 'ad'],
        ];

        $this->draftsNotVisible = true;
        app(MetaDraftPause::class)->pauseOnceCreated('act_1238155271384134', $objects, pauseChildren: false);
        $this->assertSame([], $this->argumentsFor('ads_update_entity'));

        $this->draftsNotVisible = false;
        app(MetaDraftPause::class)->resumeWhenCreated('act_1238155271384134', $objects, pauseChildren: false);

        Sleep::assertSleptTimes(1);
        $this->assertSame(['campaign'], $this->restagedPaused());
        Log::shouldHaveReceived('info')
            ->withArgs(fn (string $message): bool => $message === 'Meta campaign, ad set, and ads are created, pausing the campaign')
            ->once();
    }

    /** A pause Meta refuses for a real reason still stops the publish. */
    public function test_a_pause_refused_for_another_reason_still_stops_the_publish(): void
    {
        $this->pauseUpdateError = 'other';

        try {
            $this->publish();
            $this->fail('A pause Meta refused for another reason should stop the publish.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString('budget', $exception->getMessage());
        }
    }

    /** Pausing before the publish is what makes Meta say the ad set is already publishing. */
    public function test_nothing_is_paused_until_the_publish_returns(): void
    {
        $this->publish();

        $tools = array_column($this->calls, 'tool');

        $this->assertGreaterThan(
            array_search('ads_activate_entity', $tools, true),
            array_search('ads_update_entity', $tools, true),
            'A status update ran before the publish, which starts a second publish.',
        );
    }

    /**
     * The whole tree is published together.
     *
     * object_ids publishes exactly what it lists. A campaign published without
     * its ad sets leaves them staged under a parent that is now live, which is
     * the half-made campaign the rollback exists to prevent.
     */
    public function test_the_campaign_its_ad_set_and_its_ads_publish_together(): void
    {
        app(Meta::class)->settleAsPaused('act_1238155271384134', [
            ['id' => '900001', 'type' => 'campaign'],
            ['id' => '900002', 'type' => 'ad_set'],
            ['id' => '900004', 'type' => 'ad'],
            ['id' => '900005', 'type' => 'ad'],
        ]);

        $arguments = $this->argumentsFor('ads_activate_entity')[0];

        $this->assertSame(['900001', '900002', '900004', '900005'], $arguments['object_ids']);
        $this->assertSame('900001', $arguments['entity_id']);
        $this->assertSame('campaign', $arguments['entity_type']);
        $this->assertFalse($arguments['publish_as_active']);

        // Each level restaged, ads included.
        $types = array_column($this->argumentsFor('ads_update_entity'), 'entity_type');
        $this->assertSame(['campaign', 'ad_set', 'ad', 'ad'], $types);
    }

    /**
     * Graph creates live and paused already, so it must not publish anything.
     *
     * ads_activate_entity against a Graph-made campaign is not a no-op: it is
     * the call that turns a paused campaign on.
     */
    public function test_nothing_is_published_when_the_mcp_is_off(): void
    {
        config(['platforms.meta.mcp.enabled' => false]);

        $this->publish();

        foreach ($this->calls as $call) {
            $this->assertStringNotContainsString('activate', strtolower($call['tool']));
        }
    }

    /** One retry budget for the whole rollback, so a failed publish cannot outlast the request. */
    public function test_refused_deletes_share_one_capped_retry_budget(): void
    {
        Sleep::fake();
        $this->refuseDeletes = true;
        $campaign = Campaign::create([
            'user_id' => User::factory()->create()->id,
            'name' => 'Rolled back',
            'platform' => 'meta',
            'status' => 'draft',
            'ad_account_id' => 'act_1238155271384134',
        ]);

        $left = app(MetaPublisher::class)->rollBack($campaign, [
            'campaign_id' => '900001',
            'ad_sets' => [['adset_id' => '900002']],
            'ads' => array_map(fn (int $i): array => ['ad_id' => '90010'.$i, 'creative_id' => '90020'.$i], range(1, 5)),
        ], 'tester');

        $this->assertContains('900001', $left);
        $this->assertCount(7, array_diff($left, array_map(fn (int $i): string => '90020'.$i, range(1, 5))));
        Sleep::assertSleptTimes(4);
    }

    /** Graph cannot delete an unpublished MCP draft, so the rollback publishes it paused first. */
    public function test_rollback_publishes_mcp_drafts_paused_then_deletes_them(): void
    {
        Sleep::fake();
        $campaign = Campaign::create([
            'user_id' => User::factory()->create()->id,
            'name' => 'Rolled back',
            'platform' => 'meta',
            'status' => 'draft',
            'ad_account_id' => 'act_1238155271384134',
        ]);

        $left = app(MetaPublisher::class)->rollBack($campaign, [
            'campaign_id' => '900001',
            'ad_sets' => [['adset_id' => '900002']],
            'ads' => [['ad_id' => '900004', 'creative_id' => '900003']],
        ], 'tester');

        $this->assertSame([], $left);
        $published = $this->argumentsFor('ads_activate_entity')[0];
        $this->assertSame(['900001', '900002', '900004'], $published['object_ids']);
        $this->assertFalse($published['publish_as_active']);
        $deletes = array_values(array_filter(array_column($this->calls, 'tool'), fn (string $tool): bool => str_starts_with($tool, 'DELETE ')));
        $this->assertCount(3, $deletes);
        foreach (['900004', '900002', '900001'] as $index => $id) {
            $this->assertStringContainsString('/'.$id, $deletes[$index]);
        }
        $this->assertSame('900003', $this->argumentsFor('ads_creative_delete')[0]['creative_id']);
        $this->assertLessThan(
            array_search($deletes[0], array_column($this->calls, 'tool'), true),
            array_search('ads_activate_entity', array_column($this->calls, 'tool'), true),
        );
    }

    public function test_a_generic_mcp_error_keeps_its_upstream_diagnostics_in_the_audit_row(): void
    {
        $this->failAdSetInternally = true;
        Log::spy();

        try {
            $this->publish();
            $this->fail('The simulated ad-set error should stop publishing.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString('INTERNAL', $exception->getMessage());
        }

        $call = ApiCall::query()->where('endpoint', 'ads_create_ad_set')->firstOrFail();

        $this->assertFalse($call->ok);
        $this->assertSame(200, $call->status);
        $this->assertNull($call->object_id, 'A failed MCP response must not imply that it created an object.');
        $this->assertSame('mcp-request-123', $call->response['_error_diagnostics']['correlation_headers']['x-request-id']);
        $this->assertSame('meta-trace-456', $call->response['_error_diagnostics']['correlation_headers']['x-fb-trace-id']);
        $this->assertSame('INTERNAL', $call->response['_error_diagnostics']['mcp_payload']['error_category']);
        $this->assertTrue($call->response['_error_diagnostics']['mcp_payload']['is_retryable']);
        $this->assertArrayNotHasKey('access_token', $call->response['_error_diagnostics']['mcp_payload']['details']);

        Log::shouldHaveReceived('error')
            ->withArgs(fn (string $message, array $context): bool => $message === 'Ad platform MCP call failed'
                && $context['endpoint'] === 'ads_create_ad_set'
                && $context['diagnostics']['mcp_payload']['error_category'] === 'INTERNAL'
            && ! isset($context['diagnostics']['mcp_payload']['details']['access_token'])
                && $context['diagnostics']['correlation_headers']['x-fb-trace-id'] === 'meta-trace-456')
            ->once();
    }

    /** @return array<string, mixed> */
    private function activatePayload(): array
    {
        if ($this->activateObjectErrors !== null) {
            return ['success' => true, 'results' => $this->activateObjectErrors];
        }

        return $this->metaAnswersActive ? ['success' => true, 'status' => 'ACTIVE'] : ['success' => true];
    }

    /**
     * The ad is created with the id Graph reads back, and only after that read.
     *
     * The id returned by ads_create_ad_set is a draft. Creating the ad with it
     * is what act_1418821929380936 refused with 100/1487006.
     */
    public function test_the_ad_uses_the_ad_set_id_graph_reads_back_after_publish(): void
    {
        $this->adSetReadBackId = '900777';
        $campaign = $this->publishableCampaign();
        $this->withImageAd($campaign);

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

        $activateAt = null;
        $readAt = null;
        $adAt = null;

        foreach ($this->calls as $index => $call) {
            if ($activateAt === null && $call['tool'] === 'ads_activate_entity') {
                $activateAt = $index;
            }

            if ($readAt === null && str_starts_with($call['tool'], 'GET ') && str_contains($call['tool'], '/900002')) {
                $readAt = $index;
            }

            if ($call['tool'] === 'ads_create_ad') {
                $adAt = $index;
                $this->assertSame('900777', $call['arguments']['ad_set_id'] ?? null);
            }
        }

        $this->assertNotNull($activateAt);
        $this->assertNotNull($readAt);
        $this->assertNotNull($adAt);
        $this->assertLessThan($readAt, $activateAt);
        $this->assertLessThan($adAt, $readAt);
        $this->assertSame('900777', $campaign->fresh()->primaryAdSet->external_adset_id);
    }

    /** A failed ad set is reported as itself, and no ad is created from that failure. */
    public function test_an_ad_set_publish_error_is_logged_instead_of_creating_the_ad(): void
    {
        $this->activateObjectErrors = [[
            'id' => '900002',
            'entity_type' => 'ADSET',
            'success' => false,
            'error' => ['message' => 'Promoted object is missing', 'code' => 100],
        ]];
        Log::spy();
        $campaign = $this->publishableCampaign();
        $this->withImageAd($campaign);

        try {
            $created = [];
            app(MetaPublisher::class)->create($campaign->fresh(), 'tester', $created);
            $this->fail('A failed ad set publish should stop before the ad is created.');
        } catch (MetaException $exception) {
            $this->assertStringContainsString('Promoted object is missing', $exception->getMessage());
        }

        $this->assertSame([], $this->argumentsFor('ads_create_ad'));

        Log::shouldHaveReceived('error')
            ->withArgs(fn (string $message, array $context): bool => $message === 'Meta ad set publish failed'
                && ($context['errors'][0]['message'] ?? null) === 'Promoted object is missing')
            ->once();
    }

    /** Pause and delete wait until the publish is finished. */
    public function test_rollback_does_not_pause_or_delete_while_the_publish_is_in_flight(): void
    {
        Sleep::fake();
        $this->draftsNotVisible = true;
        Log::spy();
        $campaign = Campaign::create([
            'user_id' => User::factory()->create()->id,
            'name' => 'Still publishing',
            'platform' => 'meta',
            'status' => 'draft',
            'ad_account_id' => 'act_1238155271384134',
        ]);

        $left = app(MetaPublisher::class)->rollBack($campaign, [
            'campaign_id' => '900001',
            'ad_sets' => [['adset_id' => '900002']],
            'ads' => [['ad_id' => '900004', 'creative_id' => '900003']],
        ], 'tester');

        $this->assertContains('900001', $left);
        $this->assertContains('900002', $left);
        $this->assertContains('900004', $left);
        $this->assertSame([], $this->argumentsFor('ads_update_entity'));

        foreach ($this->calls as $call) {
            $this->assertStringStartsNotWith('DELETE ', $call['tool']);
        }

        Log::shouldHaveReceived('warning')
            ->withArgs(fn (string $message): bool => $message === 'Rollback is waiting because the Meta publish is still in flight')
            ->once();
    }

    private function publishableCampaign(): Campaign
    {
        return Campaign::create([
            'user_id' => User::factory()->create()->id,
            'name' => 'Paused on arrival',
            'platform' => 'meta',
            'status' => 'draft',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_1238155271384134',
            'page_id' => '1207169149145078',
            'landing_url' => 'https://example.com',
            'budget' => 20,
            'budget_mode' => 'daily',
            'currency' => 'USD',
            'locations' => ['countries' => ['US']],
            'audience' => ['countries' => ['US'], 'placements' => ['facebook'], 'devices' => ['mobile', 'desktop']],
        ]);
    }

    private function withImageAd(Campaign $campaign): void
    {
        $asset = Asset::create([
            'owner_type' => (new User)->getMorphClass(),
            'owner_id' => $campaign->user_id,
            'kind' => 'image',
            'source' => 'generated',
            'disk' => 'public',
            'path' => 'creatives/x.png',
            'original_name' => 'x.png',
            'mime' => 'image/png',
            'bytes' => 10,
            'checksum' => 'sum-image',
        ]);

        AssetPlatformRef::create([
            'asset_id' => $asset->id,
            'platform' => 'meta',
            'ad_account_id' => $campaign->ad_account_id,
            'external_hash' => 'HASH123',
        ]);

        CampaignAd::create([
            'campaign_id' => $campaign->id,
            'headline' => 'Block pop-ups',
            'primary_text' => 'A cleaner browser.',
            'cta' => 'LEARN_MORE',
            'asset_id' => $asset->id,
        ]);
    }
}
