<?php

namespace Tests\Feature;

use App\Agent\NamespacedTool;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\PendingChanges;
use App\Models\Asset;
use App\Models\AssetPlatformRef;
use App\Models\Campaign;
use App\Models\CampaignChange;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * Every ad set can be edited, not only the first one.
 *
 * push_changes works by diffing the campaign's own attributes against the
 * snapshot taken at publish, and a campaign has one budget, one bid and one
 * schedule however many ad sets hang off it. MetaPublisher::byEntity() routes
 * those fields to the *primary* ad set by name. So a second ad set's settings
 * had nowhere to be expressed and could not be changed at all - the rows have
 * carried their own budget, bid, schedule and name since 5 Oct, and nothing
 * could reach them.
 *
 * This addresses an object by id instead of diffing, which makes every ad set
 * equal. It keeps the guards the campaign path has: approval, the change
 * cooldown and the daily cap, and an id that must belong to the campaign.
 */
class AnyAdSetCanBeEditedNotJustTheFirstTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

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

        config([
            'platforms.meta.token' => 'test-token',
            'platforms.meta.mcp.enabled' => false,
            'platforms.guardrails.allowed_ad_accounts' => ['meta:*'],
            'platforms.guardrails.paused' => false,
            // Pinned off, so the cooldown is tested where it is the subject and
            // does not refuse every other test in the file.
            'platforms.guardrails.change_cooldown_seconds' => 0,
            'platforms.guardrails.max_changes_per_day' => 20,
        ]);

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

        app(Workspace::class)->bindTo('conv-edit-entity');
        app(Workspace::class)->ownedBy($this->user);
    }

    /** A campaign with two published ad sets: the primary, and a second one. */
    private function campaign(array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Winter Sale',
            'platform' => 'meta',
            'status' => 'published',
            'objective' => 'OUTCOME_TRAFFIC',
            'ad_account_id' => 'act_111',
            'page_id' => 'page-1',
            'landing_url' => 'https://example.com/offer',
            'currency' => 'USD',
            'budget' => 25,
            'budget_mode' => 'daily',
            'budget_level' => 'ad_set',
            'external_campaign_id' => '120252047635070626',
            ...$attributes,
        ]);

        $campaign->primaryAdSet->update(['external_adset_id' => 'adset-1', 'status' => 'published']);
        $campaign->adSets()->create([
            'position' => 2,
            'name' => 'UK test',
            'budget' => 15,
            'budget_mode' => 'daily',
            'external_adset_id' => 'adset-2',
            'status' => 'published',
        ]);

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

        return $campaign->fresh();
    }

    /** The same campaign, plus a published ad row with an asset uploaded to the account. */
    private function campaignWithAd(): Campaign
    {
        $campaign = $this->campaign();

        $asset = Asset::create([
            'owner_type' => (new User)->getMorphClass(),
            'owner_id' => $this->user->id,
            'kind' => 'image', 'source' => 'generated', 'disk' => 'public',
            'path' => 'creatives/x.png', 'original_name' => 'x.png',
            'mime' => 'image/png', 'bytes' => 10, 'checksum' => 'sum',
        ]);

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

        $campaign->ads()->create([
            'headline' => 'Winter Sale',
            'primary_text' => 'Everything reduced.',
            'cta' => 'SHOP_NOW',
            'asset_id' => $asset->id,
            'external_ad_id' => 'ad-1',
            'external_creative_id' => 'creative-1',
            'status' => 'published',
        ]);

        // The same snapshot publishing takes, so the copy fingerprint in it is
        // real rather than absent - an absent one reports a rebuild regardless.
        $campaign = $campaign->fresh();
        $campaign->forceFill(['published_state' => app(PendingChanges::class)->snapshot($campaign)])->save();

        return $campaign->fresh();
    }

    /** An asset attached to this conversation and already uploaded to the account. */
    private function uploadedAsset(string $hash): Asset
    {
        $asset = Asset::create(['kind' => 'image', 'source' => 'upload', 'path' => 'assets/'.$hash.'.png']);

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

        app(Workspace::class)->produced($asset, focus: false);

        return $asset;
    }

    private function fakeMeta(): void
    {
        Http::fake([
            '*/adsets*' => Http::response(['data' => [['id' => 'adset-1'], ['id' => 'adset-2']]]),
            '*/ads*' => Http::response(['data' => [['id' => 'ad-1', 'adset_id' => 'adset-1']]]),
            '*/adcreatives*' => Http::response(['id' => 'creative-new']),
            '*' => Http::response(['success' => true]),
        ]);
    }

    /** @return list<array<string,mixed>> payloads posted to the creatives edge */
    private function creativesCreated(): array
    {
        $made = [];

        foreach (Http::recorded() as [$request]) {
            if ($request->method() === 'POST' && str_contains((string) $request->url(), '/adcreatives')) {
                $made[] = $request->data();
            }
        }

        return $made;
    }

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

        $this->assertNotNull($tool, 'campaign__edit_entity is not registered');

        return $tool;
    }

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

    /** @return array<string,mixed> fields sent to this object id */
    private function sentTo(string $id): array
    {
        foreach (Http::recorded() as [$request]) {
            if ($request->method() === 'POST' && str_ends_with((string) parse_url($request->url(), PHP_URL_PATH), '/'.$id)) {
                return $request->data();
            }
        }

        return [];
    }

    // ------------------------------------------------------ the second ad set

    /** The defect: the second ad set was unreachable. */
    public function test_the_second_ad_set_budget_can_be_changed(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-2', 'budget' => 40]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        // Minor units: Meta reads 40 as 40 cents.
        $this->assertSame(4000, $this->sentTo('adset-2')['daily_budget']);
    }

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

        $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-2', 'name' => 'UK test v2']);

        $this->assertSame('UK test v2', $this->sentTo('adset-2')['name']);
    }

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

        $this->edit([
            'entity_type' => 'ad_set',
            'id' => 'adset-2',
            'bid_strategy' => 'COST_CAP',
            'bid_amount' => 1.5,
            'ends_at' => '2026-12-31',
        ]);

        $sent = $this->sentTo('adset-2');

        $this->assertSame('COST_CAP', $sent['bid_strategy']);
        $this->assertSame(150, $sent['bid_amount']);
        $this->assertStringStartsWith('2026-12-31', $sent['end_time']);
        $this->assertSame([], $this->sentTo('adset-1'), 'the first ad set was changed instead');
    }

    /** The local row moves with it, so our copy matches the platform. */
    public function test_the_local_ad_set_row_is_updated(): void
    {
        $campaign = $this->campaign();
        $this->fakeMeta();

        $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-2', 'budget' => 40]);

        $this->assertSame('40.00', (string) $campaign->adSets()->where('external_adset_id', 'adset-2')->value('budget'));
    }

    /**
     * Editing the first ad set moves the campaign's mirrored attributes too.
     *
     * The campaign's own budget, bid and schedule mirror its first ad set, so
     * changing that one on the platform without moving them leaves
     * review_changes reporting a difference nobody made.
     */
    public function test_editing_the_first_ad_set_keeps_the_campaign_in_step(): void
    {
        $campaign = $this->campaign();
        $this->fakeMeta();

        $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-1', 'budget' => 30]);

        $this->assertSame('30.00', (string) $campaign->fresh()->budget);
        $this->assertSame(30, (int) ($campaign->fresh()->published_state['budget'] ?? 0));
    }

    /** And editing a later one leaves the campaign alone. */
    public function test_editing_a_later_ad_set_does_not_touch_the_campaign(): void
    {
        $campaign = $this->campaign();
        $this->fakeMeta();

        $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-2', 'budget' => 40]);

        $this->assertSame('25.00', (string) $campaign->fresh()->budget);
    }

    // ---------------------------------------------------------------- the ad

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

        $result = $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'name' => 'Winter Sale - ad A']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('Winter Sale - ad A', $this->sentTo('ad-1')['name']);
    }

    /** A field no level takes is still named rather than dropped. */
    public function test_a_field_no_level_takes_is_refused_with_the_reason(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'objective' => 'OUTCOME_SALES']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('objective', $result['error']);
        $this->assertSame([], $this->sentTo('ad-1'));
    }

    /** A field the level does not take is named, never dropped in silence. */
    public function test_an_ad_set_field_sent_to_an_ad_is_refused(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'budget' => 40]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('budget', $result['error']);
        $this->assertSame([], $this->sentTo('ad-1'));
    }

    // ------------------------------------------------------------- ad copy

    /**
     * New copy on a live ad, under the same ad id.
     *
     * The old refusal said ad copy "cannot be changed after publishing and needs
     * a new campaign". A creative is immutable on Meta; an ad is not. Pointing
     * the existing ad at a new creative keeps its id and its history, where
     * adding a second ad beside it does not.
     */
    public function test_new_copy_creates_a_creative_and_repoints_the_same_ad(): void
    {
        $this->campaignWithAd();
        $this->fakeMeta();

        $result = $this->edit([
            'entity_type' => 'ad',
            'id' => 'ad-1',
            'headline' => 'Everything half price',
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertNotEmpty($this->creativesCreated(), 'no new creative was made');
        $this->assertSame(
            json_encode(['creative_id' => 'creative-new']),
            $this->sentTo('ad-1')['creative'] ?? null,
            'the ad was not repointed at the new creative',
        );
    }

    /** The row carries the new wording, and the new creative id. */
    public function test_the_local_ad_row_records_the_new_copy_and_creative(): void
    {
        $campaign = $this->campaignWithAd();
        $this->fakeMeta();

        $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'headline' => 'Everything half price']);

        $ad = $campaign->ads()->where('external_ad_id', 'ad-1')->first();

        $this->assertSame('Everything half price', $ad->headline);
        $this->assertSame('creative-new', $ad->external_creative_id);
    }

    /** Learning resets when a creative changes, so the reply has to say so. */
    public function test_it_warns_that_learning_restarts(): void
    {
        $this->campaignWithAd();
        $this->fakeMeta();

        $result = $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'primary_text' => 'New body']);

        $this->assertStringContainsString('learning phase', $result['note']);
    }

    /** A refusal rolls the row back, so our copy never claims what the ad does not run. */
    public function test_a_refused_creative_leaves_the_old_copy_in_place(): void
    {
        $campaign = $this->campaignWithAd();

        Http::fake([
            '*/adsets*' => Http::response(['data' => [['id' => 'adset-1'], ['id' => 'adset-2']]]),
            '*/ads*' => Http::response(['data' => [['id' => 'ad-1', 'adset_id' => 'adset-1']]]),
            '*/adcreatives*' => Http::response(['error' => ['message' => 'Invalid creative']], 400),
            '*' => Http::response(['success' => true]),
        ]);

        $result = $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'headline' => 'Everything half price']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('still running its old copy', $result['note']);
        $this->assertSame('Winter Sale', $campaign->ads()->where('external_ad_id', 'ad-1')->value('headline'));
        $this->assertSame('creative-1', $campaign->ads()->where('external_ad_id', 'ad-1')->value('external_creative_id'));
    }

    public function test_a_named_campaign_rewrites_an_ad_that_is_not_stored_here(): void
    {
        $this->campaign();
        Http::fake(function ($request) {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);

            if (str_ends_with($path, '/120248690751510100') && $request->method() === 'GET') {
                return Http::response([
                    'id' => '120248690751510100',
                    'campaign_id' => '120248690751530100',
                    'account_id' => '111',
                    'creative' => [
                        'object_story_spec' => [
                            'page_id' => 'page-1',
                            'link_data' => [
                                'message' => 'Old body',
                                'name' => 'Old headline',
                                'link' => 'https://example.com/offer',
                            ],
                        ],
                    ],
                ]);
            }

            if (str_contains($path, '/adcreatives')) {
                return Http::response(['id' => 'creative-new']);
            }

            return Http::response(['success' => true]);
        });

        $result = $this->edit([
            'entity_type' => 'ad',
            'id' => '120248690751510100',
            'campaign_id' => '120248690751530100',
            'primary_text' => 'Researching stocks can be overwhelming.',
        ]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        $this->assertSame('creative-new', $result['creative_id']);
        $this->assertStringContainsString('learning phase', $result['note']);
        Http::assertSent(function ($request): bool {
            $path = (string) parse_url($request->url(), PHP_URL_PATH);
            $story = json_decode((string) ($request['object_story_spec'] ?? ''), true);

            return str_contains($path, '/adcreatives')
                && ($story['link_data']['message'] ?? null) === 'Researching stocks can be overwhelming.';
        });
    }

    /** An ad we have no row for cannot have its copy rewritten, and says why. */
    public function test_an_ad_with_no_local_row_is_refused_with_a_way_out(): void
    {
        $this->campaign();
        $this->fakeMeta();

        $result = $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'headline' => 'New']);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not recorded here', $result['error']);
        $this->assertStringContainsString('add_ads', $result['note']);
    }

    /**
     * A successful rewrite must not leave the campaign looking dirty forever.
     *
     * PendingChanges fingerprints ad copy at publish time and calls any later
     * difference a change that needs a whole new campaign. That was true before
     * this tool existed. If the snapshot is not moved on, one copy edit would
     * block every later budget or name push on that campaign, and the chat
     * would keep offering a rebuild for a change already made.
     */
    public function test_a_rewrite_does_not_leave_the_campaign_needing_a_rebuild(): void
    {
        $campaign = $this->campaignWithAd();
        $this->fakeMeta();

        $this->assertSame([], app(PendingChanges::class)->requiringRebuild($campaign));

        $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'headline' => 'Everything half price']);

        $this->assertSame(
            [],
            app(PendingChanges::class)->requiringRebuild($campaign->fresh()),
            'the campaign still reports a pending rebuild after the copy was changed on Meta',
        );
    }

    /** But a refused rewrite leaves the snapshot alone, since Meta never took it. */
    public function test_a_refused_rewrite_does_not_move_the_snapshot(): void
    {
        $campaign = $this->campaignWithAd();
        $before = $campaign->published_state['ads_fingerprint'];

        Http::fake([
            '*/adsets*' => Http::response(['data' => [['id' => 'adset-1'], ['id' => 'adset-2']]]),
            '*/ads*' => Http::response(['data' => [['id' => 'ad-1', 'adset_id' => 'adset-1']]]),
            '*/adcreatives*' => Http::response(['error' => ['message' => 'Invalid creative']], 400),
            '*' => Http::response(['success' => true]),
        ]);

        $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'headline' => 'Everything half price']);

        $this->assertSame($before, $campaign->fresh()->published_state['ads_fingerprint']);
    }

    /** Unrelated drift stays blocked: only the copy was made true, not everything. */
    public function test_it_does_not_bless_an_unrelated_pending_change(): void
    {
        $campaign = $this->campaignWithAd();
        $this->fakeMeta();

        $campaign->forceFill(['landing_url' => 'https://example.com/somewhere-else'])->save();

        $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'headline' => 'Everything half price']);

        $this->assertNotSame(
            [],
            app(PendingChanges::class)->requiringRebuild($campaign->fresh()),
            'changing ad copy quietly blessed a landing url change that needs a new campaign',
        );
    }

    /**
     * One fingerprint covers every ad, so fixing one must not clear the others.
     *
     * write_ad_copy rewrites all of a campaign's copy locally without touching
     * the platform. If a buyer does that on a live campaign and then rewrites
     * only the first ad through this tool, the other ads are still running
     * their old wording on Meta - and the rebuild notice has to stand until
     * each one has actually been pushed.
     */
    public function test_fixing_one_ad_does_not_clear_the_notice_for_ads_still_out_of_step(): void
    {
        $campaign = $this->campaignWithAd();
        $this->fakeMeta();

        $second = $campaign->ads()->create([
            'headline' => 'Second ad',
            'primary_text' => 'Other words.',
            'cta' => 'SHOP_NOW',
            'asset_id' => $campaign->ads()->first()->asset_id,
            'external_ad_id' => 'ad-2',
            'external_creative_id' => 'creative-2',
            'status' => 'published',
        ]);

        // Both ads rewritten locally, nothing pushed - what write_ad_copy does.
        $second->forceFill(['headline' => 'Rewritten locally'])->save();

        $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'headline' => 'Everything half price']);

        $this->assertNotSame(
            [],
            app(PendingChanges::class)->requiringRebuild($campaign->fresh()),
            'the second ad is still running its old copy on Meta but the campaign reports nothing pending',
        );
    }

    // --------------------------------------------------------- the image

    /**
     * A different uploaded image, under the same ad.
     *
     * The same mechanism as the wording: Meta cannot swap an image out of a
     * creative, but it will point an ad at a new creative built around a
     * different asset. attach_creatives used to write asset_id straight onto a
     * live ad's row, which changed our record and nothing else.
     */
    public function test_a_different_asset_rebuilds_the_creative_under_the_same_ad(): void
    {
        $campaign = $this->campaignWithAd();
        $other = $this->uploadedAsset('HASH456');
        $this->fakeMeta();

        $result = $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'asset_id' => $other->id]);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
        // The hash sits inside object_story_spec.link_data, which Meta takes as
        // an encoded string - so this asserts on the payload as sent.
        $this->assertStringContainsString(
            'HASH456',
            json_encode($this->creativesCreated()[0] ?? []),
            'the new creative was not built from the new asset',
        );
        $this->assertSame($other->id, $campaign->ads()->where('external_ad_id', 'ad-1')->value('asset_id'));
    }

    /** An id typed into the chat must not pull a stranger's upload onto the account. */
    public function test_an_asset_from_outside_the_conversation_is_refused(): void
    {
        $this->campaignWithAd();
        $stranger = Asset::create(['kind' => 'image', 'source' => 'upload', 'path' => 'assets/theirs.png']);
        $this->fakeMeta();

        $result = $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'asset_id' => $stranger->id]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not attached to this conversation', $result['error']);
        $this->assertSame([], $this->creativesCreated(), 'a creative was built from an asset we do not own');
    }

    /**
     * An asset never uploaded to the account is refused with the way out.
     *
     * creative() reads the account's own image hash off the platform ref, so
     * without one this is a null dereference inside the publisher rather than
     * an answer anyone can act on.
     */
    public function test_an_asset_not_yet_uploaded_to_the_account_is_refused(): void
    {
        $campaign = $this->campaignWithAd();

        $notUploaded = Asset::create(['kind' => 'image', 'source' => 'upload', 'path' => 'assets/local.png']);
        app(Workspace::class)->produced($notUploaded, focus: false);

        $this->fakeMeta();

        $result = $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'asset_id' => $notUploaded->id]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not been uploaded', $result['error']);
        $this->assertStringContainsString('review_assets', $result['note']);
        $this->assertSame([], $this->creativesCreated());
    }

    /** And a refusal leaves the ad pointing where it did. */
    public function test_a_refused_image_leaves_the_old_one_in_place(): void
    {
        $campaign = $this->campaignWithAd();
        $was = $campaign->ads()->where('external_ad_id', 'ad-1')->value('asset_id');

        $stranger = Asset::create(['kind' => 'image', 'source' => 'upload', 'path' => 'assets/theirs.png']);
        $this->fakeMeta();

        $this->edit(['entity_type' => 'ad', 'id' => 'ad-1', 'asset_id' => $stranger->id]);

        $this->assertSame($was, $campaign->ads()->where('external_ad_id', 'ad-1')->value('asset_id'));
    }

    // ------------------------------------------------------------- the guards

    public function test_it_is_approval_gated(): void
    {
        $this->assertInstanceOf(Approvable::class, $this->tool()->inner());
        $this->campaign();
        $this->fakeMeta();

        $this->assertNotNull($this->tool()->shouldRequestApproval(
            new Request(['entity_type' => 'ad_set', 'id' => 'adset-2', 'budget' => 40]),
        ));
    }

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

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-999', 'budget' => 40]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('not an ad set id or name in this campaign', $result['error']);
        $this->assertSame([], $this->sentTo('adset-999'));
    }

    /** The change cooldown applies here as it does to a campaign edit. */
    public function test_the_change_cooldown_is_honoured(): void
    {
        config(['platforms.guardrails.change_cooldown_seconds' => 600]);

        $campaign = $this->campaign();
        $this->fakeMeta();

        CampaignChange::create([
            'campaign_id' => $campaign->id,
            'actor' => 'tester',
            'changes' => [],
            'state' => 'applied',
            'applied_at' => now()->subSeconds(30),
        ]);

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-2', 'budget' => 40]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('limited to one every', $result['error']);
        $this->assertSame([], $this->sentTo('adset-2'));
    }

    /** Every attempt is written down, applied or not. */
    public function test_the_change_is_recorded(): void
    {
        $campaign = $this->campaign();
        $this->fakeMeta();

        $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-2', 'budget' => 40]);

        $change = CampaignChange::where('campaign_id', $campaign->id)->latest('id')->first();

        $this->assertSame('applied', $change->state);
        $this->assertSame(['budget' => 40], $change->changes['ad_set:adset-2']);
    }

    /** A platform refusal is recorded as failed and reported as nothing done. */
    public function test_a_refused_write_is_recorded_as_failed(): void
    {
        $campaign = $this->campaign();

        Http::fake(function (\Illuminate\Http\Client\Request $request) {
            $path = parse_url($request->url(), PHP_URL_PATH) ?? '';

            if ($request->method() === 'GET' && str_ends_with($path, '/adsets')) {
                return Http::response(['data' => [['id' => 'adset-1'], ['id' => 'adset-2']]]);
            }

            if ($request->method() === 'GET' && (str_ends_with($path, '/adset-1') || str_ends_with($path, '/adset-2'))) {
                return Http::response(['id' => 'adset-2', 'daily_budget' => '1500']);
            }

            if ($request->method() === 'GET') {
                return Http::response(['id' => '120252047635070626']);
            }

            return Http::response(['error' => ['message' => 'Invalid parameter']], 400);
        });

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-2', 'budget' => 40]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Nothing was changed', $result['note']);
        $this->assertSame('failed', CampaignChange::where('campaign_id', $campaign->id)->latest('id')->value('state'));
        $this->assertSame('15.00', (string) $campaign->adSets()->where('external_adset_id', 'adset-2')->value('budget'));
    }

    /** A campaign holding its own budget has none on the ad set to change. */
    public function test_a_campaign_budget_cannot_be_changed_through_an_ad_set(): void
    {
        $this->campaign(['budget_level' => 'campaign']);
        $this->fakeMeta();

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-2', 'budget' => 40]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('holds the budget itself', $result['error']);
        $this->assertSame([], $this->sentTo('adset-2'));
    }

    public function test_an_unpublished_campaign_is_refused_without_a_call(): void
    {
        $this->campaign(['external_campaign_id' => null, 'status' => 'draft']);
        Http::fake();

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-2', 'budget' => 40]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('nothing on Meta to change', $result['error']);
        Http::assertNothingSent();
    }

    public function test_nothing_to_change_is_refused_with_the_field_list(): void
    {
        $this->campaign();
        Http::fake();

        $result = $this->edit(['entity_type' => 'ad_set', 'id' => 'adset-2']);

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